Exemple #1
0
 private ViewResult ViewWalletSendLedger(PSBT psbt, BitcoinAddress hintChange = null)
 {
     SetAmbientPSBT(psbt);
     return(View("WalletSendLedger", new WalletSendLedgerModel()
     {
         PSBT = psbt.ToBase64(),
         HintChange = hintChange?.ToString(),
         WebsocketPath = this.Url.Action(nameof(LedgerConnection))
     }));
 }
            private static XlsxTransactionInputOutput Create(BitcoinAddress address,
                                                             ICoin source,
                                                             BlockInformation block,
                                                             uint256 transactionHash,
                                                             IDictionary <string, IAssetDefinition> assetDictionary,
                                                             int index,
                                                             Network network,
                                                             CoinType coinType)
            {
                string coloredAddress = null;

                try
                {
                    coloredAddress = address?.ToColoredAddress()?.ToWif();
                }
                catch
                {
                }
                var result = new XlsxTransactionInputOutput
                {
                    Address         = address?.ToString(),
                    ColoredAddress  = coloredAddress,
                    TransactionHash = transactionHash.ToString(),
                    Index           = index,
                    CoinType        = coinType,
                };

                if (block != null)
                {
                    result.BlockDate = block.BlockTime.UtcDateTime;
                    result.BlockHash = block.BlockId.ToString();
                }
                if (source is ColoredCoin colored)
                {
                    var assetId = colored.AssetId.GetWif(network).ToString();

                    var asset        = assetDictionary.ContainsKey(assetId) ? assetDictionary[assetId] : null;
                    var divisibility = asset?.Divisibility ?? 0;

                    result.ColouredAssetValue = BitcoinUtils.CalculateColoredAssetQuantity(colored.Amount.Quantity, divisibility);
                    result.BtcValue           = BitcoinUtils.SatoshiToBtc(colored.Bearer.Amount.Satoshi);

                    result.ColouredAssetName = asset != null ? asset.Name : assetId;
                }

                if (source is Coin uncolored)
                {
                    result.BtcValue = BitcoinUtils.SatoshiToBtc(uncolored.Amount.Satoshi);
                }

                return(result);
            }
Exemple #3
0
 public async Task <InvoiceResponse> CreateInvoice(string description, long?amountMsat = null,
                                                   int?expireIn          = null, BitcoinAddress fallbackAddress = null,
                                                   CancellationToken cts = default(CancellationToken))
 {
     return(await SendCommandAsync <CreateInvoiceRequest, InvoiceResponse>("createinvoice",
                                                                           new CreateInvoiceRequest()
     {
         Description = description,
         ExpireIn = expireIn,
         AmountMsat = amountMsat,
         FallbackAddress = fallbackAddress?.ToString()
     }, cts));
 }
Exemple #4
0
		public async Task ImportAddressAsync(BitcoinAddress address, string label, bool rescan)
		{
			await SendCommandAsync("importaddress", address.ToString(), label, rescan).ConfigureAwait(false);
		}
Exemple #5
0
		public void ImportAddress(BitcoinAddress address, string label, bool rescan)
		{
			SendCommand("importaddress", address.ToString(), label, rescan);
		}
Exemple #6
0
		/// <summary>
		/// Requires wallet support. Requires an unlocked wallet or an unencrypted wallet.
		/// </summary>
		/// <param name="address">A P2PKH or P2SH address to which the bitcoins should be sent</param>
		/// <param name="amount">The amount to spend</param>
		/// <param name="commentTx">A locally-stored (not broadcast) comment assigned to this transaction. Default is no comment</param>
		/// <param name="commentDest">A locally-stored (not broadcast) comment assigned to this transaction. Meant to be used for describing who the payment was sent to. Default is no comment</param>
		/// <returns>The TXID of the sent transaction</returns>
		public async Task<uint256> SendToAddressAsync(BitcoinAddress address, Money amount, string commentTx = null, string commentDest = null)
		{
			List<object> parameters = new List<object>();
			parameters.Add(address.ToString());
			parameters.Add(amount.ToString());
			if(commentTx != null)
				parameters.Add(commentTx);
			if(commentDest != null)
				parameters.Add(commentDest);
			var resp = await SendCommandAsync(RPCOperations.sendtoaddress, parameters.ToArray()).ConfigureAwait(false);
			return uint256.Parse(resp.Result.ToString());
		}
 public async Task ImportAddressAsync(BitcoinAddress address, string label, bool rescan)
 {
     await SendCommandAsync(RPCOperations.importaddress, address.ToString(), label, rescan).ConfigureAwait(false);
 }
        /// <summary>
        /// Returns the total amount received by the specified address in transactions with the
        /// specified number of confirmations. It does not count coinbase transactions.
        /// </summary>
        /// <param name="confirmations">
        /// The minimum number of confirmations an externally-generated transaction must have before
        /// it is counted towards the balance. Transactions generated by this node are counted immediately.
        /// Typically, externally-generated transactions are payments to this wallet and transactions
        /// generated by this node are payments to other wallets. Use 0 to count unconfirmed transactions.
        /// Default is 1.
        /// </param>
        /// <returns>The number of bitcoins received by the address, excluding coinbase transactions. May be 0.</returns>
        public Money GetReceivedByAddress(BitcoinAddress address, int confirmations)
        {
            RPCResponse response = SendCommand(RPCOperations.getreceivedbyaddress, address.ToString(), confirmations);

            return(Money.Coins(response.Result.Value <decimal>()));
        }
        // dumpprivkey

        public BitcoinSecret DumpPrivKey(BitcoinAddress address)
        {
            RPCResponse response = SendCommand(RPCOperations.dumpprivkey, address.ToString());

            return(this.Network.Parse <BitcoinSecret>((string)response.Result));
        }
Exemple #10
0
        public BitcoinSecret DumpPrivKey(BitcoinAddress address)
        {
            var response = SendCommand("dumpprivkey", address.ToString());

            return(Network.CreateFromBase58Data <BitcoinSecret>((string)response.Result));
        }
        public async Task <ByteString> IssueWithdrawal(IList <OutboundTransaction> transactions)
        {
            HttpClient          client   = new HttpClient();
            BitcoinAddress      address  = storageKey.ScriptPubKey.GetDestinationAddress(this.Network);
            HttpResponseMessage response = await client.GetAsync(new Uri(url, $"addresses/{address.ToString()}/unspents"));

            string body = await response.Content.ReadAsStringAsync();

            JArray outputs = JArray.Parse(body);

            TransactionBuilder builder = new TransactionBuilder();

            builder.AddKeys(storageKey.GetBitcoinSecret(Network));
            foreach (JObject output in outputs)
            {
                string transactionHash = (string)output["transaction_hash"];
                uint   outputIndex     = (uint)output["output_index"];
                long   amount          = (long)output["value"];

                builder.AddCoins(new Coin(uint256.Parse(transactionHash), outputIndex, new Money(amount), storageKey.ScriptPubKey));
            }

            foreach (OutboundTransaction outboundTransaction in transactions)
            {
                builder.Send(BitcoinAddress.Create(outboundTransaction.Target, Network).ScriptPubKey, new Money(outboundTransaction.Amount));
            }

            builder.SendFees(defaultFees);
            builder.SetChange(storageKey.ScriptPubKey, ChangeType.All);

            NBitcoin.Transaction transaction = builder.BuildTransaction(true);

            return(new ByteString(transaction.ToBytes()));
        }
Exemple #12
0
        /// <summary>
        /// Console for test code
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Console.WriteLine("{0} This is a console client for bitpoker, making REST or JSON RPC calls to the host", DateTime.UtcNow);

            Server server = new Server();

            server.MessageEvent += Server_MessageEvent;

            Int16 restPort = 8080; ///for rest
            Int16 tcpPort  = 5555;

            if (args == null || args.Length < 1)
            {
                Log(String.Format("tcp://127.0.0.1:{0}", tcpPort));
                args = new string[] { carol.ToString(), String.Format("tcp://127.0.0.1:{0}", tcpPort) };
            }

            Log("Starting tcp server");
            Task task = new Task(() => server.Listen(args[0]));

            task.Start();
            Log("TCP server running");

            String baseUrl = String.Format("http://*****:*****@"C:\Users\lucas.cullen\Source\Repos\bitpoker\headsupcolddeck.txt");

            Mnemonic mnemo = new Mnemonic("test", Wordlist.English);

            var key = mnemo.DeriveExtKey();
            var x   = key.PrivateKey;

            var s = x.GetBitcoinSecret(Network.Main);
            var b = s.GetAddress();


            Console.WriteLine(b);
            Console.ReadKey();

            IDeck deck = new FiftyTwoCardDeck();

            deck.Shuffle(null);

            DumpToDisk(deck.Cards, "deck.txt");
        }
Exemple #13
0
 public override string ToString()
 {
     return(_bitcoinAddress.ToString());
 }
Exemple #14
0
        private List <TransactionInformation> QueryWithListReceivedByAddress(bool withProof, BitcoinAddress address)
        {
            var result       = RPCClient.SendCommand("listreceivedbyaddress", 0, false, true, address.ToString());
            var transactions = ((JArray)result.Result).OfType <JObject>().Select(o => o["txids"]).OfType <JArray>().SingleOrDefault();

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

            HashSet <uint256>             resultsSet = new HashSet <uint256>();
            List <TransactionInformation> results    = new List <TransactionInformation>();

            foreach (var txIdObj in transactions)
            {
                var txId = new uint256(txIdObj.ToString());
                //May have duplicates
                if (!resultsSet.Contains(txId))
                {
                    var tx = GetTransaction(txId);
                    if (tx == null || (withProof && tx.Confirmations == 0))
                    {
                        continue;
                    }
                    resultsSet.Add(txId);
                    results.Add(tx);
                }
            }
            return(results);
        }
Exemple #15
0
        /// <summary>
        /// Returns the total amount received by the specified address in transactions with the
        /// specified number of confirmations. It does not count coinbase transactions.
        /// </summary>
        /// <param name="confirmations">
        /// The minimum number of confirmations an externally-generated transaction must have before
        /// it is counted towards the balance. Transactions generated by this node are counted immediately.
        /// Typically, externally-generated transactions are payments to this wallet and transactions
        /// generated by this node are payments to other wallets. Use 0 to count unconfirmed transactions.
        /// Default is 1.
        /// </param>
        /// <returns>The number of bitcoins received by the address, excluding coinbase transactions. May be 0.</returns>
        public Money GetReceivedByAddress(BitcoinAddress address, int confirmations)
        {
            var response = SendCommand(RPCOperations.getreceivedbyaddress, address.ToString(), confirmations);

            return(GetMoney(response));
        }
Exemple #16
0
        /// <summary>
        /// Returns the total amount received by the specified address in transactions with at
        /// least one (default) confirmations. It does not count coinbase transactions.
        /// </summary>
        /// <param name="address">The address whose transactions should be tallied.</param>
        /// <returns>The number of bitcoins received by the address, excluding coinbase transactions. May be 0.</returns>
        public async Task <Money> GetReceivedByAddressAsync(BitcoinAddress address)
        {
            var response = await SendCommandAsync(RPCOperations.getreceivedbyaddress, address.ToString()).ConfigureAwait(false);

            return(GetMoney(response));
        }
 static public void GetBalanceSummary(BitcoinAddress address, NBitcoin.Network network, GetBalanceSummaryResponse response, bool colored = true)
 {
     ObservableWWW.Get(URL(network, "balances/" + EscapeUrlPart(address.ToString()) + "/summary" + CreateParameters("colored", colored))).
     Subscribe(x => response(JsonUtility.FromJson <Models.BalanceSummary>(x).Result(), network),
               ex => Debug.Log("error : " + ex.Message));
 }
Exemple #18
0
 /// <summary>
 /// Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash.
 /// </summary>
 /// <param name="address"></param>
 /// <returns></returns>
 internal static byte[] HashAddress(BitcoinAddress address)
 {
     return(Hashes.Hash256(Encoders.ASCII.DecodeData(address.ToString())).ToBytes().Take(4).ToArray());
 }
        public async Task <List <InboundTransaction> > GetUnspentOutputs()
        {
            HttpClient          client   = new HttpClient();
            BitcoinAddress      address  = ReceivingKey.ScriptPubKey.GetDestinationAddress(this.Network);
            HttpResponseMessage response = await client.GetAsync(new Uri(url, $"addresses/{address.ToString()}/unspents"));

            string body = await response.Content.ReadAsStringAsync();

            JArray outputs = JArray.Parse(body);

            List <InboundTransaction> result = new List <InboundTransaction>();

            foreach (JObject output in outputs)
            {
                string transactionHash = (string)output["transaction_hash"];
                int    outputIndex     = (int)output["output_index"];
                long   amount          = (long)output["value"];

                HttpResponseMessage transactionResponse = await client.GetAsync(new Uri(url, $"transactions/{transactionHash}"));

                JObject transaction = JObject.Parse(await transactionResponse.Content.ReadAsStringAsync());
                string  target      = (string)FindDestination(transaction);

                if (target != null)
                {
                    result.Add(new InboundTransaction(transactionHash, outputIndex, null, amount, target));
                }
            }

            return(result);
        }
Exemple #20
0
        public async Task <BitcoinSecret> DumpPrivKeyAsync(BitcoinAddress address)
        {
            var response = await SendCommandAsync("dumpprivkey", address.ToString()).ConfigureAwait(false);

            return(Network.CreateFromBase58Data <BitcoinSecret>((string)response.Result));
        }
Exemple #21
0
        public void base58_keys_valid_gen()
        {
            var tests = TestCase.read_json(TestDataLocations.DataFolder(@"base58_keys_valid.json"));

            tests = tests.Concat(TestCase.read_json(TestDataLocations.DataFolder(@"base58_keys_valid2.json"))).ToArray();
            Network network = null;

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

                if (isTestnet)
                {
                    continue;                     // todo: consider to sadd the bitcoin testnet network
                }
                //network = Network.TestNet;
                else
                {
                    network = BitcoinNetwork.Main;
                }

                if (isPrivkey)
                {
                    bool          isCompressed = metadata.isCompressed;
                    Key           key          = new Key(exp_payload, fCompressedIn: isCompressed);
                    BitcoinSecret secret       = network.CreateBitcoinSecret(key);
                    Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
                }
                else
                {
                    string        exp_addrType = (string)metadata.addrType;
                    TxDestination dest;
                    if (exp_addrType == "pubkey")
                    {
                        dest = new KeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "script")
                    {
                        dest = new ScriptId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wpkh")
                    {
                        dest = new WitKeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wsh")
                    {
                        dest = new WitScriptId(exp_payload);
                    }
                    else if (exp_addrType == "none")
                    {
                        continue;
                    }
                    else
                    {
                        Assert.True(false, "Bad addrtype: " + strTest);
                        continue;
                    }
                    try
                    {
                        BitcoinAddress addrOut = dest.GetAddress(network);
                        Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
                        Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
                        Assert.True(dest.ScriptPubKey.GetDestination() == dest);
                    }
                    catch (ArgumentException)
                    {
                        Assert.True(dest.GetType() == typeof(TxDestination));
                    }
                }
            }
        }
        public async Task <BitcoinSecret> DumpPrivKeyAsync(BitcoinAddress address)
        {
            RPCResponse response = await SendCommandAsync(RPCOperations.dumpprivkey, address.ToString()).ConfigureAwait(false);

            return(this.Network.Parse <BitcoinSecret>((string)response.Result));
        }
Exemple #23
0
        /// <summary>
        /// Returns the total amount received by the specified address in transactions with the
        /// specified number of confirmations. It does not count coinbase transactions.
        /// </summary>
        /// <param name="confirmations">
        /// The minimum number of confirmations an externally-generated transaction must have before
        /// it is counted towards the balance. Transactions generated by this node are counted immediately.
        /// Typically, externally-generated transactions are payments to this wallet and transactions
        /// generated by this node are payments to other wallets. Use 0 to count unconfirmed transactions.
        /// Default is 1.
        /// </param>
        /// <returns>The number of bitcoins received by the address, excluding coinbase transactions. May be 0.</returns>
        public async Task <Money> GetReceivedByAddressAsync(BitcoinAddress address, int confirmations)
        {
            var response = await SendCommandAsync(RPCOperations.getreceivedbyaddress, address.ToString(), confirmations).ConfigureAwait(false);

            return(Money.Coins(response.Result.Value <decimal>()));
        }
 public async Task ImportAddressAsync(BitcoinAddress address)
 {
     await SendCommandAsync(RPCOperations.importaddress, address.ToString()).ConfigureAwait(false);
 }
Exemple #25
0
        public void TestAddressCreation()
        {
            Key privateKey;                                                                               // = new Key();

            privateKey = Key.Parse("L5e7GTVzDEFTS2YwRJcRse5LkgpAetKApCafc6avoKLovPcnFE74", Network.Main); // For getting the same outputs
            PubKey         publicKey         = privateKey.PubKey;
            BitcoinAddress addressLegacy     = publicKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main);
            BitcoinAddress addressSegwit     = publicKey.GetAddress(ScriptPubKeyType.Segwit, Network.Main);
            BitcoinAddress addressSegwitP2SH = publicKey.GetAddress(ScriptPubKeyType.SegwitP2SH, Network.Main);
            KeyId          publicKeyHash     = publicKey.Hash;

            // Wif -> 
            // Priv. key -> Wif (Check README.md - Wif)
            BitcoinSecret wif  = privateKey.GetWif(Network.Main);
            BitcoinSecret wif2 = new BitcoinSecret("L5e7GTVzDEFTS2YwRJcRse5LkgpAetKApCafc6avoKLovPcnFE74", Network.Main);

            Assert.AreEqual(wif, wif2);

            // Private key -> 
            // Wif -> Priv. key
            Key privateKey1 = Key.Parse("L5e7GTVzDEFTS2YwRJcRse5LkgpAetKApCafc6avoKLovPcnFE74", Network.Main);

            Assert.AreEqual(privateKey, privateKey1);

            // Base58 encoded priv key
            var privKeyVersionBytes = Network.Main.GetVersionBytes(Base58Type.SECRET_KEY, true);

            byte[] privKeyWithVersionBytes = Helper.Concat(privKeyVersionBytes, privateKey.ToBytes());
            var    privKeyBase58           = Encoders.Base58Check.EncodeData(privKeyWithVersionBytes);

            // Encrypted priv key (BIP38)
            BitcoinEncryptedSecret encryptedPrivKey = wif.Encrypt("password");

            // Decrypted priv key
            BitcoinEncryptedSecret encryptedPrivKeyFromStr = BitcoinEncryptedSecret.Create("6PYWRpL1zPnz5kVxn74H9WdGJZVQ3ah6Pnq54GNinkfrXdd9fWNVS6dn95", Network.Main);
            BitcoinSecret          decryptedPrivKey        = encryptedPrivKeyFromStr.GetSecret("password");

            Assert.AreEqual(wif, decryptedPrivKey);

            // Public key hash -> 
            // Check README (Hash160(Public Key))
            var hash1 = NBitcoin.Crypto.Hashes.SHA256(publicKey.ToBytes());
            var pkh   = NBitcoin.Crypto.Hashes.RIPEMD160(hash1, hash1.Length); // SHA256(RIPEMD160(PUB_KUY))
            var generatedPubKeyHash = new KeyId(pkh);

            Assert.AreEqual(publicKeyHash, generatedPubKeyHash);

            // Bitcoin Address > 
            var versionBytes = Network.Main.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, true); // 0x00

            byte[] PKHWithVersionBytes = Helper.Concat(versionBytes, pkh);                    // 0x00 + PKH
            var    address1            = Encoders.Base58Check.EncodeData(PKHWithVersionBytes);

            Assert.AreEqual(addressLegacy.ToString(), address1); // 1Co3ZZ3U5ELVmZrV3oXk2qbv58AjuwRrnB

            Console.WriteLine();
            Console.WriteLine($"Pri : {privateKey.ToHex()} (Hex)");         // fb401b5261327d8543382c065af27e28a9775c278b7c3dba8cd0d88f0ad042b1
            Console.WriteLine($"Pri : {privKeyBase58} (Base58)");           // 5KiwSFcZuAM3N5Ruf8cfiNzdCFupxFoFuqPafmK7JHqtsEms7HB
            Console.WriteLine($"Pri : {encryptedPrivKey} (Encrypted)");     // 6PYWRpL1zPnz5kVxn74H9WdGJZVQ3ah6Pnq54GNinkfrXdd9fWNVS6dn95
            Console.WriteLine($"Pri : {wif} (Wif)");                        // L5e7GTVzDEFTS2YwRJcRse5LkgpAetKApCafc6avoKLovPcnFE74
            Console.WriteLine($"Pub : {publicKey}");                        // 03c092d451383dedd6052de6778f9b7c393252ecbd4cd05e842638a84a2c6e2528
            Console.WriteLine($"Pub : {publicKey.Decompress()} (Decomp.)"); // 04c092d451383dedd6052de6778f9b7c393252ecbd4cd05e842638a84a2c6e2528fe41f265a1d8884eb304a33b6f8a6a245fab83f7bf503d7dfc532ffc6593df15
            Console.WriteLine($"PKH : {publicKey.Hash}");                   // 815ea7e8372ae215c40dc3d07a024adc7ddaf858
            Console.WriteLine($"Add : {addressLegacy} (Legacy)");           // 1Co3ZZ3U5ELVmZrV3oXk2qbv58AjuwRrnB
            Console.WriteLine($"Add : {addressSegwitP2SH} (SegwitP2SH)");   // 3JCvRhjrEyw9pvZiE3TxsdSHNPJQh1vHTe
            Console.WriteLine($"Add : {addressSegwit} (Segwit)");           // bc1qs90206ph9t3pt3qdc0g85qj2m37a47zclpwws7
        }
 public Task <IEnumerable <HistoricalTransactionDto> > GetHistoryFrom(BitcoinAddress address, string afterHash, int take)
 {
     return(GetHistory(address.ToString(), afterHash, take, true));
 }
Exemple #27
0
        public async Task <Transaction> GetOrBuildTransferTransaction(Guid operationId,
                                                                      BitcoinAddress fromAddress,
                                                                      BitcoinAddress toAddress,
                                                                      string assetId,
                                                                      Money amountToSend,
                                                                      bool includeFee)
        {
            if (await _operationMetaRepository.Exist(operationId))
            {
                var alreadyBuildedTransaction = await _transactionBlobStorage.GetTransaction(operationId, TransactionBlobType.Initial);

                return(Transaction.Parse(alreadyBuildedTransaction));
            }

            var buildedTransaction = await _transactionBuilder.GetTransferTransaction(fromAddress, toAddress, amountToSend, includeFee);

            await _transactionBlobStorage.AddOrReplaceTransaction(operationId, TransactionBlobType.Initial,
                                                                  buildedTransaction.TransactionData.ToHex());

            var operation = OperationMeta.Create(operationId, fromAddress.ToString(), toAddress.ToString(), assetId,
                                                 buildedTransaction.Amount.Satoshi, buildedTransaction.Fee.Satoshi, includeFee);
            await _operationMetaRepository.Insert(operation);

            return(buildedTransaction.TransactionData);
        }
Exemple #28
0
		public void ImportAddress(BitcoinAddress address)
		{
			SendCommand("importaddress", address.ToString());
		}
Exemple #29
0
        void SetTransactionOutput(SeleniumTester s, int index, BitcoinAddress dest, decimal amount, bool subtract = false)
        {
            s.Driver.FindElement(By.Id($"Outputs_{index}__DestinationAddress")).SendKeys(dest.ToString());
            var amountElement = s.Driver.FindElement(By.Id($"Outputs_{index}__Amount"));

            amountElement.Clear();
            amountElement.SendKeys(amount.ToString());
            var checkboxElement = s.Driver.FindElement(By.Id($"Outputs_{index}__SubtractFeesFromOutput"));

            if (checkboxElement.Selected != subtract)
            {
                checkboxElement.Click();
            }
        }
Exemple #30
0
		public async Task ImportAddressAsync(BitcoinAddress address)
		{
			await SendCommandAsync("importaddress", address.ToString()).ConfigureAwait(false);
		}
Exemple #31
0
		public BitcoinSecret DumpPrivKey(BitcoinAddress address)
		{
			var response = SendCommand("dumpprivkey", address.ToString());
			return Network.CreateFromBase58Data<BitcoinSecret>((string)response.Result);
		}
Exemple #32
0
        public void base58_keys_valid_gen()
        {
            var     tests   = TestCase.read_json("data/base58_keys_valid.json");
            Network network = null;

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

                if (isTestnet)
                {
                    network = Network.TestNet;
                }
                else
                {
                    network = Network.Main;
                }
                if (isPrivkey)
                {
                    bool          isCompressed = metadata.isCompressed;
                    Key           key          = new Key(exp_payload, fCompressedIn: isCompressed);
                    BitcoinSecret secret       = network.CreateBitcoinSecret(key);
                    Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
                }
                else
                {
                    string        exp_addrType = (string)metadata.addrType;
                    TxDestination dest;
                    if (exp_addrType == "pubkey")
                    {
                        dest = new KeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "script")
                    {
                        dest = new ScriptId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "none")
                    {
                        dest = new TxDestination(0);
                    }
                    else
                    {
                        Assert.True(false, "Bad addrtype: " + strTest);
                        continue;
                    }
                    try
                    {
                        BitcoinAddress addrOut = network.CreateBitcoinAddress(dest);
                        Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
                    }
                    catch (ArgumentException)
                    {
                        Assert.True(dest.GetType() == typeof(TxDestination));
                    }
                }
            }

            // Visiting a CNoDestination must fail
            TxDestination nodest = new TxDestination();

            Assert.Throws <ArgumentException>(() => network.CreateBitcoinAddress(nodest));
        }
 static public void GetBalance(BitcoinAddress address, NBitcoin.Network network, GetBalanceResponse response, bool includeImmature = false, bool unspentOnly = false, bool colored = true)
 {
     ObservableWWW.Get(URL(network, "balances/" + EscapeUrlPart(address.ToString()) + CreateParameters("includeImmature", includeImmature, "unspentOnly", unspentOnly, "colored", colored))).
     Subscribe(x => response(JsonUtility.FromJson <Models.BalanceModel>(x).Result(), network),
               ex => Debug.Log("error : " + ex.Message));
 }
Exemple #34
0
		public async Task<BitcoinSecret> DumpPrivKeyAsync(BitcoinAddress address)
		{
			var response = await SendCommandAsync("dumpprivkey", address.ToString()).ConfigureAwait(false);
			return Network.CreateFromBase58Data<BitcoinSecret>((string)response.Result);
		}
Exemple #35
0
 public void ImportAddress(BitcoinAddress address)
 {
     SendCommand("importaddress", address.ToString());
 }
Exemple #36
0
 public void ImportAddress(BitcoinAddress address, string label, bool rescan)
 {
     SendCommand("importaddress", address.ToString(), label, rescan);
 }
        public void StoredPartialTransactionsTriggerSignatureRequest()
        {
            var dataFolder = new DataFolder(CreateTestDir(this));

            this.Init(dataFolder);
            this.AddFunding();
            this.AppendBlocks(WithdrawalTransactionBuilder.MinConfirmations);

            MultiSigAddress multiSigAddress = this.wallet.MultiSigAddress;

            using (ICrossChainTransferStore crossChainTransferStore = this.CreateStore())
            {
                crossChainTransferStore.Initialize();
                crossChainTransferStore.Start();

                Assert.Equal(this.ChainIndexer.Tip.HashBlock, crossChainTransferStore.TipHashAndHeight.HashBlock);
                Assert.Equal(this.ChainIndexer.Tip.Height, crossChainTransferStore.TipHashAndHeight.Height);

                BitcoinAddress address1 = (new Key()).PubKey.Hash.GetAddress(this.network);
                BitcoinAddress address2 = (new Key()).PubKey.Hash.GetAddress(this.network);

                var deposit1 = new Deposit(0, new Money(160m, MoneyUnit.BTC), address1.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);
                var deposit2 = new Deposit(1, new Money(60m, MoneyUnit.BTC), address2.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);

                MaturedBlockDepositsModel[] blockDeposits = new[] { new MaturedBlockDepositsModel(
                                                                        new MaturedBlockInfoModel()
                    {
                        BlockHash   = 1,
                        BlockHeight = crossChainTransferStore.NextMatureDepositHeight
                    },
                                                                        new[] { deposit1, deposit2 }) };

                crossChainTransferStore.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();

                Dictionary <uint256, Transaction> transactions = crossChainTransferStore.GetTransactionsByStatusAsync(
                    CrossChainTransferStatus.Partial).GetAwaiter().GetResult();

                var requester = new PartialTransactionRequester(this.loggerFactory, crossChainTransferStore, this.asyncLoopFactory,
                                                                this.nodeLifetime, this.connectionManager, this.federationGatewaySettings);

                var peerEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("1.2.3.4"), 5);
                var peer         = Substitute.For <INetworkPeer>();
                peer.RemoteSocketAddress.Returns(peerEndPoint.Address);
                peer.RemoteSocketPort.Returns(peerEndPoint.Port);
                peer.PeerEndPoint.Returns(peerEndPoint);
                peer.IsConnected.Returns(true);

                var peers = new NetworkPeerCollection();
                peers.Add(peer);

                this.federationGatewaySettings.FederationNodeIpEndPoints.Returns(new[] { peerEndPoint });

                this.connectionManager.ConnectedPeers.Returns(peers);

                requester.Start();

                Thread.Sleep(100);

                peer.Received().SendMessageAsync(Arg.Is <RequestPartialTransactionPayload>(o =>
                                                                                           o.DepositId == 0 && o.PartialTransaction.GetHash() == transactions[0].GetHash())).GetAwaiter().GetResult();

                peer.DidNotReceive().SendMessageAsync(Arg.Is <RequestPartialTransactionPayload>(o =>
                                                                                                o.DepositId == 1 && o.PartialTransaction.GetHash() == transactions[1].GetHash())).GetAwaiter().GetResult();
            }
        }