public void CanExtractTxOutDestinationEasily() { var secret = new BitcoinSecret("KyJTjvFpPF6DDX4fnT56d2eATPfxjdUPXFFUb85psnCdh34iyXRQ"); var tx = new Transaction(); var p2pkh = new TxOut(new Money((UInt64)45000000), secret.GetAddress()); var p2pk = new TxOut(new Money((UInt64)80000000), secret.PrivateKey.PubKey); tx.AddOutput(p2pkh); tx.AddOutput(p2pk); Assert.False(p2pkh.IsTo(secret.PrivateKey.PubKey)); Assert.True(p2pkh.IsTo(secret.GetAddress())); Assert.True(p2pk.IsTo(secret.PrivateKey.PubKey)); Assert.False(p2pk.IsTo(secret.GetAddress())); }
public void EncryptedSecretNoECmultiply() { var tests = new[] { new { Passphrase= "TestingOneTwoThree", Encrypted = "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg", Unencrypted = "5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR", Compressed = false }, new { Passphrase= "Satoshi", Encrypted = "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq", Unencrypted = "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5", Compressed = false }, new { Passphrase= "TestingOneTwoThree", Encrypted = "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo", Unencrypted = "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP", Compressed = true }, new { Passphrase= "Satoshi", Encrypted = "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7", Unencrypted = "KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7", Compressed = true } }; //Slow test, run in parallel Parallel.ForEach(tests, test => { var secret = new BitcoinSecret(test.Unencrypted, Network.Main); var encryptedKey = secret.PrivateKey.GetEncryptedBitcoinSecret(test.Passphrase, Network.Main); Assert.Equal(test.Encrypted, encryptedKey.ToString()); var actualSecret = encryptedKey.GetKey(test.Passphrase); Assert.Equal(test.Unencrypted, actualSecret.GetBitcoinSecret(Network.Main).ToString()); Assert.Equal(test.Compressed, actualSecret.IsCompressed); }); }
public async Task ImportPrivKeyAsync(BitcoinSecret secret) { await SendCommandAsync("importprivkey", secret.ToWif()).ConfigureAwait(false); }
public async Task ImportPrivKeyAsync(BitcoinSecret secret, string label, bool rescan) { await SendCommandAsync(RPCOperations.importprivkey, secret.ToWif(), label, rescan).ConfigureAwait(false); }
public void ImportPrivKey(BitcoinSecret secret) { SendCommand("importprivkey", secret.ToWif()); }
/// <summary> /// Puts data to the blockchain /// </summary> /// <param name="privateKey">you need to have money on it</param> /// <param name="data"></param> /// <returns>transaction id</returns> static string MakePayment(string privateKey, byte[] data) { BitcoinSecret secret = new BitcoinSecret(privateKey); var changeScriptPubKey = secret.ScriptPubKey; #region TxFee // Get and calculate fee WriteLine("Calculating dynamic transaction fee..."); Money satoshiFeePerBytes = null; try { satoshiFeePerBytes = QueryFeePerBytes(); } catch { satoshiFeePerBytes = new Money(100, MoneyUnit.Satoshi); } int inNum = 1; // send from 1 address int outNum = 1; // send back to the same 1 address int maxOpRetOutSize = 80; // max size of OP_RETURN output is 80 byte // Here is how you estimate the fee: http://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending int estimatedTxSize = inNum * 148 + outNum * 34 + 10 + inNum + maxOpRetOutSize; WriteLine($"Estimated tx size: {estimatedTxSize} bytes"); Money fee = satoshiFeePerBytes * estimatedTxSize; WriteLine($"Fee: {fee.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); #endregion //sidenote: I guess you need to deal with the dust limit, too, the testnet doesnt care //something like checking how much money have been sent to the changeScriptPubKey //somehow like this: var dustLimit = new Money(0.001m, MoneyUnit.BTC); var minimumNeededAmount = fee + dustLimit; #region FindCoinsToSpen // Gather coins can be spend WriteLine("Gathering unspent coins..."); Dictionary <Coin, bool> unspentCoins = GetUnspentCoins(secret); // Select coins WriteLine("Selecting coins..."); var coinsToSpend = new HashSet <Coin>(); var unspentConfirmedCoins = new List <Coin>(); var unspentUnconfirmedCoins = new List <Coin>(); foreach (var elem in unspentCoins) { if (elem.Value) { unspentConfirmedCoins.Add(elem.Key); } else { unspentUnconfirmedCoins.Add(elem.Key); } } bool haveEnough = SelectCoins(ref coinsToSpend, minimumNeededAmount, unspentConfirmedCoins); if (!haveEnough) { haveEnough = SelectCoins(ref coinsToSpend, minimumNeededAmount, unspentUnconfirmedCoins); } if (!haveEnough) { throw new Exception("Not enough funds."); } #endregion #region AddData // add data to the transaction var scriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(data); #endregion // Build the transaction WriteLine("Signing transaction..."); var builder = new TransactionBuilder(); var tx = builder .AddCoins(coinsToSpend) .AddKeys(secret) .Send(scriptPubKey, Money.Zero) .SetChange(changeScriptPubKey) .SendFees(fee) .BuildTransaction(true); #region Broadcast if (!builder.Verify(tx)) { throw new Exception("Couldn't build the transaction."); } WriteLine($"Transaction Id: {tx.GetHash()}"); var qBitClient = new QBitNinjaClient(secret.Network); // QBit's success response is buggy so let's check manually, too BroadcastResponse broadcastResponse; var success = false; var tried = 0; var maxTry = 7; do { tried++; WriteLine($"Try broadcasting transaction... ({tried})"); broadcastResponse = qBitClient.Broadcast(tx).Result; var getTxResp = qBitClient.GetTransaction(tx.GetHash()).Result; if (getTxResp == null) { Thread.Sleep(3000); continue; } else { success = true; break; } } while (tried <= maxTry); if (!success) { if (broadcastResponse.Error != null) { WriteLine($"Error code: {broadcastResponse.Error.ErrorCode} Reason: {broadcastResponse.Error.Reason}"); } throw new Exception($"The transaction might not have been successfully broadcasted. Please check the Transaction ID in a block explorer."); } WriteLine("Transaction is successfully propagated on the network.", ConsoleColor.Green); #endregion return(tx.GetHash().ToString()); // txid }
public void ImportPrivKey(BitcoinSecret secret, string label, bool rescan) { SendCommand(RPCOperations.importprivkey, secret.ToWif(), label, rescan); }
public Transaction SendWallMessage(string sourceTxId, string sourcePublicAddress, string stratPrivateKey, string destinationAddress, double amountTx, double feeTx, byte[] bytesMsg) { // RPC Connection to Stratis Blockchain var rpc = GetRPC(); // Can either use the raw transaction hex from a wallet's getrawtransaction CLI command, or look up the equivalent information via RPC Transaction tx = rpc.GetRawTransaction(uint256.Parse(sourceTxId)); // The destination address will receive 0.0001 STRAT BitcoinAddress destAddress = BitcoinAddress.Create(destinationAddress, Network.StratisMain); // Stratis Source Address - The source address is used to store the 'change' from the transaction - THIS IS THE SIGNATURE for the attestation BitcoinAddress sourceAddress = BitcoinAddress.Create(sourcePublicAddress, Network.StratisMain); // The private key must be the key for the source address to be able to send funds from the source address (String of ~52 ASCII) BitcoinSecret sourcePrivateKey = new BitcoinSecret(stratPrivateKey, Network.StratisMain); int outputIndex = 0; int indexTx = 0; TxOutList listOutTx = tx.Outputs; foreach (var item in listOutTx) { string opCode = item.ScriptPubKey.ToString(); if (opCode.StartsWith("OP_DUP OP_HASH160")) { string sAddress = new Script(opCode).GetDestinationAddress(Network.StratisMain).ToString(); if (sAddress.Equals(sourcePublicAddress)) { outputIndex = indexTx; } } ++indexTx; } // For the fee to be correctly calculated, the quantity of funds in the source transaction needs to be known Money remainingBalance = tx.Outputs[outputIndex].Value; // Now that the source Transaction is obtained, the right output needs to be selected as an input for the new transaction. OutPoint outPoint = new OutPoint(tx, outputIndex); // The source transaction's output (must be unspent) is the input for the new transaction Transaction sendTx = new Transaction(); sendTx.Inputs.Add(new TxIn() { PrevOut = outPoint }); // Can currently only send a maximum of 40 bytes in the null data transaction (bytesMsg) // Also note that a nulldata transaction currently has to have a nonzero value assigned to it. TxOut messageTxOut = new TxOut() { Value = new Money((decimal)0.0001, MoneyUnit.BTC), ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytesMsg) }; // For Attestation amountTx = 0.0001 STRAT is being sent to destAddress TxOut destTxOut = new TxOut() { Value = new Money((decimal)amountTx, MoneyUnit.BTC), ScriptPubKey = destAddress.ScriptPubKey }; double discBalance = feeTx + amountTx + 0.0001; // 0.0001 : nulldata transaction amount // This is what subsequent transactions use to prove ownership of the funds (more specifically, the private key used to create the ScriptPubKey is known) // Send the change back to the originating address. TxOut changeBackTxOut = new TxOut() { Value = new Money(((remainingBalance.ToDecimal(MoneyUnit.BTC) - (decimal)discBalance)), MoneyUnit.BTC), ScriptPubKey = sourceAddress.ScriptPubKey }; // changeBackTxOut = remainingBalance - 0.0001 (sent) - 0.0001 (network fee) - 0.0001 (nulldata) // Transactions without fees may violate consensus rules, or may not be relayed by other nodes on the network. // Add the outputs to the transaction being built sendTx.Outputs.Add(destTxOut); sendTx.Outputs.Add(messageTxOut); sendTx.Outputs.Add(changeBackTxOut); // Signing the transaction sendTx.Inputs[0].ScriptSig = sourceAddress.ScriptPubKey; // Sign the transaction using the specified private key sendTx.Sign(sourcePrivateKey, false); // Broadcast Transaction rpc.SendRawTransactionAsync(sendTx); return(sendTx); }
/// <summary> /// A default constructor of Wallet service. (Need to initialized from a ContractService object.) /// </summary> /// <param name="contract">A wallet contract object</param> /// <param name="contractService">A wallet contract service object</param> /// <param name="db">LiteDB database object</param> /// <param name="userPrivateKey">User's private key</param> /// <param name="api">Insight-based compatible API (>0.4)</param> /// <param name="TransferFee">Fee for token transfer</param> /// <returns>A wallet service is used to obtain all the ledger from the wallet. Private key is used to create the ledger on the user's behalf.</returns> internal WalletService(WalletContract contract, ContractService contractService, LiteDatabase db, BitcoinSecret userPrivateKey, IInsightAPI api, decimal TransferFee) { this.TransferFee = TransferFee; this.userPrivateKey = userPrivateKey; this.contractService = contractService; this.contract = contract; this.api = api; this.db = db; byte[] myByte = Encoding.ASCII.GetBytes(contract.ID); var encrypted = NBitcoin.Crypto.Hashes.RIPEMD160(myByte, myByte.Length); var hashID = encrypted.ByteArrayToString(); ledger = db.GetCollection <Ledger>($"Ledger-{hashID}"); account = db.GetCollection <Account>($"Account-{hashID}"); ownerAddress = new BitcoinPubKeyAddress(contract.OwnerPublicAddress, contractService.MainNetwork); }
static void Main(string[] args) { decimal subbuCoin1 = 0; decimal subbuCoin2 = 0; decimal sendAmount = 0; int blockCount = 0; int option = 0; RandomUtils.Random = new UnsecureRandom(); List <Transaction> transactionList = new List <Transaction>(); DateTimeOffset current = DateTimeOffset.UtcNow; ConcurrentChain chain = new ConcurrentChain(Network.Main); Key subbuPrivateKey = new Key(); Key swethaPrivateKey = new Key(); Key adityaPrivateKey = new Key(); Key kavyaPrivateKey = new Key(); BitcoinSecret subbu = subbuPrivateKey.GetBitcoinSecret(Network.Main); BitcoinSecret swetha = swethaPrivateKey.GetBitcoinSecret(Network.Main); BitcoinSecret aditya = adityaPrivateKey.GetBitcoinSecret(Network.Main); BitcoinSecret kavya = kavyaPrivateKey.GetBitcoinSecret(Network.Main); Console.WriteLine("\n Enter first coin value:"); subbuCoin1 = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("\n Enter second coin value:"); subbuCoin2 = Convert.ToDecimal(Console.ReadLine()); decimal totalAmount = subbuCoin1 + subbuCoin2; Console.WriteLine("\n Total Coins Value: " + totalAmount); while (blockCount != 5) { while (option != 1) { Console.WriteLine("\n Enter Send amount:"); sendAmount = Convert.ToDecimal(Console.ReadLine()); Transaction subbuFunding = new Transaction() { Outputs = { new TxOut(subbuCoin1.ToString(), subbu.GetAddress()), new TxOut(subbuCoin2.ToString(), subbu.PubKey) } }; Coin[] subbuCoins = subbuFunding .Outputs .Select((o, i) => new Coin(new OutPoint(subbuFunding.GetHash(), i), o)) .ToArray(); var txBuilder = new TransactionBuilder(); var tx = txBuilder .AddCoins(subbuCoins) .AddKeys(subbu.PrivateKey) .Send(swetha.GetAddress(), sendAmount.ToString()) .SendFees("0.001") .SetChange(subbu.GetAddress()) .BuildTransaction(true); Console.WriteLine(tx); Console.ReadLine(); transactionList.Add(tx); Console.WriteLine("Press 1 for Mine block or 2 go to next transaction:"); option = int.Parse(Console.ReadLine()); } chain.SetTip(CreateBlock(current, blockCount, transactionList, chain)); blockCount++; option = 0; } }
private void TestDERCoherence(BitcoinSecret secret) { var serializedSecret = secret.PrivateKey.ToDER(); var deserializedSecret = ECKey.FromDER(serializedSecret); AssertEx.CollectionEquals(secret.PrivateKey.ToDER(), deserializedSecret.ToDER(secret.PrivateKey.IsCompressed)); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Please enter a valid question number as commande line argument"); } else if (args.First() == "Question-1") { Key privateKey = new Key(); // generate a random private key PubKey publicKey = privateKey.PubKey; // Get the public key //Console.WriteLine(publicKey); Console.WriteLine(privateKey.ToString(Network.TestNet)); var mainnetAddress = publicKey.GetAddress(Network.Main); //Mainnet address var testnetAddress = publicKey.GetAddress(Network.TestNet); // Testnet address string walletInfo = privateKey.ToString(Network.TestNet) + "@" + mainnetAddress.ToString() + "@" + testnetAddress.ToString(); walletInfo = walletInfo.Replace("@", System.Environment.NewLine); System.IO.File.WriteAllText("C:\\Users\\Mathieu\\Documents\\Blockchain\\wallet2.txt", walletInfo); // Generate QR-code QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(testnetAddress.ToString(), QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(11); // Print the bitmap PrintDocument pd = new PrintDocument(); pd.PrintPage += (thesender, ev) => { float x = 230.0F; float y = 320.0F; RectangleF srcRect = new RectangleF(40.0F, 40.0F, 600.0F, 600.0F); GraphicsUnit units = GraphicsUnit.Pixel; ev.Graphics.DrawImage(qrCodeImage, x, y, srcRect, units); }; pd.Print(); } else if (args.First() == "Question-2") { Key privateKey = new Key(); // generate a random private key PubKey publicKey = privateKey.PubKey; // Get the public key var vanityAddress = publicKey.GetAddress(Network.TestNet); //TestNet address string Text = vanityAddress.ToString(); while (Text.Substring(1, 4).Equals("math", StringComparison.CurrentCultureIgnoreCase) == false) { privateKey = new Key(); // generate a random private key publicKey = privateKey.PubKey; // Get the public key vanityAddress = publicKey.GetAddress(Network.TestNet); //TestNet address Text = vanityAddress.ToString(); } Console.WriteLine(vanityAddress.ToString()); string walletInfo = privateKey.ToString(Network.TestNet) + "@" + vanityAddress.ToString(); walletInfo = walletInfo.Replace("@", System.Environment.NewLine); System.IO.File.WriteAllText("C:\\Users\\Mathieu\\Documents\\Blockchain\\vanity2.txt", walletInfo); } else if (args.First() == "Question-3") { // Create a client QBitNinjaClient client = new QBitNinjaClient(Network.Main); string TXID = "12bec2fe21387b60c33f2e766557dfeb8b9f1b75d505745f11100d6b2425cf9f"; // Parse transaction id to NBitcoin.uint256 so the client can eat it var transactionId = uint256.Parse(TXID); // Query the transaction GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; Console.WriteLine(); Console.WriteLine(); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine("--------------------------------------------------------------------------"); // Outputs of the transaction = Received Coins Console.WriteLine("Output associated to TX = " + TXID); Console.WriteLine(); List <ICoin> receivedCoins = transactionResponse.ReceivedCoins; Money receivedAmount = Money.Zero; foreach (var coinR in receivedCoins) { Money amount = (Money)coinR.Amount; Console.WriteLine("Amount = " + amount.ToDecimal(MoneyUnit.BTC) + " BTC"); var paymentScript = coinR.TxOut.ScriptPubKey; Console.WriteLine("ScriptPubKey = \"" + paymentScript + "\""); // It's the ScriptPubKey var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine("Going to address : " + address); receivedAmount = (Money)coinR.Amount.Add(receivedAmount); Console.WriteLine(); } Console.WriteLine("Total output amount = " + receivedAmount.ToDecimal(MoneyUnit.BTC) + " BTC"); Console.WriteLine("--------------------------------------------------------------------------"); // Inputs of the transaction Console.WriteLine("Inputs associated to TX = " + TXID); Console.WriteLine(); List <ICoin> spentCoins = transactionResponse.SpentCoins; Money spentAmount = Money.Zero; foreach (var coinS in spentCoins) { Money amount = (Money)coinS.Amount; Console.WriteLine("Amount = " + amount.ToDecimal(MoneyUnit.BTC) + " BTC"); var paymentScript = coinS.TxOut.ScriptPubKey; Console.WriteLine("ScriptPubKey = \"" + paymentScript + "\""); // It's the ScriptPubKey var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine("Coming from address : " + address); spentAmount = (Money)coinS.Amount.Add(spentAmount); Console.WriteLine(); } Console.WriteLine("Total input amount = " + spentAmount.ToDecimal(MoneyUnit.BTC) + " BTC"); Console.WriteLine("--------------------------------------------------------------------------"); // Now looking at the fees NBitcoin.Transaction transaction = transactionResponse.Transaction; var fee = transaction.GetFee(spentCoins.ToArray()); Console.WriteLine("Transaction fees = " + fee.ToString() + " BTC"); Console.WriteLine("--------------------------------------------------------------------------"); var inputs = transaction.Inputs; foreach (TxIn input in inputs) { OutPoint previousOutpoint = input.PrevOut; Console.WriteLine("Previous TX hash : " + previousOutpoint.Hash); // hash of prev tx Console.WriteLine("Previous TX index : " + previousOutpoint.N); // idx of out from prev tx, that has been spent in the current tx Console.WriteLine(); } Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine(); // Getting the balance from the address string copayAddress = "mz2oHHuMqnJg2grqCrKRDGs2vwG5dwNDRu"; BitcoinAddress WalletAddress = new BitcoinPubKeyAddress(copayAddress, Network.TestNet); QBitNinjaClient testnetClient = new QBitNinjaClient(Network.TestNet); var balanceModel = testnetClient.GetBalance(WalletAddress).Result; var unspentCoins = new List <Coin>(); foreach (var operation in balanceModel.Operations) { unspentCoins.AddRange(operation.ReceivedCoins.Select(coin => coin as Coin)); } var balance = unspentCoins.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC)); Console.WriteLine(); Console.WriteLine("Copay Address = " + copayAddress); Console.WriteLine("Total balance = " + balance.ToString()); // Get all operations for that address if (balanceModel.Operations.Count > 0) { foreach (var operation in balanceModel.Operations) { // We take the transaction ID var TXIDb = operation.TransactionId; GetTransactionResponse transactionResponseb = testnetClient.GetTransaction(TXIDb).Result; NBitcoin.Transaction transactionb = transactionResponse.Transaction; Console.WriteLine(); Console.WriteLine("Transaction list for the address : "); Console.WriteLine(); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine("--------------------------------------------------------------------------"); // Outputs of the transaction = Received Coins Console.WriteLine("Transaction ID : " + TXIDb); Console.WriteLine(); Console.WriteLine("OUTPUTS"); Console.WriteLine(); List <ICoin> receivedCoinsb = transactionResponseb.ReceivedCoins; foreach (var coinR in receivedCoinsb) { Money amount = (Money)coinR.Amount; Console.WriteLine("Amount = " + amount.ToDecimal(MoneyUnit.BTC) + " BTC"); var paymentScript = coinR.TxOut.ScriptPubKey; var address = paymentScript.GetDestinationAddress(Network.TestNet); Console.WriteLine("Going to address : " + address); Console.WriteLine(); } Console.WriteLine("--------------------------------------------------------------------------"); // Inputs of the transaction Console.WriteLine("INPUTS"); Console.WriteLine(); List <ICoin> spentCoinsb = transactionResponseb.SpentCoins; foreach (var coinS in spentCoinsb) { Money amount = (Money)coinS.Amount; Console.WriteLine("Amount = " + amount.ToDecimal(MoneyUnit.BTC) + " BTC"); var paymentScript = coinS.TxOut.ScriptPubKey; var address = paymentScript.GetDestinationAddress(Network.TestNet); Console.WriteLine("Coming from address : " + address); Console.WriteLine(); } Console.WriteLine("--------------------------------------------------------------------------"); // Now looking at the fees var feeb = transactionb.GetFee(spentCoinsb.ToArray()); Console.WriteLine("Transaction fees = " + feeb.ToString() + " BTC"); Console.WriteLine("--------------------------------------------------------------------------"); var inputsb = transactionb.Inputs; foreach (TxIn input in inputsb) { OutPoint previousOutpoint = input.PrevOut; Console.WriteLine("Previous TX hash : " + previousOutpoint.Hash); // hash of prev tx Console.WriteLine("Previous TX index : " + previousOutpoint.N); // idx of out from prev tx, that has been spent in the current tx Console.WriteLine(); } Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine(); } } // List of UTXO Console.WriteLine(); Console.WriteLine("List of UTXO"); foreach (var c in unspentCoins) { Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine(c.Outpoint.ToString()); Console.WriteLine(); } } else if (args.First() == "Question-4") { // Sending a transaction var bitcoinPrivateKey = new BitcoinSecret("cP8UmUrZgiRfQZF9C7VYvJQuPK2Ao9ZTnR1BcZ79hADqn9yNTFXg"); var network = bitcoinPrivateKey.Network; var address = bitcoinPrivateKey.GetAddress(); var client = new QBitNinjaClient(Network.TestNet); var transactionId = uint256.Parse("9e698153d261be07b939ee3e4638b0c09eb466b485f2e09eded5a5eb6fff0519"); var transactionResponse = client.GetTransaction(transactionId).Result; // From where ? var receivedCoins = transactionResponse.ReceivedCoins; OutPoint outPointToSpend = null; foreach (var coin in receivedCoins) { if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey) { outPointToSpend = coin.Outpoint; } } if (outPointToSpend == null) { throw new Exception("TxOut doesn't contain our ScriptPubKey"); } Console.WriteLine("We want to spend {0}. outpoint:", outPointToSpend.N + 1); var transaction = Transaction.Create(network); transaction.Inputs.Add(new TxIn() { PrevOut = outPointToSpend }); // To where ? var CopayAddress = new BitcoinPubKeyAddress("mokLh8W4J4DzZpj2XyEhE1ReZf5BnsSZcs"); // How much we want to spend var CopayAmount = new Money(0.08m, MoneyUnit.BTC); // How much miner fee we want to pay var minerFee = new Money(0.0001m, MoneyUnit.BTC); // How much we want to get back as change var txInAmount = (Money)receivedCoins[(int)outPointToSpend.N].Amount; var changeAmount = txInAmount - CopayAmount - minerFee; TxOut CopayTxOut = new TxOut() { Value = CopayAmount, ScriptPubKey = CopayAddress.ScriptPubKey }; TxOut changeTxOut = new TxOut() { Value = changeAmount, ScriptPubKey = bitcoinPrivateKey.ScriptPubKey }; transaction.Outputs.Add(CopayTxOut); transaction.Outputs.Add(changeTxOut); // We can use the private key to sign transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey; transaction.Sign(bitcoinPrivateKey, receivedCoins.ToArray()); BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result; if (!broadcastResponse.Success) { Console.Error.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode); Console.Error.WriteLine("Error message: " + broadcastResponse.Error.Reason); } else { Console.WriteLine("Success! Hash of the transaction :"); Console.WriteLine(transaction.GetHash()); } // Confirmations of the transaction var newTXID = uint256.Parse("4777e829eabd4dd5821153d016e5f3256998e962d0e10af1935bfd7ee95e45d0"); int n = 0; while (n < 10) { GetTransactionResponse newTXResponse = client.GetTransaction(newTXID).Result; Console.WriteLine(); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine("Current number of confirmations : " + newTXResponse.Block.Confirmations); Console.WriteLine("--------------------------------------------------------------------------"); Console.WriteLine(); System.Threading.Thread.Sleep(10000); n++; } } else if (args.First() == "Question-5") { // We identify the blocks in question // And we create a list of address that have received these coinbase transactions var client = new QBitNinjaClient(Network.Main); var blockHeight = new BlockFeature(2); var blockResponse = client.GetBlock(blockHeight).Result; var TX = blockResponse.Block.Transactions.First(); var reward = TX.Outputs.First(); var nextAddr = reward.ScriptPubKey.GetDestinationAddress(Network.Main); Console.WriteLine(nextAddr); } }
internal string[] SignSGAMessageOut(int[] SecretSalt, int[] SecretPW, string sgaMessage) { try { ExtKey masterKey = GetExtKey(SecretSalt, SecretPW); ExtKey masterKeyD = masterKey.Derive(GetCurrencyIndex("btc"), hardened: true); ExtKey key = masterKeyD.Derive((uint)0); byte[] keybytes = key.PrivateKey.ToBytes(); Key pkey = new Key(keybytes, -1, false); BitcoinSecret bitcoinSecret = new BitcoinSecret(pkey, Network.Main); var address = bitcoinSecret.PubKey.GetAddress(GetBLKNetworkAlt("btc")).ToString(); var signature = bitcoinSecret.PrivateKey.SignMessage(sgaMessage); Sclear.EraseBytes(keybytes); masterKeyD = null; key = null; pkey = null; NWS WS = new NWS(); List <BitfiWallet.NOXWS.NoxAddresses> lnoxAddresses = new List <BitfiWallet.NOXWS.NoxAddresses>(); string adrlist = JsonConvert.SerializeObject(lnoxAddresses); string tkmsg = WS.GetSGAToken(address, signature); if (tkmsg.Length < 10) { return(new string[2] { tkmsg, adrlist }); } var objaddrListindexes = WS.GetAddressIndexes(tkmsg); if (objaddrListindexes != null) { lnoxAddresses = GetReviewIndexes(objaddrListindexes, masterKey); adrlist = JsonConvert.SerializeObject(lnoxAddresses); } else { tkmsg = "1"; } return(new string[2] { tkmsg, adrlist }); } catch { return(new string[2] { "4", "" }); } }
static void Main(string[] args) { Network network = Network.TestNet; var treasurer = new BitcoinSecret("key") var alice = new BitcoinSecret("key"); Console.WriteLine("treasurer key: " + treasurer.PrivateKey.GetWif(network)); Console.WriteLine("Alice key: " + alice.PrivateKey.GetWif(network)); var scriptPubKey = PayToMultiSigTemplate .Instance .GenerateScriptPubKey(2, new[] { alice.PubKey, treasurer.PubKey }); Console.WriteLine("PubKey script: " + scriptPubKey); var redeemScript = PayToMultiSigTemplate .Instance .GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, treasurer.PubKey }); var paymentScript = redeemScript.PaymentScript; Console.WriteLine("paymentScript: " + paymentScript); Console.WriteLine("multi-sig address: " + redeemScript.Hash.GetAddress(network)); var client = new QBitNinjaClient(network); // Update var receiveTransactionId = uint256.Parse("yourid"); var receiveTransactionResponse = client.GetTransaction(receiveTransactionId).Result; Console.WriteLine(receiveTransactionResponse.TransactionId); var receiveTransactionResponse = client.GetTransaction(receiveTransactionId).Result; Console.WriteLine(receiveTransactionResponse.TransactionId); Console.WriteLine(receiveTransactionResponse.Block.Confirmations); var receivedCoins = receiveTransactionResponse.ReceivedCoins; OutPoint outpointToSpend = null; ScriptCoin coinToSpend = null; foreach (var c in receivedCoins) { try { coinToSpend = new ScriptCoin(c.Outpoint, c.TxOut, redeemScript); outpointToSpend = c.Outpoint; break; } catch { } if (outpointToSpend == null) throw new Exception("TxOut doesn't contain any our ScriptPubKey"); Console.WriteLine("outpoint #{0}"); var lucasAddress = BitcoinAddress.Create("address", network); TransactionBuilder builder = network.CreateTransactionBuilder(); var minerFee = new Money(0.0005m, MoneyUnit.BTC); var txInAmount = (Money)receivedCoins[(int)outpointToSpend.N].Amount; var sendAmount = txInAmount - minerFee; Transaction unsigned = builder .AddCoins(coinToSpend) .Send(lucasAddress, sendAmount) .SetChange(lucasAddress, ChangeType.Uncolored) .BuildTransaction(sign: false); Transaction aliceSigned = builder .AddCoins(coinToSpend) .AddKeys(alice) Transaction bobSigned = builder .AddCoins(coinToSpend) .AddKeys(bob) .SignTransaction(aliceSigned);
public void SetDummyMinerSecret(BitcoinSecret secret) { this.MinerSecret = secret; }
public Block[] GenerateStratis(int blockCount, List <Transaction> passedTransactions = null, bool broadcast = true) { var fullNode = (this.runner as StratisBitcoinPowRunner).FullNode; BitcoinSecret dest = this.MinerSecret; List <Block> blocks = new List <Block>(); DateTimeOffset now = this.MockTime == null ? DateTimeOffset.UtcNow : this.MockTime.Value; #if !NOSOCKET for (int i = 0; i < blockCount; i++) { uint nonce = 0; Block block = new Block(); block.Header.HashPrevBlock = fullNode.Chain.Tip.HashBlock; block.Header.Bits = block.Header.GetWorkRequired(fullNode.Network, fullNode.Chain.Tip); block.Header.UpdateTime(now, fullNode.Network, fullNode.Chain.Tip); var coinbase = new Transaction(); coinbase.AddInput(TxIn.CreateCoinbase(fullNode.Chain.Height + 1)); coinbase.AddOutput(new TxOut(fullNode.Network.GetReward(fullNode.Chain.Height + 1), dest.GetAddress())); block.AddTransaction(coinbase); if (passedTransactions?.Any() ?? false) { passedTransactions = this.Reorder(passedTransactions); block.Transactions.AddRange(passedTransactions); } block.UpdateMerkleRoot(); while (!block.CheckProofOfWork(fullNode.Network.Consensus)) { block.Header.Nonce = ++nonce; } blocks.Add(block); if (broadcast) { uint256 blockHash = block.GetHash(); var newChain = new ChainedBlock(block.Header, blockHash, fullNode.Chain.Tip); var oldTip = fullNode.Chain.SetTip(newChain); fullNode.ConsensusLoop().Puller.InjectBlock(blockHash, new DownloadedBlock { Length = block.GetSerializedSize(), Block = block }, CancellationToken.None); //try //{ // var blockResult = new BlockResult { Block = block }; // fullNode.ConsensusLoop.AcceptBlock(blockResult); // // similar logic to what's in the full node code // if (blockResult.Error == null) // { // fullNode.ChainBehaviorState.ConsensusTip = fullNode.ConsensusLoop.Tip; // //if (fullNode.Chain.Tip.HashBlock == blockResult.ChainedBlock.HashBlock) // //{ // // var unused = cache.FlushAsync(); // //} // fullNode.Signals.Blocks.Broadcast(block); // } //} //catch (ConsensusErrorException) //{ // // set back the old tip // fullNode.Chain.SetTip(oldTip); //} } } return(blocks.ToArray()); #endif }
public void NonStandardScriptPubKeyDoesNotReturnsWrongBalance() { using(var tester = CreateTester()) { var bob = new Key(); var alice = new Key(); BalanceId bobId = new BalanceId(bob); NonStandardScriptPubKeyDoesNotReturnsWrongBalanceCore(tester, bob, alice, bobId); bob = new Key(); alice = new Key(); bobId = new BalanceId("bob"); tester.Client.AddWalletRule("bob", new ScriptRule() { ScriptPubKey = bob.ScriptPubKey }); NonStandardScriptPubKeyDoesNotReturnsWrongBalanceCore(tester, bob, alice, bobId); bob = new Key(); alice = new Key(); bobId = new BalanceId("bob2"); tester.Client.AddWalletRule("bob2", new ScriptRule() { ScriptPubKey = bob.ScriptPubKey }); var chainBuilder = tester.CreateChainBuilder(); List<Coin> bobCoins = new List<Coin>(); bobCoins.AddRange(chainBuilder.EmitMoney(bob, "50.0").Outputs.AsCoins()); bobCoins.AddRange(chainBuilder.EmitMoney(bob, "5.0").Outputs.AsCoins()); bobCoins.AddRange(chainBuilder.EmitMoney(bob, "15.0").Outputs.AsCoins()); var prev = chainBuilder.Emit(new Transaction() { Outputs = { new TxOut(Money.Coins(1.0m), bob.ScriptPubKey + OpcodeType.OP_NOP), new TxOut(Money.Coins(1.5m), bob.ScriptPubKey + OpcodeType.OP_NOP), new TxOut(Money.Coins(2.0m), bob.ScriptPubKey + OpcodeType.OP_NOP), } }); bobCoins.AddRange(prev.Outputs.AsCoins()); Shuffle(bobCoins); chainBuilder.SubmitBlock(); chainBuilder.SyncIndexer(); var bobBalance = tester.Client.GetOrderedBalance(bobId).ToArray(); Assert.True(bobBalance.Length == 3); var tx = new Transaction(); foreach(var coin in bobCoins) { tx.Inputs.Add(new TxIn() { PrevOut = coin.Outpoint, ScriptSig = bob.ScriptPubKey }); } tx.Outputs.Add(new TxOut(Money.Coins(0.1m), alice)); tx.Sign(bob, false); chainBuilder.Emit(tx); chainBuilder.SubmitBlock(); chainBuilder.SyncIndexer(); for(int i = 0; i < 2; i++) { bobBalance = tester.Client.GetOrderedBalance(bobId).ToArray(); Assert.True(bobBalance.Length == 4); //OP_NOP spending should not appear Assert.True(bobBalance[0].SpentCoins.Count == 3); foreach(var coin in bobBalance[0].SpentCoins) { Assert.Equal(bob.ScriptPubKey, coin.TxOut.ScriptPubKey); } } } }
public void MempoolSyncTransactions() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisNodeSync = builder.CreateStratisPowNode(this.network); CoreNode stratisNode1 = builder.CreateStratisPowNode(this.network); CoreNode stratisNode2 = builder.CreateStratisPowNode(this.network); builder.StartAll(); stratisNodeSync.NotInIBD(); stratisNode1.NotInIBD(); stratisNode2.NotInIBD(); // generate blocks and wait for the downloader to pickup stratisNodeSync.SetDummyMinerSecret(new BitcoinSecret(new Key(), stratisNodeSync.FullNode.Network)); stratisNodeSync.GenerateStratisWithMiner(105); // coinbase maturity = 100 // wait for block repo for block sync to work TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(stratisNodeSync)); // sync both nodes stratisNode1.CreateRPCClient().AddNode(stratisNodeSync.Endpoint, true); stratisNode2.CreateRPCClient().AddNode(stratisNodeSync.Endpoint, true); TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(stratisNode1, stratisNodeSync)); TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(stratisNode2, stratisNodeSync)); // create some transactions and push them to the pool var trxs = new List <Transaction>(); foreach (int index in Enumerable.Range(1, 5)) { Block block = stratisNodeSync.FullNode.BlockStore().GetBlockAsync(stratisNodeSync.FullNode.Chain.GetBlock(index).HashBlock).Result; Transaction prevTrx = block.Transactions.First(); var dest = new BitcoinSecret(new Key(), stratisNodeSync.FullNode.Network); Transaction tx = stratisNodeSync.FullNode.Network.CreateTransaction(); tx.AddInput(new TxIn(new OutPoint(prevTrx.GetHash(), 0), PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(stratisNodeSync.MinerSecret.PubKey))); tx.AddOutput(new TxOut("25", dest.PubKey.Hash)); tx.AddOutput(new TxOut("24", new Key().PubKey.Hash)); // 1 btc fee tx.Sign(stratisNodeSync.FullNode.Network, stratisNodeSync.MinerSecret, false); trxs.Add(tx); } var options = new ParallelOptions { MaxDegreeOfParallelism = 5 }; Parallel.ForEach(trxs, options, transaction => { stratisNodeSync.Broadcast(transaction); }); // wait for all nodes to have all trx TestHelper.WaitLoop(() => stratisNodeSync.CreateRPCClient().GetRawMempool().Length == 5); // the full node should be connected to both nodes Assert.True(stratisNodeSync.FullNode.ConnectionManager.ConnectedPeers.Count() >= 2); TestHelper.WaitLoop(() => stratisNode1.CreateRPCClient().GetRawMempool().Length == 5); TestHelper.WaitLoop(() => stratisNode2.CreateRPCClient().GetRawMempool().Length == 5); // mine the transactions in the mempool stratisNodeSync.GenerateStratisWithMiner(1); TestHelper.WaitLoop(() => stratisNodeSync.CreateRPCClient().GetRawMempool().Length == 0); // wait for block and mempool to change TestHelper.WaitLoop(() => stratisNode1.CreateRPCClient().GetBestBlockHash() == stratisNodeSync.CreateRPCClient().GetBestBlockHash()); TestHelper.WaitLoop(() => stratisNode2.CreateRPCClient().GetBestBlockHash() == stratisNodeSync.CreateRPCClient().GetBestBlockHash()); TestHelper.WaitLoop(() => stratisNode1.CreateRPCClient().GetRawMempool().Length == 0); TestHelper.WaitLoop(() => stratisNode2.CreateRPCClient().GetRawMempool().Length == 0); } }
public static void Play() { new Key().PubKey.WitHash.GetAddress(Network.SegNet).ToString(); var node = Node.Connect(Network.SegNet, "qbitninja-server.cloudapp.net"); node.VersionHandshake(); uint256 p2wsh = null; uint256 p2pwkh = null; uint256 p2wshp2sh = null; uint256 p2wpkhp2sh = null; foreach(var block in node.GetBlocks()) { foreach(var tx in block.Transactions) { if(p2wsh != null && p2pwkh != null && p2wshp2sh != null && p2wpkhp2sh != null) break; if(!tx.IsCoinBase && !tx.Witness.IsEmpty) { foreach(var input in tx.Inputs.AsIndexedInputs()) { if(input.WitScript == WitScript.Empty) continue; if(input.ScriptSig == Script.Empty) { if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null) p2pwkh = tx.GetHash(); else p2wsh = tx.GetHash(); } else { if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null) p2wpkhp2sh = tx.GetHash(); else p2wshp2sh = tx.GetHash(); } break; } } } } var secret = new BitcoinSecret("QTrKVpsVwNUD9GayzdbUNz2NNDqiPgjd9RCprwSa4gmBFg3V2oik", Network.SegNet); var oo = secret.PubKey.WitHash.GetAddress(Network.SegNet); var key = new Key().GetBitcoinSecret(Network.SegNet); var aa = key.GetAddress(); foreach(var n in new[]{Network.Main, Network.SegNet}) { for(int i = 0; i < 2;i++) { BitcoinAddress addr = i == 0 ? (BitcoinAddress)new Key().PubKey.GetSegwitAddress(n) : new Key().ScriptPubKey.GetWitScriptAddress(n); var c = addr.ScriptPubKey.ToString(); } } var networks = Network.GetNetworks().ToArray(); List<Conflict> conflicts = new List<Conflict>(); for(int n = 0 ; n < networks.Length ; n++) { for(int n2 = n+1; n2 < networks.Length ; n2++) { var a = networks[n]; var b = networks[n2]; if(a == Network.RegTest || b == Network.RegTest) continue; if(a == b) throw new Exception(); for(int i = 0 ; i < a.base58Prefixes.Length ; i++) { for(int y = i + 1 ; y < a.base58Prefixes.Length ; y++) { if(a.base58Prefixes[i] != null && b.base58Prefixes[y] != null) { var ae = Encoders.Hex.EncodeData(a.base58Prefixes[i]); var be = Encoders.Hex.EncodeData(b.base58Prefixes[y]); if(ae == be) continue; if(ae.StartsWith(be) || be.StartsWith(ae)) { ConflictPart ca = new ConflictPart(); ca.Network = a; ca.Type = (Base58Type)i; ca.Value = a.base58Prefixes[i]; ConflictPart cb = new ConflictPart(); cb.Network = b; cb.Type = (Base58Type)y; cb.Value = b.base58Prefixes[y]; Conflict cc = new Conflict(); cc.A = ca; cc.B = cb; conflicts.Add(cc); } } } } } } var rr = String.Join("\r\n", conflicts.OfType<object>().ToArray()); Console.WriteLine(); //ConcurrentChain chain = new ConcurrentChain(Network.Main); //ChainBehavior chainBehavior = new ChainBehavior(chain); //NodeConnectionParameters para = new NodeConnectionParameters(); //para.TemplateBehaviors.Add(chainBehavior); //NodesGroup group = new NodesGroup(Network.Main, para); //group.Connect(); //while(true) //{ // Thread.Sleep(1000); //} //Parallel.ForEach(Enumerable.Range(0, 10), _ => //{ // ConcurrentChain chain = new ConcurrentChain(Network.Main); // node.SynchronizeChain(chain); //}); //Wallet wallet = new Wallet(new ExtKey(), Network.Main); //wallet.Connect(addrman: AddressManager.LoadPeerFile(@"E:\Program Files\Bitcoin\peers.dat", Network.Main)); //while(true) //{ // Thread.Sleep(1000); // Console.WriteLine(wallet.ConnectedNodes + " " + wallet.State); //} //var node = Node.ConnectToLocal(Network.Main); //node.VersionHandshake(); //var chain = node.GetChain(); //var v3 = chain.Tip // .EnumerateToGenesis() // .Take(1000) // .Aggregate(0, (a, b) => b.Header.Version == 3 ? a+1 : a); //var r = (double)v3 / (double)1000; Stopwatch watch = new Stopwatch(); watch.Start(); System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.Net.ServicePointManager.Expect100Continue = false; var repo = new QBitNinjaTransactionRepository("http://rapidbase-test.azurewebsites.net/"); var colored = new OpenAsset.NoSqlColoredTransactionRepository(repo); var result = repo .Get("c3462373f1a722c66cbb1b93712df94aa7b3731f4142cd8413f10c9e872927de") .GetColoredTransaction(colored); watch.Stop(); //for(int i = 0 ; i < 100 ; i++) //{ // using(var node = Node.ConnectToLocal(Network.Main)) // { // node.VersionHandshake(); // var chain = new ConcurrentChain(Network.Main); // node.SynchronizeChain(chain); // } //} }
public void base58_keys_valid_parse() { TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid.json")); Network network; foreach (TestCase test in tests) { string strTest = test.ToString(); if (test.Count < 3) // Allow for extra stuff (useful for comments) { Assert.True(false, "Bad test " + strTest); continue; } string exp_base58string = (string)test[0]; byte[] exp_payload = TestUtils.ParseHex((string)test[1]); //const Object &metadata = test[2].get_obj(); bool isPrivkey = (bool)test.GetDynamic(2).isPrivkey; bool isTestnet = (bool)test.GetDynamic(2).isTestnet; if (isTestnet) { network = KnownNetworks.TestNet; } else { network = KnownNetworks.Main; } if (isPrivkey) { bool isCompressed = (bool)test.GetDynamic(2).isCompressed; // Must be valid private key // Note: CBitcoinSecret::SetString tests isValid, whereas CBitcoinAddress does not! BitcoinSecret secret = network.CreateBitcoinSecret(exp_base58string); //If not valid exception would throw Key privkey = secret.PrivateKey; Assert.True(privkey.IsCompressed == isCompressed, "compressed mismatch:" + strTest); Assert.True(Utils.ArrayEqual(privkey.ToBytes(), exp_payload), "key mismatch:" + strTest); // Private key must be invalid public key Assert.Throws <FormatException>(() => network.CreateBitcoinAddress(exp_base58string)); } else { string exp_addrType = (string)test.GetDynamic(2).addrType; // "script" or "pubkey" // Must be valid public key BitcoinAddress addr = network.CreateBitcoinAddress(exp_base58string); Assert.True((addr is BitcoinScriptAddress) == (exp_addrType == "script"), "isScript mismatch" + strTest); if (exp_addrType == "script") { Assert.True(addr.GetType() == typeof(BitcoinScriptAddress)); } if (exp_addrType == "pubkey") { Assert.True(addr.GetType() == typeof(BitcoinPubKeyAddress)); } Assert.Throws <FormatException>(() => network.CreateBitcoinSecret(exp_base58string)); } } }
public static void Play() { Transaction txxxxx = new Transaction("0100000000010213206299feb17742091c3cb2ab45faa3aa87922d3c030cafb3f798850a2722bf0000000000feffffffa12f2424b9599898a1d30f06e1ce55eba7fabfeee82ae9356f07375806632ff3010000006b483045022100fcc8cf3014248e1a0d6dcddf03e80f7e591605ad0dbace27d2c0d87274f8cd66022053fcfff64f35f22a14deb657ac57f110084fb07bb917c3b42e7d033c54c7717b012102b9e4dcc33c9cc9cb5f42b96dddb3b475b067f3e21125f79e10c853e5ca8fba31feffffff02206f9800000000001976a9144841b9874d913c430048c78a7b18baebdbea440588ac8096980000000000160014e4873ef43eac347471dd94bc899c51b395a509a502483045022100dd8250f8b5c2035d8feefae530b10862a63030590a851183cb61b3672eb4f26e022057fe7bc8593f05416c185d829b574290fb8706423451ebd0a0ae50c276b87b43012102179862f40b85fa43487500f1d6b13c864b5eb0a83999738db0f7a6b91b2ec64f00db080000"); Script scriptCode = new Script("OP_DUP OP_HASH160 e4873ef43eac347471dd94bc899c51b395a509a5 OP_EQUALVERIFY OP_CHECKSIG"); var rrrr = Script.SignatureHash(scriptCode, txxxxx, 0, SigHash.All, Money.Satoshis(10000000), HashVersion.Witness); //Console.WriteLine(total); new Key().PubKey.WitHash.GetAddress(Network.SegNet).ToString(); var node = Node.Connect(Network.SegNet, "qbitninja-server.cloudapp.net"); node.VersionHandshake(); uint256 p2wsh = null; uint256 p2pwkh = null; uint256 p2wshp2sh = null; uint256 p2wpkhp2sh = null; foreach(var block in node.GetBlocks()) { foreach(var tx in block.Transactions) { if(p2wsh != null && p2pwkh != null && p2wshp2sh != null && p2wpkhp2sh != null) break; if(!tx.IsCoinBase && tx.HasWitness) { foreach(var input in tx.Inputs.AsIndexedInputs()) { if(input.WitScript == WitScript.Empty) continue; if(input.ScriptSig == Script.Empty) { if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null) p2pwkh = tx.GetHash(); else p2wsh = tx.GetHash(); } else { if(PayToWitPubKeyHashTemplate.Instance.ExtractWitScriptParameters(input.WitScript) != null) p2wpkhp2sh = tx.GetHash(); else p2wshp2sh = tx.GetHash(); } break; } } } } var secret = new BitcoinSecret("QTrKVpsVwNUD9GayzdbUNz2NNDqiPgjd9RCprwSa4gmBFg3V2oik", Network.SegNet); var oo = secret.PubKey.WitHash.GetAddress(Network.SegNet); var key = new Key().GetBitcoinSecret(Network.SegNet); var aa = key.GetAddress(); foreach(var n in new[] { Network.Main, Network.SegNet }) { for(int i = 0 ; i < 2 ; i++) { BitcoinAddress addr = i == 0 ? (BitcoinAddress)new Key().PubKey.GetSegwitAddress(n) : new Key().ScriptPubKey.GetWitScriptAddress(n); var c = addr.ScriptPubKey.ToString(); } } var networks = Network.GetNetworks().ToArray(); List<Conflict> conflicts = new List<Conflict>(); for(int n = 0 ; n < networks.Length ; n++) { for(int n2 = n + 1 ; n2 < networks.Length ; n2++) { var a = networks[n]; var b = networks[n2]; if(a == Network.RegTest || b == Network.RegTest) continue; if(a == b) throw new Exception(); for(int i = 0 ; i < a.base58Prefixes.Length ; i++) { for(int y = i + 1 ; y < a.base58Prefixes.Length ; y++) { if(a.base58Prefixes[i] != null && b.base58Prefixes[y] != null) { var ae = Encoders.Hex.EncodeData(a.base58Prefixes[i]); var be = Encoders.Hex.EncodeData(b.base58Prefixes[y]); if(ae == be) continue; if(ae.StartsWith(be) || be.StartsWith(ae)) { ConflictPart ca = new ConflictPart(); ca.Network = a; ca.Type = (Base58Type)i; ca.Value = a.base58Prefixes[i]; ConflictPart cb = new ConflictPart(); cb.Network = b; cb.Type = (Base58Type)y; cb.Value = b.base58Prefixes[y]; Conflict cc = new Conflict(); cc.A = ca; cc.B = cb; conflicts.Add(cc); } } } } } } var rr = String.Join("\r\n", conflicts.OfType<object>().ToArray()); Console.WriteLine(); //ConcurrentChain chain = new ConcurrentChain(Network.Main); //ChainBehavior chainBehavior = new ChainBehavior(chain); //NodeConnectionParameters para = new NodeConnectionParameters(); //para.TemplateBehaviors.Add(chainBehavior); //NodesGroup group = new NodesGroup(Network.Main, para); //group.Connect(); //while(true) //{ // Thread.Sleep(1000); //} //Parallel.ForEach(Enumerable.Range(0, 10), _ => //{ // ConcurrentChain chain = new ConcurrentChain(Network.Main); // node.SynchronizeChain(chain); //}); //Wallet wallet = new Wallet(new ExtKey(), Network.Main); //wallet.Connect(addrman: AddressManager.LoadPeerFile(@"E:\Program Files\Bitcoin\peers.dat", Network.Main)); //while(true) //{ // Thread.Sleep(1000); // Console.WriteLine(wallet.ConnectedNodes + " " + wallet.State); //} //var node = Node.ConnectToLocal(Network.Main); //node.VersionHandshake(); //var chain = node.GetChain(); //var v3 = chain.Tip // .EnumerateToGenesis() // .Take(1000) // .Aggregate(0, (a, b) => b.Header.Version == 3 ? a+1 : a); //var r = (double)v3 / (double)1000; Stopwatch watch = new Stopwatch(); watch.Start(); System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.Net.ServicePointManager.Expect100Continue = false; var repo = new QBitNinjaTransactionRepository("http://rapidbase-test.azurewebsites.net/"); var colored = new OpenAsset.NoSqlColoredTransactionRepository(repo); var result = repo .Get("c3462373f1a722c66cbb1b93712df94aa7b3731f4142cd8413f10c9e872927de") .GetColoredTransaction(colored); watch.Stop(); //for(int i = 0 ; i < 100 ; i++) //{ // using(var node = Node.ConnectToLocal(Network.Main)) // { // node.VersionHandshake(); // var chain = new ConcurrentChain(Network.Main); // node.SynchronizeChain(chain); // } //} }
public ISignResult Sign(string transactionContext, IEnumerable <string> privateKeys) { var context = Serializer.ToObject <TransactionInfo>(transactionContext); var tx = Transaction.Parse(context.TransactionHex, _network); var secretKeys = privateKeys.Select(p => Key.Parse(p, _network)).ToList(); Key GetPrivateKey(TxDestination pubKeyHash) { foreach (var secret in secretKeys) { var key = new BitcoinSecret(secret, _network); if (key.PubKey.Hash == pubKeyHash || key.PubKey.WitHash.ScriptPubKey.Hash == pubKeyHash || key.PubKey.WitHash.AsKeyId() == pubKeyHash) { return(key.PrivateKey); } } return(null); } var hashType = SigHash.All; for (var i = 0; i < tx.Inputs.Count; i++) { var input = tx.Inputs[i]; var output = context.UsedCoins.FirstOrDefault(o => o.Outpoint == input.PrevOut)?.TxOut; if (output == null) { throw new BusinessException("Input not found", ErrorCode.InputNotFound); } if (PayToPubkeyHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey)) { var secret = GetPrivateKey( PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(output.ScriptPubKey)); if (secret != null) { var hash = tx.GetSignatureHash(output.ScriptPubKey, i, hashType, output.Value); var signature = secret.Sign(hash, hashType); tx.Inputs[i].ScriptSig = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(signature, secret.PubKey); continue; } throw new BusinessException("Incompatible private key", ErrorCode.IncompatiblePrivateKey); } if (PayToPubkeyTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey)) { var secret = GetPrivateKey(PayToPubkeyTemplate.Instance .ExtractScriptPubKeyParameters(output.ScriptPubKey).Hash); if (secret != null) { var hash = tx.GetSignatureHash(output.ScriptPubKey, i, hashType, output.Value); var signature = secret.Sign(hash, hashType); tx.Inputs[i].ScriptSig = PayToPubkeyTemplate.Instance.GenerateScriptSig(signature); continue; } throw new BusinessException("Incompatible private key", ErrorCode.InvalidScript); } if (PayToScriptHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey)) { var secret = GetPrivateKey( PayToScriptHashTemplate.Instance.ExtractScriptPubKeyParameters(output.ScriptPubKey)); if (secret != null && secret.PubKey.WitHash.ScriptPubKey.Hash.ScriptPubKey == output.ScriptPubKey) { var hash = tx.GetSignatureHash(secret.PubKey.WitHash.AsKeyId().ScriptPubKey, i, hashType, output.Value, HashVersion.Witness); var signature = secret.Sign(hash, hashType); tx.Inputs[i].WitScript = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(signature, secret.PubKey); tx.Inputs[i].ScriptSig = new Script(Op.GetPushOp(secret.PubKey.WitHash.ScriptPubKey.ToBytes(true))); continue; } } if (PayToWitPubKeyHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey)) { var parameters = PayToWitPubKeyHashTemplate.Instance.ExtractScriptPubKeyParameters(output.ScriptPubKey); var secret = GetPrivateKey(parameters.AsKeyId()); if (secret != null) { var hash = tx.GetSignatureHash(parameters.AsKeyId().ScriptPubKey, i, hashType, output.Value, HashVersion.Witness); var signature = secret.Sign(hash, hashType); tx.Inputs[i].WitScript = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(signature, secret.PubKey); continue; } } throw new BusinessException("Incompatible private key", ErrorCode.InvalidScript); } return(SignResult.Ok(tx.ToHex())); }
void Start() { BitcoinSecret bitcoinPrivateKey = new BitcoinSecret("cUwC2Dk7VvVyxF3jGyHdz5HTtxHYqHuQgWX1pnYvqckwCyUGStd3"); QBitNinja4Unity.QBitNinjaClient.GetBalance(bitcoinPrivateKey.GetAddress(), bitcoinPrivateKey.Network, GetBalanceResponse); }
public async Task <string> TransferBitcoin(decimal amount, string toAddress, bool ssIsTestNet) { var fromWallet = await _walletRepository.GetDefaultWalletToSendBitcoins(); var net = ssIsTestNet ? Network.TestNet : Network.Main; var transaction = Transaction.Create(net); var bitcoinPrivateKey = new BitcoinSecret(fromWallet.PrivateKey); var fromAddress = bitcoinPrivateKey.GetAddress().ToString(); var totalBalance = await GetBalance(fromAddress); if (totalBalance <= amount) { throw new Exception("The address doesn't have enough funds!"); } var client = new QBitNinjaClient(net); var balance = client.GetBalance(new BitcoinPubKeyAddress(fromAddress), true).Result; //Add trx in //Get all transactions in for that address var txsIn = 0; if (balance.Operations.Any()) { foreach (var operation in balance.Operations) { foreach (Coin receivedCoin in operation.ReceivedCoins) { var outpointToSpend = receivedCoin.Outpoint; transaction.Inputs.Add(new TxIn { PrevOut = outpointToSpend }); transaction.Inputs[txsIn].ScriptSig = bitcoinPrivateKey.ScriptPubKey; txsIn = txsIn + 1; } } } //add address to send money var toPubKeyAddress = new BitcoinPubKeyAddress(toAddress); var toAddressTxOut = new TxOut { Value = new Money(amount, MoneyUnit.BTC), ScriptPubKey = toPubKeyAddress.ScriptPubKey }; transaction.Outputs.Add(toAddressTxOut); //add address to send change var change = totalBalance - amount; if (change > 0) { var fromPubKeyAddress = new BitcoinPubKeyAddress(fromAddress); var changeAddressTxOut = new TxOut { Value = new Money(change, MoneyUnit.BTC), ScriptPubKey = fromPubKeyAddress.ScriptPubKey }; transaction.Outputs.Add(changeAddressTxOut); } // sign transaction transaction.Sign(bitcoinPrivateKey, balance.Operations.SelectMany(x => x.ReceivedCoins.Select(y => y)).LastOrDefault()); //Send transaction var broadcastResponse = client.Broadcast(transaction).Result; if (!broadcastResponse.Success) { throw new Exception("Error broadcasting transaction " + broadcastResponse.Error.ErrorCode + " : " + broadcastResponse.Error.Reason); } var transactionId = transaction.GetHashCode().ToString(); var receiver = await _walletRepository.GetOrCreate(toAddress); _transactionRepository.Create(new TransactionModel { Amount = amount, Confirmation = 0, CreatedDate = DateTime.UtcNow, FromWalletId = fromWallet.WalletId, TransactionId = transactionId, ToWalletId = receiver.WalletId }); await _transactionRepository.SaveAsync(); await UpdateBalance(fromWallet, receiver); return(transaction.GetHash().ToString()); }
// importprivkey public void ImportPrivKey(BitcoinSecret secret) { SendCommand("importprivkey", secret.ToWif()); }
private async void SendDigibyte() { InvokeHelp.SetControlPropertyThreadSafe(Sendinglabel, "Text", "กำลังส่งเงินอัตโนมัติ"); InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Visible", true); InvokeHelp.SetControlPropertyThreadSafe(refreshbutton, "Enabled", false); InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Value", 1); Network network = NBitcoin.Altcoins.Digibyte.Instance.Mainnet; BitcoinSecret sender = saveKey.SecretKey; var myTransaction = Transaction.Create(network); var fee = new Money(Fee); var allUtxo = await GetReceivedCoinFromDigibyte(sender.GetAddress().ToString()); var utxo = allUtxo.OrderByDescending(u => u.amount).First().AsCoin(); //var utxo = allUtxo[0].ToCoin(); var txBuilder = network.CreateTransactionBuilder(); for (int i = 0; i < allUtxo.Count(); i++) { txBuilder = txBuilder.AddCoins(allUtxo[i].AsCoin()); } txBuilder.AddKeys(sender); foreach (var a in LowMoneyWallet) { try { BitcoinAddress receiver; if (a.account_id.publickey.StartsWith("dgb1")) { receiver = new BitcoinWitPubKeyAddress(a.account_id.publickey, network); } else { receiver = new BitcoinPubKeyAddress(a.account_id.publickey, network); } txBuilder .Send(receiver, new Money(MoneyToSend)); } catch { continue; } } tx = txBuilder .SetChange(sender.GetAddress()) .SendFees(fee) .BuildTransaction(true); var verified = txBuilder.Verify(tx); InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Value", 2); var txid = await BroadcastTransaction(tx.ToHex()); int issuedRepeat = 30; InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Value", 3); start: var txContract = await api.GetTransactionInfo(txid.txid); if (txContract.time == 0 && txContract.blocktime == 0) { if (issuedRepeat > 0) { issuedRepeat--; Thread.Sleep(5000); goto start; } else { InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Visible", false); InvokeHelp.SetControlPropertyThreadSafe(Sendinglabel, "Text", "ส่งเงินไม่สำเร็จ"); timer.Start(); return; } } InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Value", 4); InvokeHelp.SetControlPropertyThreadSafe(progressBar2, "Visible", false); InvokeHelp.SetControlPropertyThreadSafe(Sendinglabel, "ForeColor", Color.Green); InvokeHelp.SetControlPropertyThreadSafe(Sendinglabel, "Text", "ส่งเงินอัตโนมัติสำเร็จ"); InvokeHelp.SetControlPropertyThreadSafe(timeSendinglabel, "Text", DateTime.Now.ToString("HH:mm dd/MM/yyyy")); InvokeHelp.SetControlPropertyThreadSafe(NumOfWalletSendlabel, "Text", LowMoneyWallet.Count().ToString()); InvokeHelp.SetControlPropertyThreadSafe(totalSendlabel, "ForeColor", Color.BlueViolet); decimal totaltSent = LowMoneyWallet.Count() * (MoneyToSend / 100000000m); totaltSent = totaltSent + (Fee / 100000000m); InvokeHelp.SetControlPropertyThreadSafe(totalSendlabel, "Text", totaltSent.ToString()); InvokeHelp.SetControlPropertyThreadSafe(refreshbutton, "Enabled", true); LoadData(); t.Abort(); }
// importprivkey public void ImportPrivKey(BitcoinSecret secret) { SendCommand(RPCOperations.importprivkey, secret.ToWif()); }
/// <summary> /// Constructor. Reconstructs an extended key from the Base58 representations of /// the public key and corresponding private key. /// </summary> public ExtKey(BitcoinExtPubKey extPubKey, BitcoinSecret key) : this(extPubKey.ExtPubKey, key.PrivateKey) { }
public async Task ImportPrivKeyAsync(BitcoinSecret secret) { await SendCommandAsync(RPCOperations.importprivkey, secret.ToWif()).ConfigureAwait(false); }
static void Test(string[] args) { var qBitNinjaClient = new QBitNinjaClient(Network.TestNet); var destAddress = new BitcoinPubKeyAddress("ms2aSazNDyGdjSJcQKoottewTw4eY2yPRZ"); var balance = qBitNinjaClient.GetBalance(destAddress).Result; //var network = Network.Main; //var privateKey = new Key(); //var bitcoinPrivateKey = privateKey.GetWif(Network.Main); //var address = bitcoinPrivateKey.GetAddress(); //Console.WriteLine(bitcoinPrivateKey); //Console.WriteLine(address); //Carrying out a Transaction var bitcoinPrivateKey = new BitcoinSecret("L46GfzE4z24gmX7d3MTWh2dRjTpd6jv4SB3zTB88uvFniMwTbg4B"); var network = bitcoinPrivateKey.Network; var address = bitcoinPrivateKey.GetAddress(); var client = new QBitNinjaClient(network); var transactionId = uint256.Parse("06c0aec7543467951abad0c28998a2c1fc1cdc34e01113f8ec1fdb22be854771"); var transactionResponse = client.GetTransaction(transactionId).Result; Console.WriteLine(transactionResponse.TransactionId); if (transactionResponse.Block != null) { Console.WriteLine(transactionResponse.Block.Confirmations); } var receivedCoins = transactionResponse.ReceivedCoins; OutPoint outPointToSpend = null; foreach (var coin in receivedCoins) { if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey) { outPointToSpend = coin.Outpoint; } } var transaction = new Transaction(); transaction.Inputs.Add(new TxIn() { PrevOut = outPointToSpend }); var ugoBtcDestinationAddress = new BitcoinPubKeyAddress("15iDEceRgbfvAGdsCHSb2stUR3tSdxVU35"); TxOut ugoBtcDestinationAddressTxOut = new TxOut() { Value = new Money((decimal)0.00034492, MoneyUnit.BTC), ScriptPubKey = ugoBtcDestinationAddress.ScriptPubKey }; TxOut changeBackTxOut = new TxOut() { Value = new Money((decimal)0.00017246, MoneyUnit.BTC), ScriptPubKey = bitcoinPrivateKey.ScriptPubKey }; transaction.Outputs.Add(ugoBtcDestinationAddressTxOut); transaction.Outputs.Add(changeBackTxOut); var message = "ugo the jedi master"; var bytes = Encoding.UTF8.GetBytes(message); TxOut transactionDescription = new TxOut() { Value = Money.Zero, ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes) }; transaction.Outputs.Add(transactionDescription); transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey; transaction.Sign(bitcoinPrivateKey, false); BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result; if (!broadcastResponse.Success) { Console.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode); Console.WriteLine("Error message: " + broadcastResponse.Error.Reason); } else { Console.WriteLine("Success, you can now checkout the transaction in any block explorer"); Console.WriteLine("Hash: " + transaction.GetHash()); } Console.ReadKey(); }
public void base58_keys_valid_gen() { TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid.json")); tests = tests.Concat(TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid2.json"))).ToArray(); Network network = null; foreach (TestCase 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 = KnownNetworks.TestNet; } else { network = KnownNetworks.Main; } if (isPrivkey) { bool isCompressed = metadata.isCompressed; var 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(KnownNetworks.Main) == dest); } catch (ArgumentException) { Assert.True(dest.GetType() == typeof(TxDestination)); } } } }
public void SetMinerSecret(BitcoinSecret secret) { CreateRPCClient().ImportPrivKey(secret); MinerSecret = secret; }
public void ImportPrivKey(BitcoinSecret secret, string label, bool rescan) { SendCommand("importprivkey", secret.ToWif(), label, rescan); }
public void key_test1() { BitcoinSecret bsecret1 = Network.Main.CreateBitcoinSecret(strSecret1); BitcoinSecret bsecret2 = Network.Main.CreateBitcoinSecret(strSecret2); BitcoinSecret bsecret1C = Network.Main.CreateBitcoinSecret(strSecret1C); BitcoinSecret bsecret2C = Network.Main.CreateBitcoinSecret(strSecret2C); Assert.Throws <FormatException>(() => Network.Main.CreateBitcoinSecret(strAddressBad)); Key key1 = bsecret1.PrivateKey; Assert.True(key1.IsCompressed == false); Assert.True(bsecret1.Copy(true).PrivateKey.IsCompressed == true); Assert.True(bsecret1.Copy(true).Copy(false).IsCompressed == false); Assert.True(bsecret1.Copy(true).Copy(false).ToString() == bsecret1.ToString()); Key key2 = bsecret2.PrivateKey; Assert.True(key2.IsCompressed == false); Key key1C = bsecret1C.PrivateKey; Assert.True(key1C.IsCompressed == true); Key key2C = bsecret2C.PrivateKey; Assert.True(key1C.IsCompressed == true); PubKey pubkey1 = key1.PubKey; PubKey pubkey2 = key2.PubKey; PubKey pubkey1C = key1C.PubKey; PubKey pubkey2C = key2C.PubKey; Assert.True(addr1.Hash == pubkey1.Hash); Assert.True(addr2.Hash == pubkey2.Hash); Assert.True(addr1C.Hash == pubkey1C.Hash); Assert.True(addr2C.Hash == pubkey2C.Hash); for (int n = 0; n < 16; n++) { string strMsg = String.Format("Very secret message {0}: 11", n); if (n == 10) { //Test one long message strMsg = String.Join(",", Enumerable.Range(0, 2000).Select(i => i.ToString()).ToArray()); } uint256 hashMsg = Hashes.Hash256(TestUtils.ToBytes(strMsg)); // normal signatures ECDSASignature sign1 = null, sign2 = null, sign1C = null, sign2C = null; List <Task> tasks = new List <Task>(); tasks.Add(Task.Run(() => sign1 = key1.Sign(hashMsg))); tasks.Add(Task.Run(() => sign2 = key2.Sign(hashMsg))); tasks.Add(Task.Run(() => sign1C = key1C.Sign(hashMsg))); tasks.Add(Task.Run(() => sign2C = key2C.Sign(hashMsg))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2C)))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1C.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1C.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2C.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2C)))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); // compact signatures (with key recovery) byte[] csign1 = null, csign2 = null, csign1C = null, csign2C = null; tasks.Add(Task.Run(() => csign1 = key1.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign2 = key2.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign1C = key1C.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign2C = key2C.SignCompact(hashMsg))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); PubKey rkey1 = null, rkey2 = null, rkey1C = null, rkey2C = null; tasks.Add(Task.Run(() => rkey1 = PubKey.RecoverCompact(hashMsg, csign1))); tasks.Add(Task.Run(() => rkey2 = PubKey.RecoverCompact(hashMsg, csign2))); tasks.Add(Task.Run(() => rkey1C = PubKey.RecoverCompact(hashMsg, csign1C))); tasks.Add(Task.Run(() => rkey2C = PubKey.RecoverCompact(hashMsg, csign2C))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); Assert.True(rkey1.ToHex() == pubkey1.ToHex()); Assert.True(rkey2.ToHex() == pubkey2.ToHex()); Assert.True(rkey1C.ToHex() == pubkey1C.ToHex()); Assert.True(rkey2C.ToHex() == pubkey2C.ToHex()); } }
public async Task ImportPrivKeyAsync(BitcoinSecret secret, string label, bool rescan) { await SendCommandAsync("importprivkey", secret.ToWif(), label, rescan).ConfigureAwait(false); }
public void CanGeneratePubKeysAndAddress() { //Took from http://brainwallet.org/ and http://procbits.com/2013/08/27/generating-a-bitcoin-address-with-javascript var tests = new[] { new { PrivateKeyWIF = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD", CompressedPrivateKeyWIF = "KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5auC2qc3", PubKey = "04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495", CompressedPubKey = "03d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f", Address = "16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS", CompressedAddress = "1FkKMsKNJqWSDvTvETqcCeHcUQQ64kSC6s", Hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8", CompressedHash160 = "a1c2f92a9dacbd2991c3897724a93f338e44bdc1", DER = "3082011302010104201184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fda081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a14403420004d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495", CompressedDER = "3081d302010104201184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fda08185308182020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a12403220003d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f" }, new { PrivateKeyWIF = "5J7WTMRn1vjZ9udUxNCLq7F9DYEJiqRCjstiBrY6mDjnaomd6kZ", CompressedPrivateKeyWIF = "KxXj1KAMh6ApvKJ2PNZ4XLZRGLqjDehppFdEnueGSBDrC2Hfe7vt", PubKey = "0493e5d305cad2588d5fb254065fe48ce446028ba380e6ee663baea9cd105500897eb030c033cdab160f31c36df0ea38330fdd69677df49cd14826902022d17f3f", CompressedPubKey = "0393e5d305cad2588d5fb254065fe48ce446028ba380e6ee663baea9cd10550089", Address = "1MZmwgyMyjM11uA6ZSpgn1uK3LBWCzvV6e", CompressedAddress = "1AECNr2TDye8dpC1TeDH3eJpGoZ7dNPy4g", Hash160 = "e19557c8f8fb53a964c5dc7bfde86d806709f7c5", CompressedHash160 = "6538094af65453ea279f14d1a04b408e3adfebd7", DER = "308201130201010420271ac4d7056937c156abd828850d05df0697dd662d3c1b0107f53a387b4c176ca081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a1440342000493e5d305cad2588d5fb254065fe48ce446028ba380e6ee663baea9cd105500897eb030c033cdab160f31c36df0ea38330fdd69677df49cd14826902022d17f3f", CompressedDER = "3081d30201010420271ac4d7056937c156abd828850d05df0697dd662d3c1b0107f53a387b4c176ca08185308182020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a1240322000393e5d305cad2588d5fb254065fe48ce446028ba380e6ee663baea9cd10550089" } }; foreach (var test in tests) { BitcoinSecret secret = Network.Main.CreateBitcoinSecret(test.PrivateKeyWIF); Assert.Equal(test.PubKey, secret.PrivateKey.PubKey.ToHex()); TestDERCoherence(secret); TestDEREqual(test.DER, secret); var address = Network.Main.CreateBitcoinAddress(test.Address); Assert.Equal(new KeyId(test.Hash160), address.Hash); Assert.Equal(new KeyId(test.Hash160), secret.PrivateKey.PubKey.Hash); Assert.Equal(address.Hash, secret.PrivateKey.PubKey.GetAddress(Network.Main).Hash); var compressedSec = secret.Copy(true); TestDERCoherence(compressedSec); TestDEREqual(test.CompressedDER, compressedSec); var a = secret.PrivateKey.PubKey; var b = compressedSec.PrivateKey.PubKey; Assert.Equal(test.CompressedPrivateKeyWIF, compressedSec.ToWif()); Assert.Equal(test.CompressedPubKey, compressedSec.PrivateKey.PubKey.ToHex()); Assert.True(compressedSec.PrivateKey.PubKey.IsCompressed); var compressedAddr = Network.Main.CreateBitcoinAddress(test.CompressedAddress); Assert.Equal(new KeyId(test.CompressedHash160), compressedAddr.Hash); Assert.Equal(new KeyId(test.CompressedHash160), compressedSec.PrivateKey.PubKey.Hash); } }
public void CanQueryBalanceRange() { using(var tester = CreateTester()) { Key bob = new BitcoinSecret("L4JinGSmHxKJJrjbeFx3zxf9Vr3VD6jmq5wXpDm6ywUewcWoXEAy").PrivateKey; var chainBuilder = tester.CreateChainBuilder(); chainBuilder.NoRandom = true; Dictionary<string, Transaction> txs = new Dictionary<string, Transaction>(); txs.Add("tx1", chainBuilder.EmitMoney(bob, "1.0")); chainBuilder.SubmitBlock(); txs.Add("tx21", chainBuilder.EmitMoney(bob, "2.1")); txs.Add("tx22", chainBuilder.EmitMoney(bob, "2.2")); chainBuilder.SubmitBlock(); txs.Add("tx31", chainBuilder.EmitMoney(bob, "3.1")); txs.Add("tx32", chainBuilder.EmitMoney(bob, "3.2")); txs.Add("tx33", chainBuilder.EmitMoney(bob, "3.3")); chainBuilder.SubmitBlock(); txs.Add("tx41", chainBuilder.EmitMoney(bob, "4.2")); txs.Add("tx42", chainBuilder.EmitMoney(bob, "4.3")); txs.Add("tx43", chainBuilder.EmitMoney(bob, "4.1")); chainBuilder.SubmitBlock(); txs.Add("utx51", chainBuilder.EmitMoney(bob, "5.1", isCoinbase: false, indexBalance: true)); Thread.Sleep(1000); txs.Add("utx52", chainBuilder.EmitMoney(bob, "5.2", isCoinbase: false, indexBalance: true)); Thread.Sleep(1000); txs.Add("utx53", chainBuilder.EmitMoney(bob, "5.3", isCoinbase: false, indexBalance: true)); chainBuilder.SyncIndexer(); var tests = new String[][] { new string[]{"2in", "4in", "tx43,tx42,tx41,tx33,tx32,tx31,tx22,tx21"}, new string[]{"4in", "2in", "tx43,tx42,tx41,tx33,tx32,tx31,tx22,tx21"}, //Does not care about order new string[]{"2ex", "4in", "tx43,tx42,tx41,tx33,tx32,tx31"}, new string[]{"2in", "4ex", "tx33,tx32,tx31,tx22,tx21"}, new string[]{"2ex", "4ex", "tx33,tx32,tx31"}, new string[]{"{utx51}in", "{utx52}in", "utx52,utx51"}, new string[]{"{utx51}in", "{utx53}ex", "utx52,utx51"}, new string[]{"{utx51}ex", "{utx53}in", "utx53,utx52"}, new string[]{"{utx52}ex", "3in", "utx53,tx43,tx42,tx41,tx33,tx32,tx31"} }; var all = tester.Client.GetOrderedBalance(bob).ToArray(); Assert.Equal(all.Length, txs.Count); foreach(var test in tests) { var data = test; BalanceQuery query = new BalanceQuery(); query.From = Parse(data[0], all, txs); query.FromIncluded = ParseIncl(data[0]); query.To = Parse(data[1], all, txs); query.ToIncluded = ParseIncl(data[1]); var result = tester.Client.GetOrderedBalance(bob, query).ToArray(); var expected = data[2].Split(',').ToArray(); var expectedResult = String.Join(",", expected); var actualResult = String.Join(",", result.Select(o => GetName(txs, o))); Assert.Equal(expectedResult, actualResult); } } }
public static void SendTransaction(Decimal amountOfBtc, String toAddress) { Network network = Network.TestNet; BitcoinSecret frank = new BitcoinSecret("cSRGkyQ8Ny3QEMxHYp3BnDPAibQYReg4g1Nso7jfrAUgH79sjzsL"); var PubKey = frank.PubKey; var address = PubKey.GetAddress(ScriptPubKeyType.Legacy, network); Console.WriteLine("Address: " + address); using (HttpClient client = new HttpClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12; var url = "https://api.blockcypher.com/v1/btc/test3/addrs/" + address; var response = client.GetAsync(url); var jsonVar = response.Result.Content.ReadAsStringAsync().Result; var Txs = JObject.Parse(jsonVar)["txrefs"]; int numOfTxs = (int)JObject.Parse(jsonVar)["n_tx"]; // loop through array to get spendable transaction hash String tx_hash = ""; String prev_tx_hash = ""; bool spendableTxFound = false; int maxTransactionEntries = numOfTxs; for (int i = 0; i < maxTransactionEntries; i++) { tx_hash = Txs[i]["tx_hash"].ToString(); Console.WriteLine(tx_hash); if (prev_tx_hash == tx_hash) //if the next tx_hash is the same { maxTransactionEntries++; } try { if (Txs[i]["spent"].ToString() == "False" && (int)Txs[i]["confirmations"] > 5) { spendableTxFound = true; break; } } catch (NullReferenceException ex) { } prev_tx_hash = tx_hash; } // if spendable transaction is found if (spendableTxFound == true) { var qclient = new QBitNinjaClient(network); var transactionId = uint256.Parse(tx_hash); var transactionResponse = qclient.GetTransaction(transactionId).Result; Console.WriteLine("Address: " + address); Console.WriteLine("Transaction ID: " + transactionResponse.TransactionId); Console.WriteLine("Amount of Confirmations: " + transactionResponse.Block.Confirmations); var receivedCoins = transactionResponse.ReceivedCoins; OutPoint outPointToSpend = null; foreach (var coin in receivedCoins) { if (coin.TxOut.ScriptPubKey == address.ScriptPubKey) { outPointToSpend = coin.Outpoint; } } if (outPointToSpend == null) { throw new Exception("TxOut doesn't contain our ScriptPubKey"); } Transaction transaction = Transaction.Create(network); transaction.Inputs.Add(new TxIn() { PrevOut = outPointToSpend }); var recipientAddress = BitcoinAddress.Create(toAddress, network); var amountToSend = new Money(amountOfBtc, MoneyUnit.BTC); decimal numOfBytes = 1 * 180 + 2 * 34 + 10 + 1; decimal satoshisInCoin = 100000000; // 1 hundred million decimal recommendedFee = numOfBytes * 6 / satoshisInCoin; // Set how to much to pay for fees below (Higher fees are mined quicker) var minerFee = new Money(recommendedFee, MoneyUnit.BTC); Console.WriteLine($"Your fees are: {minerFee}BTC"); // Change var txInAmount = (Money)receivedCoins[(int)outPointToSpend.N].Amount; var changeAmount = txInAmount - amountToSend - minerFee; transaction.Outputs.Add(amountToSend, recipientAddress.ScriptPubKey); // Send the change back transaction.Outputs.Add(changeAmount, address.ScriptPubKey); // Add a message for a total of 3 outputs // String message = "I did it!"; //var bytes = Encoding.UTF8.GetBytes(message); //transaction.Outputs.Add(Money.Zero, TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)); // Add ScriptPubKey as input and sign with WIF private key transaction.Inputs[0].ScriptSig = address.ScriptPubKey; transaction.Sign(frank, receivedCoins.ToArray()); BroadcastResponse broadcastResponse = qclient.Broadcast(transaction).Result; if (!broadcastResponse.Success) { Console.Error.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode); Console.Error.WriteLine("Error message: " + broadcastResponse.Error.Reason); } else { Console.WriteLine("Success! You can check out the hash of the transaction in any block explorer:"); Console.WriteLine(transaction.GetHash()); } } else { Console.WriteLine("No spendable transaction (UTXO) found..."); } } }
private void TestDEREqual(string expected, BitcoinSecret secret) { var serializedSecret = secret.PrivateKey.ToDER(); var deserializedSecret = ECKey.FromDER(serializedSecret); var deserializedTestSecret = ECKey.FromDER(Encoders.Hex.DecodeData(expected)); AssertEx.CollectionEquals(deserializedTestSecret.ToDER(secret.PrivateKey.IsCompressed), deserializedSecret.ToDER(secret.PrivateKey.IsCompressed)); Assert.Equal(expected, Encoders.Hex.EncodeData(serializedSecret)); }
private async Task <(bool, string)> SignBroadcastAndInvokeSucessEvent(Transaction transaction, BitcoinSecret Secret, ICollection <Utxo> utxos, string message) { var rtxid = await DogeTransactionHelpers.SignAndBroadcastTransaction(transaction, Secret, utxos); if (rtxid != null) { await InvokeSendPaymentSuccessEvent(rtxid, message); return(true, rtxid); } return(false, ""); }
static void Test(string[] args) { //Carrying out a Transaction var bitcoinPrivateKey = new BitcoinSecret("cNZupUgfs54DmsShwxa1wpomQcszUtuJYFvx9zWPbXrT7KsWtiUd"); var network = bitcoinPrivateKey.Network; var address = bitcoinPrivateKey.GetAddress(); var client = new QBitNinjaClient(network); var balance = client.GetBalance(address, true).Result; var transactionId = uint256.Parse("3f3278d550ecd4f921d7f6f48f1e4b873e39d4b1b2a5098867d4c4e30ab9b444"); var transactionResponse = client.GetTransaction(transactionId).Result; var tx = new Transaction(); foreach (var operation in balance.Operations) { OutPoint spendOutPoint = null; var coinsReceived = operation.ReceivedCoins; foreach (var coin in coinsReceived) { if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey) { spendOutPoint = coin.Outpoint; tx.Inputs.Add(new TxIn() { PrevOut = spendOutPoint }); } } } var chimaTestDestinationAddress = new BitcoinPubKeyAddress("mxgN2AiqHjKfGvo6Y57fAe4Y754rPdKf4P"); TxOut chimaTestDestinationAddressTxOut = new TxOut() { Value = new Money((decimal)0.50, MoneyUnit.BTC), ScriptPubKey = chimaTestDestinationAddress.ScriptPubKey }; TxOut ugoChangeBackTxOut = new TxOut() { Value = new Money((decimal)2.39, MoneyUnit.BTC), ScriptPubKey = bitcoinPrivateKey.ScriptPubKey }; tx.Outputs.Add(chimaTestDestinationAddressTxOut); tx.Outputs.Add(ugoChangeBackTxOut); var msg = "ugo the jedi master"; var msgBytes = Encoding.UTF8.GetBytes(msg); TxOut txDesc = new TxOut() { Value = Money.Zero, ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(msgBytes) }; tx.Outputs.Add(txDesc); tx.Inputs[0].ScriptSig = bitcoinPrivateKey.PubKey.ScriptPubKey; tx.Inputs[1].ScriptSig = bitcoinPrivateKey.PubKey.ScriptPubKey; tx.Inputs[2].ScriptSig = bitcoinPrivateKey.PubKey.ScriptPubKey; tx.Sign(bitcoinPrivateKey, false); string txHex = tx.ToHex(); BroadcastResponse broadcast = client.Broadcast(tx).Result; if (!broadcast.Success) { Console.WriteLine("ErrorCode: " + broadcast.Error.ErrorCode); Console.WriteLine("Error message: " + broadcast.Error.Reason); } else { Console.WriteLine("Success, you can now checkout the transaction in any block explorer"); Console.WriteLine("Hash: " + tx.GetHash()); } //end of our dark wallet Console.ReadKey(); }
public static void HttpListener(string[] prefixes) { HttpListener listener = new HttpListener(); foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); HttpListenerContext context; HttpListenerRequest request_h; HttpListenerResponse response_h; Stream output; byte[] buffer; BigInteger num, previous, next, startPrivKey; BigInteger max = BigInteger.Parse("904625697166532776746648320380374280100293470930272690489102837043110636675"); byte[] hash = new byte[32]; String hashKey, privKey, privKey_C, bitAddr, bitAddr_C, rsp, searchKey = String.Empty; Key privateKey; PubKey publicKey; Key privateKey_C; PubKey publicKey_C; WebRequest request; WebResponse response; Stream dataStream; StreamReader reader; JsonRSP obj; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; while (true) { // 1 - 115792089237316195423570985008687907852837564279074904382605163141518161494337 bitcoin privatekey space context = listener.GetContext(); request_h = context.Request; response_h = context.Response; if (request_h.RawUrl.ToString() == "/favicon.ico") { continue; } if (request_h.RawUrl.ToString().StartsWith("/5H") || request_h.RawUrl.ToString().StartsWith("/5K") || request_h.RawUrl.ToString().StartsWith("/5J") || request_h.RawUrl.ToString().StartsWith("/K") || request_h.RawUrl.ToString().StartsWith("/L")) { var secret = new BitcoinSecret(request_h.RawUrl.Remove(0, 1)); var key = secret.PrivateKey; searchKey = key.PubKey.GetAddress(Network.Main).ToString(); byte[] b = key.ToBytes(); String hashK = String.Empty; foreach (byte h in b) { hashK += h.ToString("x2"); } hashK = "0" + hashK; num = BigInteger.Parse(hashK, System.Globalization.NumberStyles.HexNumber); num = num / 128; num = num + 1; } else { num = BigInteger.Parse(request_h.RawUrl.Remove(0, 1)); } previous = num - 1; if (previous == 0) { previous = 1; } next = num + 1; if (next > max) { next = max; } startPrivKey = (num - 1) * 128 + 1; StringBuilder sb = new StringBuilder(); //*************************************************** sb.Append("<!DOCTYPE html>"); sb.Append("<html>"); sb.Append("<head>"); sb.Append("<title>BTC_WebServer</title>"); sb.Append("<style>body{font-size:9.3pt;font-family:'Open Sans',sans-serif;}a{text-decoration:none}a:hover {text-decoration: underline}lol: target {background: #ccffcc; }</style>"); sb.Append("</head>"); sb.Append("<body>"); sb.Append("<h1>Bitcoin private key database</h1>"); sb.Append("<h3>Page " + num + " out of 904625697166532776746648320380374280100293470930272690489102837043110636675</h3>"); sb.Append("<a href='/" + previous + "'>previous</a> | "); sb.Append("<a href='/" + next + "'>next</a>"); sb.Append("<br>"); sb.Append("<pre class='keys'><strong>Private Key</strong> <strong>Address</strong> <strong>Compressed Address</strong> <strong>Private Key Compressed</strong><br>"); for (int i = 0; i < 128; i++) { if (startPrivKey.ToString("x2").Length == 65) { hashKey = startPrivKey.ToString("x2").Remove(0, 1); } else { hashKey = startPrivKey.ToString("x2"); } if (hashKey.Length < 64) { hashKey = hashKey.PadLeft(64, '0'); } int step = 0; for (int a = 0; a < 32; a++) { hash[a] = Convert.ToByte(hashKey.Substring(step, 2), 16); step += 2; } privateKey = new Key(hash, -1, false); privateKey_C = new Key(hash); publicKey = privateKey.PubKey; publicKey_C = privateKey_C.PubKey; privKey = privateKey.GetWif(Network.Main).ToString(); privKey_C = privateKey_C.GetWif(Network.Main).ToString(); bitAddr = publicKey.GetAddress(Network.Main).ToString(); bitAddr_C = publicKey_C.GetAddress(Network.Main).ToString(); request = WebRequest.Create("https://blockchain.info/q/addressbalance/" + bitAddr); response = request.GetResponse(); dataStream = response.GetResponseStream(); reader = new StreamReader(dataStream); rsp = reader.ReadToEnd(); Console.WriteLine(rsp); //dynamic data = JsonConvert.DeserializeObject(rsp); if (bitAddr == searchKey || bitAddr_C == searchKey) { sb.Append("<lol>" + privKey + "</lol> <lol style='display:inline-block;width:230px;color:#145A32;'><a href='https://bitaps.com/" + bitAddr + "'>" + "<strong>" + bitAddr + "</strong>" + "</a></lol> <lol style='display:inline-block;width:230px;color:#D35400;'><a href='https://bitaps.com/" + bitAddr_C + "'>" + "<strong>" + bitAddr_C + "</strong>" + "</a></lol> <lol style='color:#145A32;'>" + " <lol>" + privKey_C + "</lol></br>"); } else { sb.Append("<lol>" + privKey + "</lol> <lol style='display:inline-block;width:230px;color:#145A32;'><a href='https://bitaps.com/" + bitAddr + "'>" + bitAddr + "</a>" + " <span>" + rsp + "</span> " + "</lol> <lol style='display:inline-block;width:230px;color:#D35400;'><a href='https://bitaps.com/" + bitAddr_C + "'>" + bitAddr_C + "</a></lol> <lol style='color:#145A32;'>" + " <lol>" + privKey_C + "</lol></br>"); } sb.Append("<lol>" + privKey + "</lol> <lol style='display:inline-block;width:230px;color:#145A32;'><a href='https://bitaps.com/" + bitAddr + "'>" + bitAddr + "</a>" + " <span>" + rsp + "</span> " + "</lol> <lol style='display:inline-block;width:230px;color:#D35400;'><a href='https://bitaps.com/" + bitAddr_C + "'>" + bitAddr_C + "</a></lol> <lol style='color:#145A32;'>" + " <lol>" + privKey_C + "</lol></br>"); sb.Append("<lol>" + privKey + "</lol> <lol style='display:inline-block;width:230px;color:#145A32;'><a href='https://bitaps.com/" + bitAddr + "'>" + bitAddr + "</a>" + " <span>" + rsp + "</span> " + "</lol> <lol style='display:inline-block;width:230px;color:#D35400;'><a href='https://bitaps.com/" + bitAddr_C + "'>" + bitAddr_C + "</a></lol> <lol style='color:#145A32;'>" + " <lol>" + privKey_C + "</lol></br>"); sb.Append(rsp); if (startPrivKey == BigInteger.Parse("115792089237316195423570985008687907852837564279074904382605163141518161494336")) { break; } startPrivKey++; } sb.Append("<br><a href='/" + previous + "'>previous</a> | "); sb.Append("<a href='/" + next + "'>next</a>"); sb.Append("</pre><br>"); sb.Append("</body>"); sb.Append("</html>"); //**************************************************** buffer = Encoding.UTF8.GetBytes(sb.ToString()); response_h.ContentLength64 = buffer.Length; output = response_h.OutputStream; output.Write(buffer, 0, buffer.Length); } }
private static void PlaySplit() { var scan = new Key(TestUtils.ParseHex("cc411aab02edcd3bccf484a9ba5280d4a774e6f81eac8ebec9cb1c2e8f73020a")); var addr = new BitcoinStealthAddress("waPYjXyrTrvXjZHmMGdqs9YTegpRDpx97H5G3xqLehkgyrrZKsxGCmnwKexpZjXTCskUWwYywdUvrZK7L2vejeVZSYHVns61gm8VfU", Network.TestNet); var sender = new BitcoinSecret("cRjSUV1LqN2F8MsGnLE2JKfCP75kbWGFRroNQeXHC429jqVFgmW3", Network.TestNet); var tx = new Transaction(); tx.Version = 1; RPCClient client = RPCClientTests.CreateRPCClient(); var coins = client.ListUnspent(); foreach(var unspent in coins) { tx.Inputs.Add(new TxIn(unspent.OutPoint)); } var amount = coins.Select(c => c.Amount).Sum(); var perOut = (long)(amount.Satoshi / 13); while(amount > 0) { var toSend = Math.Min(perOut, (long)amount); amount -= toSend; var tout = new TxOut(toSend, sender.GetAddress()); if(!tout.IsDust) tx.Outputs.Add(tout); } tx.SignAll(sender); client.SendRawTransaction(tx); }
public void CanAskCmpctBlock() { var alice = new BitcoinSecret("KypycJyxP5yA4gSedEBRse5q5f8RwYKG8xi8z4SRe2rdaioL3YNc").PrivateKey; var satoshi = new BitcoinSecret("KypycJyxP5yA4gSedEBRse5q5f8RwYKG8xi8z4SRe2rdaioL3YNc").ToNetwork(Network.RegTest); using(var builder = NodeBuilder.Create(version: "C:\\Bitcoin\\bitcoind.exe")) { var now = new DateTimeOffset(2015, 07, 18, 0, 0, 0, TimeSpan.Zero); builder.ConfigParameters.Add("mocktime", Utils.DateTimeToUnixTime(now).ToString()); var bitcoind = builder.CreateNode(false); var bitcoind2 = builder.CreateNode(false); builder.StartAll(); bitcoind.SetMinerSecret(satoshi); bitcoind.MockTime = now; bitcoind2.SetMinerSecret(satoshi); bitcoind2.MockTime = now; var rpc = bitcoind.CreateRPCClient(); rpc.AddNode(bitcoind2.Endpoint, true); var client1 = bitcoind.CreateNodeClient(new NodeConnectionParameters() { Version = ProtocolVersion.SHORT_IDS_BLOCKS_VERSION }); using(var listener = client1.CreateListener()) { client1.VersionHandshake(); var sendCmpct = listener.ReceivePayload<SendCmpctPayload>(); Assert.Equal(1U, sendCmpct.Version); Assert.Equal(false, sendCmpct.PreferHeaderAndIDs); //Announcement client1.SendMessage(new SendCmpctPayload(false)); bitcoind.Generate(1); var inv = listener.ReceivePayload<InvPayload>(); Assert.True(inv.First().Type == InventoryType.MSG_BLOCK); //Request block inv.First().Type = InventoryType.MSG_CMPCT_BLOCK; client1.SendMessage(new GetDataPayload(inv.First())); var blk = listener.ReceivePayload<CmpctBlockPayload>(); //Request transaction var getTxn = new GetBlockTxnPayload(); getTxn.BlockId = blk.Header.GetHash(); getTxn.Indices.Add(0); client1.SendMessage(getTxn); var blockTxn = listener.ReceivePayload<BlockTxnPayload>(); Assert.True(blockTxn.BlockId == blk.Header.GetHash()); Assert.True(blockTxn.Transactions[0].GetHash() == blk.PrefilledTransactions[0].Transaction.GetHash()); bitcoind.Generate(100); var tx = bitcoind.GiveMoney(alice.ScriptPubKey, Money.Coins(1), false); var lastBlk = bitcoind.Generate(1)[0]; while(true) { var invv = listener.ReceivePayload<InvPayload>().First(); if(invv.Hash == lastBlk.GetHash()) { invv.Type = InventoryType.MSG_CMPCT_BLOCK; client1.SendMessage(new GetDataPayload(invv)); break; } } blk = listener.ReceivePayload<CmpctBlockPayload>(); Assert.Equal(1, blk.ShortIds.Count); Assert.Equal(blk.ShortIds[0], blk.GetShortID(tx.GetHash())); //Let the node know which is the last block that we know client1.SendMessage(new InvPayload(new InventoryVector(InventoryType.MSG_BLOCK, blk.Header.GetHash()))); bitcoind.Generate(1); inv = listener.ReceivePayload<InvPayload>(); inv.First().Type = InventoryType.MSG_CMPCT_BLOCK; client1.SendMessage(new GetDataPayload(inv.First())); blk = listener.ReceivePayload<CmpctBlockPayload>(); //Prefer being notified with cmpctblock client1.SendMessage(new SendCmpctPayload(true)); //Let the node know which is the last block that we know client1.SendMessage(new InvPayload(new InventoryVector(InventoryType.MSG_BLOCK, blk.Header.GetHash()))); bitcoind.Generate(1); blk = listener.ReceivePayload<CmpctBlockPayload>(); //The node ask to connect to use in high bandwidth mode var blocks = bitcoind.Generate(1, broadcast: false); client1.SendMessage(new HeadersPayload(blocks[0].Header)); var cmpct = listener.ReceivePayload<SendCmpctPayload>(); //Should become one of the three high bandwidth node Assert.True(cmpct.PreferHeaderAndIDs); var getdata = listener.ReceivePayload<GetDataPayload>(); Assert.True(getdata.Inventory[0].Type == InventoryType.MSG_CMPCT_BLOCK); client1.SendMessage(new CmpctBlockPayload(blocks[0])); //Should be able to get a compact block with Inv blocks = bitcoind.Generate(1, broadcast: false); client1.SendMessage(new InvPayload(blocks[0])); getdata = listener.ReceivePayload<GetDataPayload>(); Assert.True(getdata.Inventory[0].Type == InventoryType.MSG_CMPCT_BLOCK); client1.SendMessage(new CmpctBlockPayload(blocks[0])); //Send as prefilled transaction 0 and 2 var tx1 = bitcoind.GiveMoney(satoshi.ScriptPubKey, Money.Coins(1.0m), broadcast: false); var tx2 = bitcoind.GiveMoney(satoshi.ScriptPubKey, Money.Coins(2.0m), broadcast: false); var tx3 = bitcoind.GiveMoney(satoshi.ScriptPubKey, Money.Coins(3.0m), broadcast: false); blocks = bitcoind.Generate(1, broadcast: false); Assert.True(blocks[0].Transactions.Count == 4); var cmpctBlk = new CmpctBlockPayload(); cmpctBlk.Nonce = RandomUtils.GetUInt64(); cmpctBlk.Header = blocks[0].Header; cmpctBlk.PrefilledTransactions.Add(new PrefilledTransaction() { Index = 0, Transaction = blocks[0].Transactions[0] }); cmpctBlk.PrefilledTransactions.Add(new PrefilledTransaction() { Index = 2, Transaction = blocks[0].Transactions[2] }); cmpctBlk.AddTransactionShortId(blocks[0].Transactions[1]); cmpctBlk.AddTransactionShortId(blocks[0].Transactions[3]); client1.SendMessage(cmpctBlk); //Check that node ask for 1 and 3 var gettxn = listener.ReceivePayload<GetBlockTxnPayload>(); Assert.Equal(2, gettxn.Indices.Count); Assert.Equal(1, gettxn.Indices[0]); Assert.Equal(3, gettxn.Indices[1]); client1.SendMessage(new BlockTxnPayload() { BlockId = blocks[0].GetHash(), Transactions = { blocks[0].Transactions[1], blocks[0].Transactions[3], } }); //Both nodes updated ? var chain1 = client1.GetChain(); Assert.Equal(blocks[0].GetHash(), chain1.Tip.HashBlock); using(var client2 = bitcoind2.CreateNodeClient()) { client2.VersionHandshake(); var chain2 = client2.GetChain(); Assert.Equal(chain1.Tip.HashBlock, chain2.Tip.HashBlock); } //Block with coinbase only blocks = bitcoind.Generate(1, broadcast: false); client1.SendMessage(new CmpctBlockPayload(blocks[0])); client1.SynchronizeChain(chain1); Assert.Equal(chain1.Tip.HashBlock, blocks[0].GetHash()); } } }