Ejemplo n.º 1
0
        public static HotBitcoinAddress CreateUnique(Organization organization, BitcoinChain chain, params int[] derivationPath)
        {
            ExtPubKey extPubKey = BitcoinUtility.BitcoinHotPublicRoot;

            extPubKey = extPubKey.Derive((uint)organization.Identity);
            string derivationPathString = string.Empty;

            foreach (int derivation in derivationPath) // requires that order is consistent from 0 to n-1
            {
                extPubKey             = extPubKey.Derive((uint)derivation);
                derivationPathString += " " + derivation.ToString(CultureInfo.InvariantCulture);
            }

            derivationPathString = derivationPathString.TrimStart();

            int hotBitcoinAddressId =
                SwarmDb.GetDatabaseForWriting()
                .CreateHotBitcoinAddress(organization.Identity, chain, derivationPathString);

            HotBitcoinAddress addressTemp = FromIdentityAggressive(hotBitcoinAddressId);

            // Derive the last step with the now-assigned unique identifier, then set address, read again, and return

            extPubKey = extPubKey.Derive((uint)addressTemp.UniqueDerive);

            string bitcoinAddressString = extPubKey.PubKey.GetAddress(Network.Main).ToString();

            SwarmDb.GetDatabaseForWriting().SetHotBitcoinAddressAddress(hotBitcoinAddressId, bitcoinAddressString);

            return(FromIdentityAggressive(hotBitcoinAddressId));
        }
Ejemplo n.º 2
0
        private static PSBT BuildPsbt(Network network, HDFingerprint fingerprint, ExtPubKey xpub, KeyPath xpubKeyPath)
        {
            var deriveSendFromKeyPath = new KeyPath("1/0");
            var deriveSendToKeyPath   = new KeyPath("0/0");

            KeyPath sendFromKeyPath = xpubKeyPath.Derive(deriveSendFromKeyPath);
            KeyPath sendToKeyPath   = xpubKeyPath.Derive(deriveSendToKeyPath);

            PubKey sendFromPubKey = xpub.Derive(deriveSendFromKeyPath).PubKey;
            PubKey sendToPubKey   = xpub.Derive(deriveSendToKeyPath).PubKey;

            BitcoinAddress sendFromAddress = sendFromPubKey.GetAddress(ScriptPubKeyType.Segwit, network);
            BitcoinAddress sendToAddress   = sendToPubKey.GetAddress(ScriptPubKeyType.Segwit, network);

            TransactionBuilder builder = network.CreateTransactionBuilder();

            builder = builder.AddCoins(new Coin(uint256.One, 0, Money.Coins(1), sendFromAddress.ScriptPubKey));
            builder.Send(sendToAddress.ScriptPubKey, Money.Coins(0.99999m));
            PSBT psbt = builder
                        .SendFees(Money.Coins(0.00001m))
                        .BuildPSBT(false);

            var rootKeyPath1 = new RootedKeyPath(fingerprint, sendFromKeyPath);
            var rootKeyPath2 = new RootedKeyPath(fingerprint, sendToKeyPath);

            psbt.AddKeyPath(sendFromPubKey, rootKeyPath1, sendFromAddress.ScriptPubKey);
            psbt.AddKeyPath(sendToPubKey, rootKeyPath2, sendToAddress.ScriptPubKey);
            return(psbt);
        }
Ejemplo n.º 3
0
        static void MasterPublicKeyAndPrivateKey1(Network net, string words, string password)
        {
            Mnemonic mnemonic = new Mnemonic(words);

            ExtKey fatherKey = mnemonic.DeriveExtKey();

            ExtPubKey pubKey = fatherKey.Neuter();

            string wifStr = pubKey.Derive(0).ToString(net);

            Console.WriteLine(wifStr);
            Console.WriteLine();
            Console.WriteLine();

            for (int i = 0; i < 10; i++)
            {
                BitcoinAddress address1 = pubKey.Derive((uint)i).PubKey.GetAddress(ScriptPubKeyType.Legacy, net);
                Console.WriteLine(address1.ToString());
            }

            //var wiff = "";
            //for (int i = 0; i < 10; i++)
            //{
            //    ExtKey key = fatherKey.Derive((uint)i);
            //    var c = ("Key " + i + " : " + key.PrivateKey.GetBitcoinSecret(net).GetAddress(ScriptPubKeyType.Legacy).ToString() + " , wif:" + key.GetWif(net));
            //    var c1 = ("Key " + i + " : " + key.PrivateKey.GetBitcoinSecret(net).GetAddress(ScriptPubKeyType.Segwit).ToString() + " , wif:" + key.GetWif(net));
            //    var c2 = ("Key " + i + " : " + key.PrivateKey.GetBitcoinSecret(net).GetAddress(ScriptPubKeyType.SegwitP2SH).ToString() + " , wif:" + key.GetWif(net));
            //    Console.WriteLine(c);
            //    Console.WriteLine(c1);
            //    Console.WriteLine(c2);
            //}
        }
Ejemplo n.º 4
0
        public Proof GenerateProof(string hash)
        {
            var     settings    = DataService.GetSettings().ToList();
            var     lastKeyPath = settings.FirstOrDefault(x => x.Key == "KeyPath");
            var     feeSetting  = settings.FirstOrDefault(x => x.Key == "Fee");
            KeyPath keyPath;

            if (lastKeyPath != null)
            {
                keyPath = new KeyPath(lastKeyPath.Value);
                keyPath = keyPath.Increment();
            }
            else
            {
                keyPath = new KeyPath("0/0");
            }

            var newSettings = new List <Setting>
            {
                new Setting
                {
                    Key   = Constants.Settings.KeyPath,
                    Value = keyPath.ToString()
                }
            };

            int fee;

            if (feeSetting == null)
            {
                fee = Fee;
                newSettings.Add(new Setting
                {
                    Key   = Constants.Settings.Fee,
                    Value = Convert.ToString(fee)
                });
            }
            else
            {
                int.TryParse(feeSetting.Value, out fee);
                Fee = fee;
            }

            var pubKey    = _publicKey.Derive(keyPath).PubKey;
            var pubKeyStr = pubKey.ToHex();
            var address   = pubKey.GetAddress(Network.Main).ToString();
            var proof     = new Proof
            {
                PayAddress  = new WalletAddress(address, pubKeyStr, keyPath.ToString()),
                PayAmount   = fee,
                Hash        = hash,
                Status      = Constants.ProofStatus.PaymentPending,
                DateCreated = DateTime.Now
            };

            DataService.SaveSettings(newSettings);
            DataService.SaveProofs(new [] { proof });

            return(proof);
        }
Ejemplo n.º 5
0
        private void Code10()
        {
            ExtKey masterKey = new ExtKey();

            //Console.WriteLine("Master key : " + masterKey.ToString(Network.Main));
            for (int i = 0; i < 10; i++)
            {
                ExtKey key = masterKey.Derive((uint)i);
                //Console.WriteLine("Key " + i + " : " + key.ToString(Network.Main));
            }

            ExtPubKey masterPubKey = masterKey.Neuter();

            for (int i = 0; i < 10; i++)
            {
                ExtPubKey pubkey = masterPubKey.Derive((uint)i);
                //Console.WriteLine("PubKey " + i + " : " + pubkey.ToString(Network.Main));
            }

            masterKey    = new ExtKey();
            masterPubKey = masterKey.Neuter();

            //The payment server generate pubkey1
            ExtPubKey pubkey1 = masterPubKey.Derive((uint)1);

            //You get the private key of pubkey1
            ExtKey key1 = masterKey.Derive((uint)1);

            //Check it is legit
            //Console.WriteLine("Generated address : " + pubkey1.PubKey.GetAddress(Network.Main));
            //Console.WriteLine("Expected address : " + key1.Key.PubKey.GetAddress(Network.Main));

            ExtKey parent  = new ExtKey();
            ExtKey child11 = parent.Derive(new KeyPath("1/1"));


            ExtKey    ceoKey        = new ExtKey();
            ExtKey    accountingKey = ceoKey.Derive(0, hardened: true);
            ExtPubKey ceoPubkey     = ceoKey.Neuter();

            //Crash !
            ExtKey ceoKeyRecovered = accountingKey.GetParentExtKey(ceoPubkey);

            Console.WriteLine(ceoKey.ToString(Network.Main));
            Console.WriteLine(ceoKeyRecovered.ToString(Network.Main));

            ceoKey = new ExtKey();
            string  accounting = "1'";
            int     customerId = 5;
            int     paymentId  = 50;
            KeyPath path       = new KeyPath(accounting + "/" + customerId + "/" + paymentId);
            //Path : "1'/5/50"


            ExtKey paymentKey = ceoKey.Derive(path);

            var hardened    = new KeyPath("1/2/3'");
            var nonhardened = new KeyPath("1/2/3");
        }
Ejemplo n.º 6
0
 internal HDKeyManager(ExtPubKey extPubKey, KeyPath accountKeyPath, uint minGapLimit = AbsoluteMinGapLimit)
 {
     AccountKeyPath = accountKeyPath ?? DefaultAccountKeyPath;
     MinGapLimit    = minGapLimit;
     ExtPubKey      = extPubKey;
     ExternalKeys   = new KeysRegistry(extPubKey.Derive(0), AccountKeyPath.Derive(0), MinGapLimit);
     InternalKeys   = new KeysRegistry(extPubKey.Derive(1), AccountKeyPath.Derive(1), MinGapLimit);
 }
Ejemplo n.º 7
0
        public BitcoinAddress GetNewAddress()
        {
            var publickKey = _extPubKey.Derive(_keyDepth++).GetPublicKey();
            var address    = publickKey.GetAddress(ScriptPubKeyType.Segwit, Network);

            _scriptKeyMap.Add(address.ScriptPubKey, publickKey);
            return(address);
        }
Ejemplo n.º 8
0
        public void CanUseKeyPath()
        {
            KeyPath keyPath = KeyPath.Parse("0/1/2/3");

            Assert.Equal("0/1/2/3", keyPath.ToString());
            var key = new ExtKey();

            Assert.Equal(key
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(this.networkMain), key.Derive(keyPath).ToString(this.networkMain));

            ExtPubKey neuter = key.Neuter();

            Assert.Equal(neuter
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(this.networkMain), neuter.Derive(keyPath).ToString(this.networkMain));

            Assert.Equal(neuter.Derive(keyPath).ToString(this.networkMain), key.Derive(keyPath).Neuter().ToString(this.networkMain));

            keyPath = new KeyPath(new uint[] { 0x8000002Cu, 1u });
            Assert.Equal("44'/1", keyPath.ToString());

            keyPath = KeyPath.Parse("44'/1");
            Assert.False(keyPath.IsHardened);
            Assert.True(KeyPath.Parse("44'/1'").IsHardened);
            Assert.Equal(0x8000002Cu, keyPath[0]);
            Assert.Equal(1u, keyPath[1]);

            key = new ExtKey();
            Assert.Equal(key.Derive(keyPath).ToString(this.networkMain), key.Derive(44, true).Derive(1, false).ToString(this.networkMain));

            keyPath = KeyPath.Parse("");
            keyPath = keyPath.Derive(44, true).Derive(1, false);
            Assert.Equal("44'/1", keyPath.ToString());
            Assert.Equal("44'/2", keyPath.Increment().ToString());
            Assert.Equal("44'/1/2'", keyPath.Derive(1, true).Increment().ToString());
            Assert.Equal("44'", keyPath.Parent.ToString());
            Assert.Equal("", keyPath.Parent.Parent.ToString());
            Assert.Null(keyPath.Parent.Parent.Parent);
            Assert.Null(keyPath.Parent.Parent.Increment());
            Assert.Equal(key.Derive(keyPath).ToString(this.networkMain), key.Derive(44, true).Derive(1, false).ToString(this.networkMain));

            Assert.True(key.Derive(44, true).IsHardened);
            Assert.False(key.Derive(44, false).IsHardened);

            neuter = key.Derive(44, true).Neuter();
            Assert.True(neuter.IsHardened);
            neuter = key.Derive(44, false).Neuter();
            Assert.False(neuter.IsHardened);
        }
Ejemplo n.º 9
0
        private byte[][] GetScripts(bool isInternal, int offset, int count)
        {
            var change  = isInternal ? 1 : 0;
            var scripts = new byte[count][];

            for (var i = 0; i < count; i++)
            {
                var pubKey = _extPubKey.Derive(change, false).Derive(offset + i, false).PubKey;
                var bytes  = pubKey.WitHash.ScriptPubKey.ToCompressedBytes();
                scripts[i] = bytes;
            }
            return(scripts);
        }
Ejemplo n.º 10
0
        /// <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);
        }
Ejemplo n.º 11
0
        private void RunTest(TestVector test)
        {
            var       seed   = TestUtils.ParseHex(test.strHexMaster);
            ExtKey    key    = new ExtKey(seed);
            ExtPubKey pubkey = key.Neuter();

            foreach (TestDerivation derive in test.vDerive)
            {
                byte[] data = key.ToBytes();
                Assert.Equal(74, data.Length);
                data = pubkey.ToBytes();
                Assert.Equal(74, data.Length);
                // Test private key
                BitcoinExtKey b58key   = Network.Main.CreateBitcoinExtKey(key);
                var           a        = Encoders.Hex.EncodeData(Encoders.Base58Check.DecodeData(b58key.ToString()));
                var           expected = Encoders.Hex.EncodeData(Encoders.Base58Check.DecodeData(derive.prv));
                Assert.True(b58key.ToString() == derive.prv);
                // Test public key
                BitcoinExtPubKey b58pubkey = Network.Main.CreateBitcoinExtPubKey(pubkey);
                Assert.True(b58pubkey.ToString() == derive.pub);
                // Derive new keys
                ExtKey    keyNew    = key.Derive(derive.nChild);
                ExtPubKey pubkeyNew = keyNew.Neuter();
                if (!((derive.nChild & 0x80000000) != 0))
                {
                    // Compare with public derivation
                    ExtPubKey pubkeyNew2 = pubkey.Derive(derive.nChild);
                    Assert.True(pubkeyNew == pubkeyNew2);
                }
                key    = keyNew;
                pubkey = pubkeyNew;
            }
        }
Ejemplo n.º 12
0
        private void a_wallet_with_funds_at_index_20_which_is_beyond_default_gap_limit()
        {
            ExtPubKey xPublicKey = this.GetExtendedPublicKey(this.receivingStratisBitcoinNode);
            var       recipientAddressBeyondGapLimit = xPublicKey.Derive(new KeyPath("0/20")).PubKey.GetAddress(KnownNetworks.RegTest);

            TransactionBuildContext transactionBuildContext = TestHelper.CreateTransactionBuildContext(
                this.sendingStratisBitcoinNode.FullNode.Network,
                WalletName,
                AccountZero,
                WalletPassword,
                new[] {
                new Recipient {
                    Amount       = Money.COIN * 1,
                    ScriptPubKey = recipientAddressBeyondGapLimit.ScriptPubKey
                }
            },
                FeeType.Medium, 0);

            var transaction = this.sendingStratisBitcoinNode.FullNode.WalletTransactionHandler()
                              .BuildTransaction(transactionBuildContext);

            this.sendingStratisBitcoinNode.FullNode.NodeController <WalletController>()
            .SendTransaction(new SendTransactionRequest(transaction.ToHex()));

            TestHelper.MineBlocks(this.sendingStratisBitcoinNode, 1);
        }
Ejemplo n.º 13
0
        public async Task <KeyPath> GetWalletHDKeyPathForSegwitAddressAsync(KeyPath rootKeyPath, string segwitAddress, Network network, int startAtIndex = 0, int?maxAttempts = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Guard.AssertKeyPath(rootKeyPath);

            GetWalletPubKeyResponse response = await GetWalletPubKeyAsync(rootKeyPath);

            ExtPubKey hdKey = response.ExtendedPublicKey;

            var i = startAtIndex;
            var a = 0L;

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var keyPath = new KeyPath($"0/{i}");

                var segwit = $"{hdKey.Derive(keyPath).PubKey.WitHash.ScriptPubKey.Hash.GetAddress(network)}";
                if (segwit == segwitAddress)
                {
                    return(keyPath);
                }

                i++;
                a++;

                if (a > maxAttempts)
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 14
0
        private void AddInputs(Transaction transaction, ExtPubKey pubKey, List <Coin> coins, int addressNumber, ref int index, Money money)
        {
            Base58CheckEncoder base58CheckEncoder = new Base58CheckEncoder();
            var    bytes = base58CheckEncoder.DecodeData(pubKey.GetWif(Network.Main).ToString());
            string hex   = BitConverter.ToString(bytes).Replace("-", "").ToLower();

            Money spentMoney = Money.Zero;

            for (int i = 0; i < coins.Count; i++)
            {
                transaction.AddInput(new TxIn(coins[i].Outpoint));
                var s = "01ff4c53ff" + hex + "0000"
                        + (addressNumber > 9 ? addressNumber.ToString() : "0" + addressNumber) + "00";
                transaction.Inputs[i + index].ScriptSig = new Script(s);

                spentMoney += coins[i].Amount;

                if (spentMoney >= money)
                {
                    if (spentMoney - money > 0)
                    {
                        transaction.AddOutput(spentMoney - money, pubKey.Derive(0).Derive((uint)addressNumber).PubKey.Hash);
                    }

                    index = i + 1;
                    return;
                }
            }

            index = coins.Count;
        }
Ejemplo n.º 15
0
        public string DeriveNewAddress(ExtPubKey rootXPubKey, KeyPath keyPath)
        {
            var key     = rootXPubKey.Derive(keyPath);
            var address = key.GetPublicKey().GetAddress(NetworkOperator.Instance.Network).ToString();

            return(address);
        }
Ejemplo n.º 16
0
            public Derivation Derive(uint i)
            {
                var pubKey = rootDerivation.Derive(i).PubKey;

                return(new Derivation()
                {
                    ScriptPubKey = up.Segwit ? pubKey.WitHash.ScriptPubKey : pubKey.Hash.ScriptPubKey
                });
            }
Ejemplo n.º 17
0
        private HDPubKey DerivePubKeyFromIndex(int index, string knownBy)
        {
            var path     = new KeyPath((uint)index);
            var fullPath = AccountKeyPath.Derive((uint)index);
            var pubKey   = ExtPubKey.Derive(path).PubKey;
            var hdPubKey = new HDPubKey(pubKey, fullPath, knownBy);

            return(hdPubKey);
        }
Ejemplo n.º 18
0
        public void CreateAddresses()         //use this to create your own keys\addresses
        {
            //create random ext key
            ExtKey    pvtKey     = new ExtKey();
            string    extPrvKey  = (pvtKey).GetWif(Network.TestNet).ToString();                              //extended private key, can derive all addresses\keys from this
            ExtPubKey pubKey     = pvtKey.Neuter();                                                          //extended public key, can derive all public addresses from this
            string    extPubKey  = (pubKey).GetWif(Network.TestNet).ToString();                              //extended public key string
            string    pvtSrcKey  = pvtKey.Derive(0).Derive(0).PrivateKey.ToString(Network.TestNet);          //need this to spend btc
            string    pubSrcAddr = pubKey.Derive(0).Derive(0).PubKey.GetAddress(Network.TestNet).ToString(); //source from bitcoin fountain (or USD)
            string    pubRecAddr = pubKey.Derive(0).Derive(1).PubKey.GetAddress(Network.TestNet).ToString(); //use to receive funds
            string    pubChgAddr = pubKey.Derive(1).Derive(0).PubKey.GetAddress(Network.TestNet).ToString(); //use as change address

            UpdateStatus("extPrvKey : " + extPrvKey);
            UpdateStatus("extPubKey : " + extPubKey);
            UpdateStatus("pvtSrcKey : " + pvtSrcKey);
            UpdateStatus("pubSrcAddr : " + pubSrcAddr);
            UpdateStatus("pubRecAddr : " + pubRecAddr);
            UpdateStatus("pubChgAddr : " + pubChgAddr);
        }
Ejemplo n.º 19
0
        public HdPubKey GenerateNewKey(SmartLabel label, KeyState keyState, bool isInternal, bool toFile = true)
        {
            // BIP44-ish derivation scheme
            // m / purpose' / coin_type' / account' / change / address_index
            var change = isInternal ? 1 : 0;

            lock (HdPubKeysLock)
            {
                HdPubKey[] relevantHdPubKeys = HdPubKeys.Where(x => x.IsInternal == isInternal).ToArray();

                KeyPath path = new KeyPath($"{change}/0");
                if (relevantHdPubKeys.Any())
                {
                    int largestIndex         = relevantHdPubKeys.Max(x => x.Index);
                    var smallestMissingIndex = largestIndex;
                    var present = new bool[largestIndex + 1];
                    for (int i = 0; i < relevantHdPubKeys.Length; ++i)
                    {
                        present[relevantHdPubKeys[i].Index] = true;
                    }
                    for (int i = 1; i < present.Length; ++i)
                    {
                        if (!present[i])
                        {
                            smallestMissingIndex = i - 1;
                            break;
                        }
                    }

                    path = relevantHdPubKeys[smallestMissingIndex].NonHardenedKeyPath.Increment();
                }

                var fullPath = AccountKeyPath.Derive(path);
                var pubKey   = ExtPubKey.Derive(path).PubKey;

                var hdPubKey = new HdPubKey(pubKey, fullPath, label, keyState);
                HdPubKeys.Add(hdPubKey);
                lock (HdPubKeyScriptBytesLock)
                {
                    HdPubKeyScriptBytes.Add(hdPubKey.P2wpkhScript.ToCompressedBytes());
                }

                lock (ScriptHdPubKeyMapLock)
                {
                    ScriptHdPubKeyMap.Add(hdPubKey.P2wpkhScript, hdPubKey);
                }

                if (toFile)
                {
                    ToFile();
                }

                return(hdPubKey);
            }
        }
Ejemplo n.º 20
0
        public HdPubKey GenerateNewKey(string label, KeyState keyState, bool isInternal, bool toFile = true)
        {
            // BIP44-ish derivation scheme
            // m / purpose' / coin_type' / account' / change / address_index
            var change = isInternal ? 1 : 0;

            lock (HdPubKeysLock)
            {
                IEnumerable <HdPubKey> relevantHdPubKeys = isInternal ? HdPubKeys.Where(x => x.IsInternal) : HdPubKeys.Where(x => !x.IsInternal);

                KeyPath path;
                if (relevantHdPubKeys.Any())
                {
                    int        largestIndex   = relevantHdPubKeys.Max(x => x.Index);
                    List <int> missingIndexes = Enumerable.Range(0, largestIndex).Except(relevantHdPubKeys.Select(x => x.Index)).ToList();
                    if (missingIndexes.Any())
                    {
                        int smallestMissingIndex = missingIndexes.Min();
                        path = relevantHdPubKeys.First(x => x.Index == (smallestMissingIndex - 1)).NonHardenedKeyPath.Increment();
                    }
                    else
                    {
                        path = relevantHdPubKeys.First(x => x.Index == largestIndex).NonHardenedKeyPath.Increment();
                    }
                }
                else
                {
                    path = new KeyPath($"{change}/0");
                }

                var fullPath = AccountKeyPath.Derive(path);
                var pubKey   = ExtPubKey.Derive(path).PubKey;

                var hdPubKey = new HdPubKey(pubKey, fullPath, label, keyState);
                HdPubKeys.Add(hdPubKey);
                lock (HdPubKeyScriptBytesLock)
                {
                    HdPubKeyScriptBytes.Add(hdPubKey.P2wpkhScript.ToCompressedBytes());
                }

                lock (ScriptHdPubKeyMapLock)
                {
                    ScriptHdPubKeyMap.Add(hdPubKey.P2wpkhScript, hdPubKey);
                }

                if (toFile)
                {
                    ToFile();
                }

                return(hdPubKey);
            }
        }
Ejemplo n.º 21
0
        public void GeneratePubkey()
        {
            var network = Network.RegTest;

            ExtKey masterKey = new ExtKey();

            Console.WriteLine("Master key : " + masterKey.ToString(network));
            ExtPubKey masterPubKey = masterKey.Neuter();

            ExtPubKey pubkey = masterPubKey.Derive(0);

            Console.WriteLine("PubKey " + 0 + " : " + pubkey.ToString(network));
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
        private int FindPubKey(ExtPubKey xpubKey, PubKey pubKey)
        {
            var receive = xpubKey.Derive(0);

            for (int i = 0; i < 100; i++)
            {
                if (receive.Derive((uint)i).PubKey.ToHex() == pubKey.ToHex())
                {
                    return(i);
                }
            }

            throw new ArgumentException("Pubkey not found");
        }
Ejemplo n.º 24
0
        public static HotBitcoinAddress Create(Organization organization, BitcoinChain chain, params int[] derivationPath)
        {
            ExtPubKey extPubKey = BitcoinUtility.BitcoinHotPublicRoot;

            extPubKey = extPubKey.Derive((uint)organization.Identity);
            string derivationPathString = string.Empty;

            foreach (int derivation in derivationPath) // requires that order is consistent from 0 to n-1
            {
                extPubKey             = extPubKey.Derive((uint)derivation);
                derivationPathString += " " + derivation.ToString(CultureInfo.InvariantCulture);
            }

            derivationPathString = derivationPathString.TrimStart();
            string bitcoinAddress = extPubKey.PubKey.GetAddress(Network.Main).ToString();    // TODO: CHANGE NETWORK.MAIN TO NEW LOOKUP
            // string bitcoinAddressFallback = extPubKey.PubKey.GetAddress(Network.Main).ToString(); // The fallback address would be the main address

            int hotBitcoinAddressId =
                SwarmDb.GetDatabaseForWriting()
                .CreateHotBitcoinAddressConditional(organization.Identity, chain, derivationPathString, bitcoinAddress);

            return(FromIdentityAggressive(hotBitcoinAddressId));
        }
Ejemplo n.º 25
0
 public SyncWallet(WalletSettings settings, Network network)
 {
     _masterPrivKey = ExtKey.Parse(settings.MasterPrivKey);
     _masterPubKey  = _masterPrivKey.Neuter();
     _keyPath       = settings.KeyPath ?? new KeyPath("0/0");
     _curPath       = new KeyPath(_keyPath.Indexes);
     for (var index = 0; index < 1; index++)
     {
         var pubkey  = _masterPubKey.Derive(_curPath).PubKey;
         var address = new SyncAddress(pubkey, _curPath, network);
         _addresses.Add(address);
         _curPath = _curPath.Increment();
     }
     //_keyPath.Increment();
 }
Ejemplo n.º 26
0
    /// <summary>
    /// Method used for initializing all the addresses for this hardware wallet.
    /// </summary>
    public async void InitializeAddresses()
    {
        addresses[0] = new string[50];
        addresses[1] = new string[50];

        var data = await GetExtendedPublicKeyData().ConfigureAwait(false);

        if (data == null || data.chainCodeData.Length != 32)
        {
            MainThreadExecutor.QueueAction(WalletLoadUnsuccessful);
            return;
        }

        var electrumLedgerXPub = new ExtPubKey(new PubKey(data.publicKeyData).Compress(), data.chainCodeData);
        var defaultXPub        = electrumLedgerXPub.Derive(0);

        for (uint i = 0; i < addresses[0].Length; i++)
        {
            addresses[0][i] = new EthECKey(defaultXPub.Derive(i).PubKey.ToBytes(), false).GetPublicAddress().ConvertToEthereumChecksumAddress();
            addresses[1][i] = new EthECKey(electrumLedgerXPub.Derive(i).PubKey.ToBytes(), false).GetPublicAddress().ConvertToEthereumChecksumAddress();
        }

        MainThreadExecutor.QueueAction(WalletLoadSuccessful);
    }
Ejemplo n.º 27
0
        //get child keys (addresses) for given extended private key
        public static string[] GetDerivedKeysPvt(string extPrivateKey, uint start, uint cnt, bool testnet)
        {
            CheckNullOrEmpty(new object[] { extPrivateKey }, new string[] { "extPrivateKey" });

            Network   ntwk = testnet ? Network.TestNet : Network.Main;
            ExtKey    k    = ExtKey.Parse(extPrivateKey);
            ExtPubKey pk   = k.Neuter();           //get public ext key

            string[] res = new string[cnt];
            for (uint ctr = start; ctr < cnt; ctr++)
            {
                //return Private and Public key pair
                res[ctr] = k.Derive(ctr).PrivateKey.ToString(ntwk) + ":" + pk.Derive(ctr).PubKey.GetAddress(ntwk);
            }
            return(res);
        }
Ejemplo n.º 28
0
        private Tuple <PubKey, int, List <Coin> > GetPubKey(ExtPubKey extPubKey, Money amount)
        {
            var receive = extPubKey.Derive(0);

            for (int i = 0; i < 100; i++)
            {
                var item  = receive.Derive((uint)i).PubKey;
                var coins = this.GetUnspentCoins(item);
                this.GetBalances(coins, out Money confBalance, out Money unconfBalance);
                if (confBalance >= amount)
                {
                    return(new Tuple <PubKey, int, List <Coin> >(item, i, coins.Select(pair => pair.Key).ToList()));
                }
            }

            return(null);
        }
Ejemplo n.º 29
0
        public HdPubKey GenerateNewKey(string label, KeyState keyState, bool isInternal, bool toFile = true)
        {
            // BIP44-ish derivation scheme
            // m / purpose' / coin_type' / account' / change / address_index
            lock (HdPubKeysLock)
            {
                var change = isInternal ? 1 : 0;

                IEnumerable <HdPubKey> relevantHdPubKeys;
                if (isInternal)
                {
                    relevantHdPubKeys = HdPubKeys.Where(x => x.IsInternal());
                }
                else
                {
                    relevantHdPubKeys = HdPubKeys.Where(x => !x.IsInternal());
                }

                KeyPath path;
                if (!relevantHdPubKeys.Any())
                {
                    path = new KeyPath($"{change}/0");
                }
                else
                {
                    path = relevantHdPubKeys.OrderBy(x => x.GetIndex()).Last().GetNonHardenedKeyPath().Increment();
                }

                var fullPath = AccountKeyPath.Derive(path);
                var pubKey   = ExtPubKey.Derive(path).PubKey;

                var hdPubKey = new HdPubKey(pubKey, fullPath, label, keyState);
                HdPubKeys.Add(hdPubKey);

                if (toFile)
                {
                    ToFile();
                }

                return(hdPubKey);
            }
        }
Ejemplo n.º 30
0
        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            BitcoinExtPubKey bitcoinExtPubKey;
            ExtPubKey        extPubKey;

            switch (cboCoin.SelectedValue)
            {
            case "BTC - Bitcoin (BIP-44)":
                bitcoinExtPubKey = new BitcoinExtPubKey(txtInput.Text, Network.Main);
                extPubKey        = new ExtPubKey(bitcoinExtPubKey.ToBytes());
                txtAddress.Text  = extPubKey.Derive(Convert.ToUInt32(cboIndex.SelectedValue)).PubKey.ToString(Network.Main);
                break;

            case "BTC - Bitcoin (BIP-49)":
                bitcoinExtPubKey = new BitcoinExtPubKey(txtInput.Text, Network.Main);
                extPubKey        = new ExtPubKey(bitcoinExtPubKey.ToBytes());
                txtAddress.Text  = extPubKey.Derive(Convert.ToUInt32(cboIndex.SelectedValue)).PubKey.WitHash.GetAddress(Network.Main).GetScriptAddress().ToString();
                break;
            }
        }