Exemplo n.º 1
0
        public void CanTrack3()
        {
            using (var tester = ServerTester.Create())
            {
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());
                tester.Client.Track(pubkey);
                tester.Client.GetUTXOs(pubkey, null, false);                 //Track things do not wait
                var events = tester.Client.CreateNotificationSession();
                events.ListenDerivationSchemes(new[] { pubkey });

                var id = tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(1.0m));
                id = tester.RPC.SendToAddress(AddressOf(key, "0/1"), Money.Coins(1.1m));
                id = tester.RPC.SendToAddress(AddressOf(key, "0/2"), Money.Coins(1.2m));
                id = tester.RPC.SendToAddress(AddressOf(key, "0"), Money.Coins(1.2m));
                id = tester.RPC.SendToAddress(AddressOf(key, "1"), Money.Coins(1.2m));

                events.NextEvent(Timeout);
                events.NextEvent(Timeout);
                events.NextEvent(Timeout);
                events.NextEvent(Timeout);
                events.NextEvent(Timeout);
                var utxo = tester.Client.GetUTXOs(pubkey, null);

                tester.RPC.Generate(1);

                var prev = utxo;
                utxo = tester.Client.GetUTXOs(pubkey, prev);
                Assert.True(utxo.HasChanges);
                Assert.Equal(5, utxo.Confirmed.UTXOs.Count);
                utxo = tester.Client.GetUTXOs(pubkey, utxo, false);
                Assert.False(utxo.HasChanges);
            }
        }
Exemplo n.º 2
0
 public override bool TryParse(string str, Network network, Type targetType, out IBitcoinString result)
 {
     if (str.StartsWith("xprv", StringComparison.OrdinalIgnoreCase) && targetType.GetTypeInfo().IsAssignableFrom(typeof(BitcoinExtKey).GetTypeInfo()))
     {
         try
         {
             result = new BitcoinExtKey(str, network);
             return(true);
         }
         catch
         {
         }
     }
     if (str.StartsWith("xpub", StringComparison.OrdinalIgnoreCase) && targetType.GetTypeInfo().IsAssignableFrom(typeof(BitcoinExtPubKey).GetTypeInfo()))
     {
         try
         {
             result = new BitcoinExtPubKey(str, network);
             return(true);
         }
         catch
         {
         }
     }
     return(base.TryParse(str, network, targetType, out result));
 }
        /// <summary>
        /// Loads all the private keys for each of the <see cref="HdAddress"/> in <see cref="TransactionBuildContext.UnspentOutputs"/>
        /// </summary>
        /// <param name="context">The context associated with the current transaction being built.</param>
        /// <param name="coinsSpent">The coins spent to generate the transaction.</param>
        protected void AddSecrets(TransactionBuildContext context, IEnumerable <ICoin> coinsSpent)
        {
            if (!context.Sign)
            {
                return;
            }

            Wallet wallet     = this.walletManager.GetWalletByName(context.AccountReference.WalletName);
            ExtKey seedExtKey = this.walletManager.GetExtKey(context.AccountReference, context.WalletPassword, context.CacheSecret);

            var signingKeys = new HashSet <ISecret>();
            var added       = new HashSet <HdAddress>();

            foreach (Coin coinSpent in coinsSpent)
            {
                //obtain the address relative to this coin (must be improved)
                HdAddress address = context.UnspentOutputs.First(output => output.ToOutPoint() == coinSpent.Outpoint).Address;

                if (added.Contains(address))
                {
                    continue;
                }

                ExtKey        addressExtKey     = seedExtKey.Derive(new KeyPath(address.HdPath));
                BitcoinExtKey addressPrivateKey = addressExtKey.GetWif(wallet.Network);
                signingKeys.Add(addressPrivateKey);
                added.Add(address);
            }

            context.TransactionBuilder.AddKeys(signingKeys.ToArray());
        }
Exemplo n.º 4
0
        public AccountHDWallet(string accountMasterKey, uint accountIndex)
        {
            BitcoinExtKey bitcoinExtKey = new BitcoinExtKey(accountMasterKey);

            _masterKey    = bitcoinExtKey.ExtKey;
            _accountIndex = accountIndex;
        }
Exemplo n.º 5
0
        public async Task <StoresController> CreateStoreAsync()
        {
            ExtKey = new ExtKey().GetWif(parent.Network);
            var store = parent.PayTester.GetController <StoresController>(UserId);
            await store.CreateStore(new CreateStoreViewModel()
            {
                Name = "Test Store"
            });

            StoreId          = store.CreatedStoreId;
            DerivationScheme = new DerivationStrategyFactory(parent.Network).Parse(ExtKey.Neuter().ToString() + "-[legacy]");
            await store.UpdateStore(StoreId, new StoreViewModel()
            {
                SpeedPolicy = SpeedPolicy.MediumSpeed
            });

            await store.AddDerivationScheme(StoreId, new DerivationSchemeViewModel()
            {
                CryptoCurrency         = "BTC",
                DerivationSchemeFormat = "BTCPay",
                DerivationScheme       = DerivationScheme.ToString(),
            }, "Save");

            return(store);
        }
Exemplo n.º 6
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;
            }
        }
Exemplo n.º 7
0
        public void CanTrack3()
        {
            using (var tester = ServerTester.Create())
            {
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());
                tester.Client.Track(pubkey);
                tester.Client.Sync(pubkey, null, null, true);                 //Track things do not wait
                var id = tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(1.0m));
                id = tester.RPC.SendToAddress(AddressOf(key, "0/1"), Money.Coins(1.1m));
                id = tester.RPC.SendToAddress(AddressOf(key, "0/2"), Money.Coins(1.2m));

                UTXOChanges utxo = null;

                while (utxo == null || utxo.Unconfirmed.UTXOs.Count != 3)
                {
                    utxo = tester.Client.Sync(pubkey, null, null);
                }

                tester.RPC.Generate(1);

                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.True(utxo.HasChanges);
                Assert.Equal(3, utxo.Confirmed.UTXOs.Count);
                utxo = tester.Client.Sync(pubkey, utxo, true);
                Assert.False(utxo.HasChanges);
            }
        }
 public ActionResult DepositBTC()
 {
     try
     {
         if (Session["MemberInfomation"] != null)
         {
             MemberInformationBO member = (MemberInformationBO)Session["MemberInfomation"];
             int    intIndexWallet      = member.IndexWallet;
             string strClientExtKey     = masterKey;
             RandomUtils.Random = new UnsecureRandom();
             ExtKey masterPubKey     = new BitcoinExtKey(strClientExtKey, Network.TestNet);
             ExtKey pubkey           = masterPubKey.Derive(intIndexWallet, hardened: true);
             var    strWalletAddress = pubkey.PrivateKey.GetBitcoinSecret(Network.TestNet).GetAddress().ToString();
             ViewBag.WalletAddress = strWalletAddress;
             string strQRCode = Utility.GenQRCode(strWalletAddress);
             ViewBag.DataQRCode = "data:image/png;base64," + strQRCode + "";
         }
         else
         {
             ViewBag.WalletAddress = "00000000000000";
             ViewBag.DataQRCode    = "data:image/png;base64," + 00000000000000 + "";
         }
     }
     catch
     {
         ViewBag.WalletAddress = "00000000000000";
         ViewBag.DataQRCode    = "data:image/png;base64," + 00000000000000 + "";
     }
     return(PartialView());
 }
Exemplo n.º 9
0
		public void CanRebaseKeypathInPSBT()
		{
			var masterExtkey = new BitcoinExtKey("tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF", Network.TestNet);
			var masterFP = masterExtkey.GetPublicKey().GetHDFingerPrint();
			var accountExtKey = masterExtkey.Derive(new KeyPath("0'/0'/0'"));
			var accountRootedKeyPath = new KeyPath("0'/0'/0'").ToRootedKeyPath(masterExtkey);
			uint hardenedFlag = 0x80000000U;
			retry:
			Transaction funding = masterExtkey.Network.CreateTransaction();
			funding.Outputs.Add(Money.Coins(2.0m), accountExtKey.Derive(0 | hardenedFlag).ScriptPubKey);
			funding.Outputs.Add(Money.Coins(2.0m), accountExtKey.Derive(1 | hardenedFlag).ScriptPubKey);

			Transaction tx = masterExtkey.Network.CreateTransaction();
			tx.Version = 2;
			tx.Outputs.Add(Money.Coins(1.49990000m), new Script(Encoders.Hex.DecodeData("0014d85c2b71d0060b09c9886aeb815e50991dda124d")));
			tx.Outputs.Add(Money.Coins(1.00000000m), new Script(Encoders.Hex.DecodeData("001400aea9a2e5f0f876a588df5546e8742d1d87008f")));
			tx.Inputs.Add(funding, 0);
			tx.Inputs.Add(funding, 1);

			var psbt = PSBT.FromTransaction(tx, Network.TestNet);
			psbt.AddTransactions(funding);
			psbt.AddKeyPath(accountExtKey, Tuple.Create(new KeyPath(0 | hardenedFlag), funding.Outputs[0].ScriptPubKey), 
										   Tuple.Create(new KeyPath(1 | hardenedFlag), funding.Outputs[1].ScriptPubKey));
			Assert.Equal(new KeyPath(0 | hardenedFlag), psbt.Inputs[0].HDKeyPaths[accountExtKey.Derive(0 | hardenedFlag).GetPublicKey()].KeyPath);
			Assert.Equal(new KeyPath(1 | hardenedFlag), psbt.Inputs[1].HDKeyPaths[accountExtKey.Derive(1 | hardenedFlag).GetPublicKey()].KeyPath);
			Assert.Equal(accountExtKey.GetPublicKey().GetHDFingerPrint(), psbt.Inputs[0].HDKeyPaths[accountExtKey.Derive(0 | hardenedFlag).GetPublicKey()].MasterFingerprint);
			Assert.Equal(accountExtKey.GetPublicKey().GetHDFingerPrint(), psbt.Inputs[1].HDKeyPaths[accountExtKey.Derive(1 | hardenedFlag).GetPublicKey()].MasterFingerprint);

			var memento = psbt.Clone();
			psbt.GlobalXPubs.Add(accountExtKey.Neuter(), new RootedKeyPath(accountExtKey, new KeyPath()));
			var rebasingKeyPath = new RootedKeyPath(masterExtkey.GetPublicKey().GetHDFingerPrint(), new KeyPath("0'/0'/0'"));
			psbt.RebaseKeyPaths(accountExtKey, rebasingKeyPath);
			Assert.Equal(psbt.GlobalXPubs.Single().Value, rebasingKeyPath);
			psbt.ToString();
			psbt = PSBT.Parse(psbt.ToHex(), psbt.Network);
			Assert.Equal(psbt.GlobalXPubs.Single().Value, rebasingKeyPath);
			Assert.Equal(new KeyPath("0'/0'/0'").Derive(0 | hardenedFlag), psbt.Inputs[0].HDKeyPaths[accountExtKey.Derive(0 | hardenedFlag).GetPublicKey()].KeyPath);
			Assert.Equal(new KeyPath("0'/0'/0'").Derive(1 | hardenedFlag), psbt.Inputs[1].HDKeyPaths[accountExtKey.Derive(1 | hardenedFlag).GetPublicKey()].KeyPath);
			Assert.Equal(masterExtkey.GetPublicKey().GetHDFingerPrint(), psbt.Inputs[0].HDKeyPaths[accountExtKey.Derive(0 | hardenedFlag).GetPublicKey()].MasterFingerprint);
			Assert.Equal(masterExtkey.GetPublicKey().GetHDFingerPrint(), psbt.Inputs[1].HDKeyPaths[accountExtKey.Derive(1 | hardenedFlag).GetPublicKey()].MasterFingerprint);

			Assert.NotEqual(Money.Zero, psbt.GetBalance(ScriptPubKeyType.Legacy, masterExtkey));
			Assert.Equal(psbt.GetBalance(ScriptPubKeyType.Legacy, masterExtkey), psbt.GetBalance(ScriptPubKeyType.Legacy, accountExtKey, accountRootedKeyPath));
			if (hardenedFlag != 0) // If hardened, we can't get the balance from the account pubkey
			{
				Assert.Equal(Money.Zero, psbt.GetBalance(ScriptPubKeyType.Legacy, accountExtKey.Neuter(), accountRootedKeyPath));
			}
			else
			{
				Assert.Equal(psbt.GetBalance(ScriptPubKeyType.Legacy, masterExtkey), psbt.GetBalance(ScriptPubKeyType.Legacy, accountExtKey.Neuter(), accountRootedKeyPath));
			}
			Assert.Equal(Money.Zero, psbt.GetBalance(ScriptPubKeyType.Legacy, masterExtkey.Derive(new KeyPath("0'/0'/1'")), new KeyPath("0'/0'/1'").ToRootedKeyPath(masterFP)));
			Assert.Equal(Money.Zero, psbt.GetBalance(ScriptPubKeyType.Legacy, masterExtkey.Neuter())); // Can't derive!
			if (hardenedFlag != 0)
			{
				hardenedFlag = 0;
				goto retry;
			}
		}
Exemplo n.º 10
0
        public string GetPrivateKey(string masterKey, string network, long addressIndex)
        {
            Network       selectedNetwork = GetNetwork(network);
            BitcoinExtKey exkey           = new BitcoinExtKey(ExtKey.Parse(masterKey, selectedNetwork), selectedNetwork);
            ExtKey        addressKey1     = exkey.ExtKey.Derive(new KeyPath(@"m/44'/0'/0'/0/" + addressIndex));

            return(addressKey1.PrivateKey.GetWif(selectedNetwork).ToString());
        }
Exemplo n.º 11
0
        public AccountHDWallet(string accountMasterKey, uint accountIndex, IAddressGenerator addressGenerator)
        {
            BitcoinExtKey bitcoinExtKey = new BitcoinExtKey(accountMasterKey);

            _masterKey        = bitcoinExtKey.ExtKey;
            _accountIndex     = accountIndex;
            _addressGenerator = addressGenerator;
        }
Exemplo n.º 12
0
        public string GetNewDepositAddress(string masterKey, string network, long addressIndex)
        {
            Network       selectedNetwork = GetNetwork(network);
            BitcoinExtKey exkey           = new BitcoinExtKey(ExtKey.Parse(masterKey, selectedNetwork), selectedNetwork);
            ExtKey        addressKey1     = exkey.ExtKey.Derive(new KeyPath(@"m/44'/0'/0'/0/" + addressIndex));
            string        address         = addressKey1.PrivateKey.PubKey.GetAddress(ScriptPubKeyType.Legacy, selectedNetwork).ToString();

            // string privatekey = GetPrivateKey(masterKey, network, addressIndex);
            return(address);
        }
Exemplo n.º 13
0
 private BitcoinExtKey GetBaseXPriv(NRustLightningNetwork network)
 {
     if (BaseXPrivs.TryGetValue(network, out var baseKey))
     {
         return(baseKey);
     }
     baseKey = new BitcoinExtKey(new ExtKey(_keysRepository.GetNodeSecret().ToBytes()).Derive(network.BaseKeyPath), network.NBitcoinNetwork);
     BaseXPrivs.TryAdd(network, baseKey);
     return(baseKey);
 }
Exemplo n.º 14
0
        public void CanTrackSeveralTransactions()
        {
            using (var tester = ServerTester.Create())
            {
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());
                tester.Client.Track(pubkey);
                var utxo = tester.Client.Sync(pubkey, null, null, true);                 //Track things do not wait

                var addresses = new HashSet <Script>();
                tester.RPC.ImportPrivKey(PrivateKeyOf(key, "0/0"));
                var id = tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(1.0m));
                addresses.Add(AddressOf(key, "0/0").ScriptPubKey);

                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.True(utxo.HasChanges);

                var coins = Money.Coins(1.0m);
                int i     = 0;
                for (i = 0; i < 20; i++)
                {
                    LockTestCoins(tester.RPC, addresses);
                    var spendable = tester.RPC.ListUnspent(0, 0);
                    coins = coins - Money.Coins(0.001m);
                    var destination = AddressOf(key, $"0/{i + 1}");

                    tester.RPC.ImportPrivKey(PrivateKeyOf(key, $"0/{i + 1}"));
                    tester.RPC.SendToAddress(destination, coins);
                    addresses.Add(destination.ScriptPubKey);
                }

                while (true)
                {
                    utxo = tester.Client.Sync(pubkey, utxo);
                    if (!utxo.HasChanges)
                    {
                        Assert.False(true, "should have changes");
                    }
                    Assert.False(utxo.Confirmed.Reset);
                    Assert.True(utxo.Unconfirmed.HasChanges);
                    Assert.Equal(1, utxo.Unconfirmed.UTXOs.Count);
                    if (new KeyPath($"0/{i}").Equals(utxo.Unconfirmed.UTXOs[0].KeyPath))
                    {
                        break;
                    }
                }

                tester.RPC.Generate(1);

                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.Equal(1, utxo.Confirmed.UTXOs.Count);
                Assert.True(utxo.Confirmed.HasChanges);
                Assert.Equal(0, utxo.Confirmed.SpentOutpoints.Count);
            }
        }
Exemplo n.º 15
0
 public BitcoinAddress AddressOf(BitcoinExtKey key, string path)
 {
     if (this.RPC.Capabilities.SupportSegwit)
     {
         return(key.ExtKey.Derive(new KeyPath(path)).Neuter().PubKey.WitHash.GetAddress(Network));
     }
     else
     {
         return(key.ExtKey.Derive(new KeyPath(path)).Neuter().PubKey.Hash.GetAddress(Network));
     }
 }
Exemplo n.º 16
0
        public void CanTrack4()
        {
            using (var tester = ServerTester.Create())
            {
                var bob   = new BitcoinExtKey(new ExtKey(), tester.Network);
                var alice = new BitcoinExtKey(new ExtKey(), tester.Network);

                var bobPubKey   = CreateDerivationStrategy(bob.Neuter());
                var alicePubKey = CreateDerivationStrategy(alice.Neuter());

                tester.Client.Track(alicePubKey);
                var utxoAlice = tester.Client.GetUTXOs(alicePubKey, Bookmark.Start, Bookmark.Start, true); //Track things do not wait
                tester.Client.Track(bobPubKey);
                var utxoBob = tester.Client.GetUTXOs(bobPubKey, null, false);                              //Track things do not wait
                Assert.NotNull(utxoAlice.Confirmed.KnownBookmark);
                Assert.NotNull(utxoAlice.Unconfirmed.KnownBookmark);

                var id = tester.RPC.SendToAddress(AddressOf(alice, "0/1"), Money.Coins(1.0m));
                id        = tester.RPC.SendToAddress(AddressOf(bob, "0/2"), Money.Coins(0.1m));
                utxoAlice = tester.Client.GetUTXOs(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.GetUTXOs(bobPubKey, utxoBob);
                Assert.NotNull(utxoAlice.Unconfirmed.KnownBookmark);

                tester.RPC.Generate(1);

                utxoAlice = tester.Client.GetUTXOs(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.GetUTXOs(bobPubKey, utxoBob);
                Assert.NotNull(utxoAlice.Confirmed.KnownBookmark);

                LockTestCoins(tester.RPC);
                tester.RPC.ImportPrivKey(PrivateKeyOf(alice, "0/1"));
                tester.RPC.SendToAddress(AddressOf(bob, "0/3"), Money.Coins(0.6m));

                utxoAlice = tester.Client.GetUTXOs(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.GetUTXOs(bobPubKey, utxoBob);
                Assert.NotNull(utxoAlice.Unconfirmed.KnownBookmark);

                utxoAlice = tester.Client.GetUTXOs(alicePubKey, utxoAlice, false);
                Assert.NotNull(utxoAlice.Unconfirmed.KnownBookmark);

                tester.RPC.Generate(1);

                utxoAlice = tester.Client.GetUTXOs(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.GetUTXOs(bobPubKey, utxoBob);

                Assert.NotNull(utxoAlice.Confirmed.KnownBookmark);
                Assert.Single(utxoAlice.Confirmed.SpentOutpoints);
                Assert.Empty(utxoAlice.Confirmed.UTXOs);

                Assert.Empty(utxoBob.Confirmed.SpentOutpoints);
                Assert.Single(utxoBob.Confirmed.UTXOs);
                Assert.Equal("0/3", utxoBob.Confirmed.UTXOs[0].KeyPath.ToString());
            }
        }
Exemplo n.º 17
0
        public void CanTrack4()
        {
            using (var tester = ServerTester.Create())
            {
                var bob   = new BitcoinExtKey(new ExtKey(), tester.Network);
                var alice = new BitcoinExtKey(new ExtKey(), tester.Network);

                var bobPubKey   = CreateDerivationStrategy(bob.Neuter());
                var alicePubKey = CreateDerivationStrategy(alice.Neuter());

                tester.Client.Track(alicePubKey);
                var utxoAlice = tester.Client.Sync(alicePubKey, uint256.Zero, uint256.Zero, true); //Track things do not wait
                tester.Client.Track(bobPubKey);
                var utxoBob = tester.Client.Sync(bobPubKey, null, null, true);                     //Track things do not wait
                Assert.False(utxoAlice.Confirmed.Reset);
                Assert.False(utxoAlice.Unconfirmed.Reset);

                var id = tester.RPC.SendToAddress(AddressOf(alice, "0/1"), Money.Coins(1.0m));
                id        = tester.RPC.SendToAddress(AddressOf(bob, "0/2"), Money.Coins(0.1m));
                utxoAlice = tester.Client.Sync(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.Sync(bobPubKey, utxoBob);
                Assert.False(utxoAlice.Unconfirmed.Reset);

                tester.RPC.Generate(1);

                utxoAlice = tester.Client.Sync(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.Sync(bobPubKey, utxoBob);
                Assert.False(utxoAlice.Confirmed.Reset);

                LockTestCoins(tester.RPC);
                tester.RPC.ImportPrivKey(PrivateKeyOf(alice, "0/1"));
                tester.RPC.SendToAddress(AddressOf(bob, "0/3"), Money.Coins(0.6m));

                utxoAlice = tester.Client.Sync(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.Sync(bobPubKey, utxoBob);
                Assert.False(utxoAlice.Unconfirmed.Reset);

                utxoAlice = tester.Client.Sync(alicePubKey, utxoAlice, true);
                Assert.False(utxoAlice.Unconfirmed.Reset);

                tester.RPC.Generate(1);

                utxoAlice = tester.Client.Sync(alicePubKey, utxoAlice);
                utxoBob   = tester.Client.Sync(bobPubKey, utxoBob);

                Assert.False(utxoAlice.Confirmed.Reset);
                Assert.Equal(1, utxoAlice.Confirmed.SpentOutpoints.Count);
                Assert.Equal(0, utxoAlice.Confirmed.UTXOs.Count);

                Assert.Equal(0, utxoBob.Confirmed.SpentOutpoints.Count);
                Assert.Equal(1, utxoBob.Confirmed.UTXOs.Count);
                Assert.Equal("0/3", utxoBob.Confirmed.UTXOs[0].KeyPath.ToString());
            }
        }
Exemplo n.º 18
0
        private void Send(string password, string walletName, string walletAddress, string outpoint)
        {
            BitcoinExtKey privateKey = null;

            try
            {
                Safe wallet = Safe.Load(password, this.walletFilePath + walletName + ".json");

                const int firstTenAddressesInWallet = 10;
                for (int i = 0; i < firstTenAddressesInWallet; i++)
                {
                    if (wallet.GetAddress(i).ToString() == walletAddress)
                    {
                        this.WriteLineCommand("");
                        this.WriteCommand("Enter private key: ");
                        privateKey = new BitcoinExtKey(this.ReadLineCommand());

                        if (!privateKey.Equals(wallet.FindPrivateKey(wallet.GetAddress(i))))
                        {
                            this.WriteLineCommand("");
                            this.WriteLineCommand("Wrong private key!");
                            this.WriteLineCommand("");
                        }

                        break;
                    }
                }
            }
            catch
            {
                this.WriteLineCommand("");
                this.WriteLineCommand("Wrong wallet or password");
                this.WriteLineCommand("");
            }

            QBitNinjaClient client          = new QBitNinjaClient(this.currentNetwork);
            var             balance         = client.GetBalance(BitcoinAddress.Create(walletAddress), false).Result;
            OutPoint        outpointToSpend = null;

            //outpoint = transaction ID
            foreach (var entry in balance.Operations)
            {
                foreach (var coin in entry.ReceivedCoins)
                {
                    if (coin.Outpoint.ToString().Substring(0, coin.Outpoint.ToString().Length - 2) == outpoint)
                    {
                        outpointToSpend = coin.Outpoint;
                        break;
                    }
                }
            }

            this.MakeTransaction(outpointToSpend, privateKey, client);
        }
        /// <inheritdoc />
        public ISecret GetKeyForAddress(string password, HdAddress address)
        {
            // TODO: can we have more then one wallet per coins?
            var walletTree = this.Wallets.First();
            // get extended private key
            var           privateKey        = Key.Parse(walletTree.EncryptedSeed, password, walletTree.Network);
            var           seedExtKey        = new ExtKey(privateKey, walletTree.ChainCode);
            ExtKey        addressExtKey     = seedExtKey.Derive(new KeyPath(address.HdPath));
            BitcoinExtKey addressPrivateKey = addressExtKey.GetWif(walletTree.Network);

            return(addressPrivateKey);
        }
Exemplo n.º 20
0
        private void CanCheckBIP39TestVectorsCore(string file, Wordlist wordlist)
        {
            var tests = JArray.Parse(File.ReadAllText($"data/bip39_vectors.{file}.json"));

            foreach (var test in tests.Children().OfType <JObject>())
            {
                var mnemonic = new Mnemonic(test["mnemonic"].Value <string>(), wordlist);
                var actual   = mnemonic.DeriveExtKey(test["passphrase"].Value <string>()).GetWif(Network.Main);
                var expected = new BitcoinExtKey(test["bip32_xprv"].Value <string>(), Network.Main);
                Assert.Equal(actual, expected);
            }
        }
Exemplo n.º 21
0
        public void CanGetTransactionsOfDerivation()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Client.WaitServerStarted(Timeout);
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());

                tester.Client.Track(pubkey);
                var utxo = tester.Client.GetUTXOs(pubkey, null, false);                 //Track things do not wait

                var txId   = tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(1.0m));
                var result = tester.Client.GetTransactions(pubkey, new[] { Bookmark.Start }, new[] { Bookmark.Start }, new[] { Bookmark.Start });
                Assert.True(result.HasChanges());
                Assert.Single(result.UnconfirmedTransactions.Transactions);
                var height          = result.Height;
                var timestampUnconf = result.UnconfirmedTransactions.Transactions[0].Timestamp;
                Assert.Null(result.UnconfirmedTransactions.Transactions[0].BlockHash);
                Assert.Null(result.UnconfirmedTransactions.Transactions[0].Height);
                Assert.Equal(0, result.UnconfirmedTransactions.Transactions[0].Confirmations);
                Assert.Equal(result.UnconfirmedTransactions.Transactions[0].Transaction.GetHash(), result.UnconfirmedTransactions.Transactions[0].TransactionId);

                tester.Client.IncludeTransaction = false;
                result = tester.Client.GetTransactions(pubkey, new[] { Bookmark.Start }, new[] { Bookmark.Start }, new[] { Bookmark.Start });
                Assert.Null(result.UnconfirmedTransactions.Transactions[0].Transaction);

                result = tester.Client.GetTransactions(pubkey, result, false);
                Assert.False(result.HasChanges());

                tester.RPC.Generate(1);
                result = tester.Client.GetTransactions(pubkey, result);
                Assert.True(result.HasChanges());
                Assert.Null(result.UnconfirmedTransactions.KnownBookmark);

                var gotConf = result.ConfirmedTransactions.Bookmark;

                var txId2 = tester.RPC.SendToAddress(AddressOf(key, "0"), Money.Coins(1.0m));
                result = tester.Client.GetTransactions(pubkey, result);
                Assert.True(result.HasChanges());
                Assert.Equal(gotConf, result.ConfirmedTransactions.KnownBookmark);
                Assert.Single(result.UnconfirmedTransactions.Transactions);
                Assert.Equal(txId2, result.UnconfirmedTransactions.Transactions[0].TransactionId);

                result = tester.Client.GetTransactions(pubkey, null, null, null, false);
                Assert.True(result.HasChanges());
                Assert.Single(result.ConfirmedTransactions.Transactions);
                Assert.Single(result.UnconfirmedTransactions.Transactions);
                Assert.Equal(txId, result.ConfirmedTransactions.Transactions[0].TransactionId);
                Assert.Equal(timestampUnconf, result.ConfirmedTransactions.Transactions[0].Timestamp);
                Assert.Equal(txId2, result.UnconfirmedTransactions.Transactions[0].TransactionId);
            }
        }
Exemplo n.º 22
0
        public static ISecret GetExtendedPrivateKey(Key privateKey, byte[] chainCode, string hdPath, Network network)
        {
            Guard.NotNull(privateKey, nameof(privateKey));
            Guard.NotNull(chainCode, nameof(chainCode));
            Guard.NotEmpty(hdPath, nameof(hdPath));
            Guard.NotNull(network, nameof(network));

            // Get the extended key.
            var           seedExtKey        = new ExtKey(privateKey, chainCode);
            ExtKey        addressExtKey     = seedExtKey.Derive(new KeyPath(hdPath));
            BitcoinExtKey addressPrivateKey = addressExtKey.GetWif(network);

            return(addressPrivateKey);
        }
Exemplo n.º 23
0
        public void CanTrackDirect()
        {
            using (var tester = ServerTester.Create())
            {
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());
                tester.Client.Track(pubkey);
                var utxo = tester.Client.GetUTXOs(pubkey, null, false);         //Track things do not wait
                var tx1  = tester.RPC.SendToAddress(AddressOf(key, "0"), Money.Coins(1.0m));
                utxo = tester.Client.GetUTXOs(pubkey, utxo);
                Assert.NotNull(utxo.Confirmed.KnownBookmark);
                Assert.Single(utxo.Unconfirmed.UTXOs);
                Assert.Equal(tx1, utxo.Unconfirmed.UTXOs[0].Outpoint.Hash);


                LockTestCoins(tester.RPC);
                tester.RPC.ImportPrivKey(PrivateKeyOf(key, "0"));
                var tx2 = tester.RPC.SendToAddress(AddressOf(key, "1"), Money.Coins(0.6m));

                var prevUtxo = utxo;
                utxo = tester.Client.GetUTXOs(pubkey, utxo);
                Assert.NotNull(utxo.Unconfirmed.KnownBookmark);
                Assert.Single(utxo.Unconfirmed.UTXOs);
                Assert.Equal(tx2, utxo.Unconfirmed.UTXOs[0].Outpoint.Hash);         //got the 0.6m
                Assert.Equal(Money.Coins(0.6m), utxo.Unconfirmed.UTXOs[0].Value);   //got the 0.6m

                Assert.Single(utxo.Unconfirmed.SpentOutpoints);
                Assert.Equal(tx1, utxo.Unconfirmed.SpentOutpoints[0].Hash);         //previous coin is spent

                utxo = tester.Client.GetUTXOs(pubkey, prevUtxo.Confirmed.Bookmark, null);
                Assert.Null(utxo.Unconfirmed.KnownBookmark);
                Assert.Single(utxo.Unconfirmed.UTXOs);
                Assert.Empty(utxo.Unconfirmed.SpentOutpoints);         //should be skipped as the unconf coin were not known

                tester.RPC.SendToAddress(AddressOf(key, "0"), Money.Coins(0.15m));

                utxo = tester.Client.GetUTXOs(pubkey, utxo);
                Assert.Single(utxo.Unconfirmed.UTXOs);
                Assert.IsType <Coin>(utxo.Unconfirmed.UTXOs[0].AsCoin(pubkey));
                Assert.Equal(Money.Coins(0.15m), utxo.Unconfirmed.UTXOs[0].Value);
                Assert.Empty(utxo.Unconfirmed.SpentOutpoints);

                utxo = tester.Client.GetUTXOs(pubkey, null);
                Assert.Equal(2, utxo.Unconfirmed.UTXOs.Count);         //Should have 0.15 and 0.6
                Assert.Equal(Money.Coins(0.75m), utxo.Unconfirmed.UTXOs.Select(c => c.Value).Sum());
                Assert.Empty(utxo.Unconfirmed.SpentOutpoints);
            }
        }
            internal bool TryGetExtKey(Func <KeyId, Key> privateKeyProvider, out BitcoinExtKey extKey)
            {
                extKey = null;
                if (privateKeyProvider == null)
                {
                    return(false);
                }
                var privKey = privateKeyProvider(this.Extkey.ExtPubKey.PubKey.Hash);

                if (privKey == null)
                {
                    return(false);
                }
                extKey = new BitcoinExtKey(Extkey, privKey);
                return(true);
            }
Exemplo n.º 25
0
        public BtcWallet(ILogger logger, WalletContext db, bool mainnet, Uri nbxplorerAddress, bool useLegacyAddrs = false) : base(logger, db, mainnet)
        {
            this.nbxplorerAddress = nbxplorerAddress;

            // create extended key
            var network = GetNetwork();

            key = new BitcoinExtKey(new ExtKey(seedHex), network);
            var strpubkey = $"{key.Neuter().ToString()}";

            if (useLegacyAddrs)
            {
                strpubkey = strpubkey + "-[legacy]";
            }
            pubkey = (DirectDerivationStrategy) new DerivationStrategyFactory(network).Parse(strpubkey);
        }
Exemplo n.º 26
0
        TWallet IHDWallet <TWallet> .GetAccountWallet(uint accountIndex)
        {
            var externalKeyPath   = new KeyPath($"{accountIndex}'");
            var externalMasterKey = _masterKey.Derive(externalKeyPath);

            BitcoinExtKey bitcoinExtKey = new BitcoinExtKey(externalMasterKey, Network.Main);

            // TODO: Get xpiv and assert in unit test

            return(new TWallet()
            {
                PrivateKey = _masterKey.PrivateKey,
                AddressGenerator = AddressGenerator,
                Index = accountIndex
            });
        }
Exemplo n.º 27
0
        public void CanTrack2()
        {
            using (var tester = ServerTester.Create())
            {
                var key    = new BitcoinExtKey(new ExtKey(), tester.Network);
                var pubkey = CreateDerivationStrategy(key.Neuter());
                tester.Client.Track(pubkey);
                var utxo = tester.Client.Sync(pubkey, null, null, true);                 //Track things do not wait
                var tx1  = tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(1.0m));
                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.False(utxo.Confirmed.Reset);
                Assert.Equal(1, utxo.Unconfirmed.UTXOs.Count);
                Assert.Equal(tx1, utxo.Unconfirmed.UTXOs[0].Outpoint.Hash);


                LockTestCoins(tester.RPC);
                tester.RPC.ImportPrivKey(PrivateKeyOf(key, "0/0"));
                var tx2 = tester.RPC.SendToAddress(AddressOf(key, "1/0"), Money.Coins(0.6m));

                var prevUtxo = utxo;
                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.False(utxo.Unconfirmed.Reset);
                Assert.Equal(1, utxo.Unconfirmed.UTXOs.Count);
                Assert.Equal(tx2, utxo.Unconfirmed.UTXOs[0].Outpoint.Hash);                 //got the 0.6m
                Assert.Equal(Money.Coins(0.6m), utxo.Unconfirmed.UTXOs[0].Output.Value);    //got the 0.6m

                Assert.Equal(1, utxo.Unconfirmed.SpentOutpoints.Count);
                Assert.Equal(tx1, utxo.Unconfirmed.SpentOutpoints[0].Hash);                 //previous coin is spent

                utxo = tester.Client.Sync(pubkey, prevUtxo.Confirmed.Hash, null);
                Assert.True(utxo.Unconfirmed.Reset);
                Assert.Equal(1, utxo.Unconfirmed.UTXOs.Count);
                Assert.Equal(0, utxo.Unconfirmed.SpentOutpoints.Count);                 //should be skipped as the unconf coin were not known

                tester.RPC.SendToAddress(AddressOf(key, "0/0"), Money.Coins(0.15m));

                utxo = tester.Client.Sync(pubkey, utxo);
                Assert.Equal(1, utxo.Unconfirmed.UTXOs.Count);
                Assert.Equal(Money.Coins(0.15m), utxo.Unconfirmed.UTXOs[0].Output.Value);
                Assert.Equal(0, utxo.Unconfirmed.SpentOutpoints.Count);

                utxo = tester.Client.Sync(pubkey, null);
                Assert.Equal(2, utxo.Unconfirmed.UTXOs.Count);                 //Should have 0.15 and 0.6
                Assert.Equal(Money.Coins(0.75m), utxo.Unconfirmed.UTXOs.Select(c => c.Output.Value).Sum());
                Assert.Equal(0, utxo.Unconfirmed.SpentOutpoints.Count);
            }
        }
Exemplo n.º 28
0
        public async Task <StoresController> CreateStoreAsync()
        {
            ExtKey = new ExtKey().GetWif(parent.Network);
            var store = parent.PayTester.GetController <StoresController>(UserId);
            await store.CreateStore(new CreateStoreViewModel()
            {
                Name = "Test Store"
            });

            StoreId = store.CreatedStoreId;
            await store.UpdateStore(StoreId, new StoreViewModel()
            {
                DerivationScheme = ExtKey.Neuter().ToString() + "-[legacy]",
                SpeedPolicy      = SpeedPolicy.MediumSpeed
            }, "Save");

            return(store);
        }
Exemplo n.º 29
0
        private void addKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (FormAddKey form = new FormAddKey())
            {
                if (form.ShowDialog() == DialogResult.OK && form.Result != null)
                {
                    KeyPair      keyPair = null;
                    Type         type    = form.Result.GetType();
                    ListViewItem lvi     = new ListViewItem();

                    switch (type.ToString())
                    {
                    case "NBitcoin.ExtPubKey":
                        ExtPubKey pubKey = form.Result as ExtPubKey;
                        keyPair  = new KeyPair(pubKey);
                        lvi.Text = keyPair.PrivateKeyString;
                        lvi.Tag  = keyPair;
                        lvi.SubItems.AddRange(new [] { keyPair.PubKey.ToString(), keyPair.Address.ToString() });
                        listViewKey.Items.Add(lvi);
                        break;

                    case "NBitcoin.BitcoinSecret":
                        BitcoinSecret secret = form.Result as BitcoinSecret;
                        lvi.Text = secret.ToWif();
                        lvi.Tag  = secret;
                        lvi.SubItems.AddRange(new[] { "unknown", secret.GetAddress().ToString() });
                        listViewKey.Items.Add(lvi);
                        break;

                    case "NBitcoin.BitcoinExtKey":
                        BitcoinExtKey extKey = form.Result as BitcoinExtKey;
                        keyPair  = new KeyPair(extKey);
                        lvi.Text = keyPair.PrivateKeyString;
                        lvi.Tag  = keyPair;
                        lvi.SubItems.AddRange(new [] { keyPair.PubKey.ToString(), keyPair.Address.ToString() });
                        listViewKey.Items.Add(lvi);
                        break;
                    }
                }
            }
        }
Exemplo n.º 30
0
 public override bool TryParse(string str, Network network, Type targetType, out IBitcoinString result)
 {
     // Private Key
     if (str.StartsWith("????", StringComparison.OrdinalIgnoreCase) && targetType.GetTypeInfo().IsAssignableFrom(typeof(BitcoinExtKey).GetTypeInfo()))
     {
         try
         {
             var decoded = Encoders.Base58Check.DecodeData(str);
             decoded[0] = 0x04;
             decoded[1] = 0x88;
             decoded[2] = 0xB2;
             decoded[3] = 0xE4;
             result     = new BitcoinExtKey(Encoders.Base58Check.EncodeData(decoded), network);
             return(true);
         }
         catch
         {
         }
     }
     // Public Key
     if (str.StartsWith("????", StringComparison.OrdinalIgnoreCase) && targetType.GetTypeInfo().IsAssignableFrom(typeof(BitcoinExtPubKey).GetTypeInfo()))
     {
         try
         {
             var decoded = Encoders.Base58Check.DecodeData(str);
             decoded[0] = 0x04;
             decoded[1] = 0x35;
             decoded[2] = 0x87;
             decoded[3] = 0xCF;
             result     = new BitcoinExtPubKey(Encoders.Base58Check.EncodeData(decoded), network);
             return(true);
         }
         catch
         {
         }
     }
     // Other
     return(base.TryParse(str, network, out result));
 }