private static void MakePayment(BitcoinSecret sender, BitcoinSecret receiver, Money amount) { Money fees = Money.Parse("0.0001"); var tx = new Transaction(); tx.Version = 1; RPCClient client = new RPCClient(new NetworkCredential("...", "..."), "localhost", Network.TestNet); var coins = client.ListUnspent(); Money totalSent = Money.Zero; foreach (var unspent in coins.Where(c => c.Address == sender.GetAddress())) { tx.Inputs.Add(new TxIn(unspent.OutPoint)); totalSent = totalSent + unspent.Amount; if (totalSent > amount + fees) { break; } } if (totalSent < amount + fees) { throw new Exception("Not enough funds"); } tx.Outputs.Add(new TxOut(amount + fees, receiver.GetAddress())); tx.Outputs.Add(new TxOut(totalSent - amount - fees, sender.GetAddress())); //tx.SignAll(sender); client.SendRawTransaction(tx); }
public void Payment(RPCClient client, Network net, BitcoinSecret sender, BitcoinAddress receiver, Money amount) { Money fees = Money.Parse("0.001"); var tx = new Transaction(); tx.Version = 1; Money totalSent = Money.Zero; Dictionary <OutPoint, Money> availableMoney = listIdexedUnspent(client, sender.GetAddress()); foreach (var unspent in availableMoney) { TxIn vin = new TxIn(unspent.Key); vin.ScriptSig = sender.GetAddress().ScriptPubKey; tx.Inputs.Add(vin); totalSent = totalSent + unspent.Value; if (totalSent > amount + fees) { break; } } if (totalSent < amount + fees) { throw new Exception("Not enough funds"); } Console.WriteLine("availableMoney Money : " + totalSent.ToString()); tx.Outputs.Add(new TxOut(amount, receiver)); //.GetAddress())); tx.Outputs.Add(new TxOut(totalSent - amount - (fees), sender.GetAddress())); tx.Sign(net, sender.PrivateKey, false); Console.WriteLine(tx); client.SendRawTransaction(tx); /* * using (var node = Node.Connect(net, "127.0.0.1", ProtocolVersion.PROTOCOL_VERSION, true, default(CancellationToken))) //Connect to the node * { * node.VersionHandshake(); //Say hello * //Advertize your transaction (send just the hash) * node.SendMessage(new InvPayload(InventoryType.MSG_TX, tx.GetHash())); * //Send it * node.SendMessage(new TxPayload(tx)); * Thread.Sleep(500); //Wait a bit * * for (int i = 0; i < 6; i++) * client.setGenerate(true); * client.setGenerate(false); * * Thread.Sleep(500); //Wait a bit * //var chain = new PersistantChain(net, new StreamObjectStream<ChainChange>(File.Open("MainChain.dat", FileMode.OpenOrCreate))); * // node.SynchronizeChain(chain); * } * for (int i = 0; i < 6; i++) * client.setGenerate(true); * client.setGenerate(false); * */ }
public async Task <Transaction> BuildTransaction( BitcoinSecret senderPrivateKey, BitcoinPubKeyAddress receiverPublicKey, BitcoinPubKeyAddress futureSenderPublicKey, string hexData) { decimal savedRequiredAmount = 0; var futureSender = await GetAddress(futureSenderPublicKey.ToString()); if (futureSender.balance < fee * 2) { savedRequiredAmount = fee * ThreadholdRate; } else { savedRequiredAmount = fee; } var requiredAmount = savedRequiredAmount + fee; //var requiredAmount = savedRequiredAmount + fee + license.ToDecimal(MoneyUnit.BTC); var txBuilder = network.CreateTransactionBuilder().AddKeys(senderPrivateKey); var allUtxo = await ListUnspentByAddress(senderPrivateKey.GetAddress().ToString()); allUtxo = allUtxo.OrderBy(u => u.amount).ToList(); var index = 0; var sumSentAmount = 0m; try { while (requiredAmount > 0) { txBuilder = txBuilder.AddCoins(allUtxo[index].AsCoin()); requiredAmount -= allUtxo[index].amount; sumSentAmount += allUtxo[index].amount; index++; } } catch (Exception) { throw new Exception("No enough money for fee transactions."); } var tx = txBuilder .Send(futureSenderPublicKey, new Money(savedRequiredAmount, MoneyUnit.BTC)) .Send(new Script("OP_RETURN " + hexData), Money.Zero) //.Send(provisionAddress, license) .SendFees(new Money(fee, MoneyUnit.BTC)) .SetChange(senderPrivateKey.GetAddress()) .BuildTransaction(true); if (txBuilder.Verify(tx)) { return(tx); } else { throw new InvalidOperationException("Cannot build transaction according to the given private key."); } }
public async Task <Transaction> BuildTransaction( BitcoinSecret senderPrivateKey, BitcoinPubKeyAddress receiverPublicKey, decimal provisionAmount, string hexData, string inputTransaction = null) { var requiredAmount = provisionAmount + fee; var txBuilder = network.CreateTransactionBuilder().AddKeys(senderPrivateKey); var allUtxo = await ListUnspentByAddress(senderPrivateKey.GetAddress().ToString()); if (string.IsNullOrEmpty(inputTransaction)) { allUtxo = allUtxo.OrderBy(u => u.amount).ToList(); } else { allUtxo = allUtxo.Where(u => u.txid == inputTransaction).ToList(); if (allUtxo.Count == 0) { throw new Exception("The specified transaction id is not found."); } } var index = 0; var sumSentAmount = 0m; try { while (requiredAmount > 0) { txBuilder = txBuilder.AddCoins(allUtxo[index].AsCoin()); requiredAmount -= allUtxo[index].amount; sumSentAmount += allUtxo[index].amount; index++; } } catch (Exception) { throw new Exception("No enough money for fee transactions."); } var tx = txBuilder .Send(receiverPublicKey, new Money(provisionAmount, MoneyUnit.BTC)) .Send(new Script("OP_RETURN " + hexData), Money.Zero) .SendFees(new Money(fee, MoneyUnit.BTC)) .SetChange(senderPrivateKey.GetAddress()) .BuildTransaction(true); if (txBuilder.Verify(tx)) { return(tx); } else { throw new InvalidOperationException("Cannot build transaction according to the given private key."); } }
private static Transaction CreateSignTransaction(string privateKey, string destinationAddress, List <TxIn> inputs, decimal amountToSend, decimal amountToReturn, bool isTest = false, decimal fee = 0.0005m, bool donation = false, decimal donationAmount = 0.001m, string donationAddress = "", string otherInfo = "") { try { var network = GetNetwork(isTest); var secret = new BitcoinSecret(privateKey, network); // key = secret.PrivateKey; Transaction transaction = new ConsensusFactory().CreateTransaction(); foreach (var txIn in inputs) { txIn.ScriptSig = secret.GetAddress().ScriptPubKey; transaction.AddInput(txIn); } TxOut txout = new TxOut(); var destination = BitcoinAddress.Create(destinationAddress, network); txout.ScriptPubKey = destination.ScriptPubKey; //Money moneyFee = Money.Satoshis(fee); Money moneyFee = Money.Coins(fee); Money moneyToSend = Money.Coins(amountToSend); txout.Value = moneyToSend - moneyFee; //the fee money is taken of from the buyer, so if you want to pay him more, add the fee to the money you send. transaction.AddOutput(txout); if (donation) { TxOut txoutDonation = new TxOut(); var destinationDonation = BitcoinAddress.Create(donationAddress, network); txoutDonation.ScriptPubKey = destinationDonation.ScriptPubKey; txoutDonation.Value = Money.Coins(donationAmount); transaction.AddOutput(txoutDonation); } //incase there is a change we need to bring it back to the sender. if (amountToReturn > 0) { TxOut txoutChange = new TxOut(); var returnDestination = BitcoinAddress.Create(secret.GetAddress().ToString(), network); txoutChange.ScriptPubKey = returnDestination.ScriptPubKey; txoutChange.Value = Money.Coins(amountToReturn); transaction.AddOutput(txoutChange); } transaction.Sign(secret, false); return(transaction); //return transaction.GetHash().ToString(); //transaction.ToHex().ToString() //Getting the Hex and pasting it in broadcast network like testNet blockcypher } catch (Exception ex) { throw new Exception("Error in CreateSignTransaction"); } }
public async void PrepareWallet() { 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 lowBalanceWallet) { 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); }
public JsonResult BalanceCheck(int Id) { var publicKeyBalance = db.Wallet.FirstOrDefault(t => t.IsActive && t.Id == Id); if (!string.IsNullOrWhiteSpace(publicKeyBalance.PublicKey)) { Transaction transaction = new Transaction(); QBitNinjaClient client = new QBitNinjaClient(network); var bitcoinSecret = new BitcoinSecret(publicKeyBalance.PrivateKey); var balanceModel = client.GetBalance(bitcoinSecret.GetAddress()); if (balanceModel.Result.Operations.Count() == 0) { return(Json(new { State = false, Msg = "İşlem Hareketi Bulunamadı!" }, JsonRequestBehavior.AllowGet)); } else { var unspendCoin = new List <Coin>(); var operationList = balanceModel.Result.Operations.Where(p => p.Confirmations >= 0).ToList(); foreach (var operation in operationList) { unspendCoin.AddRange(operation.ReceivedCoins.Select(coin => coin as Coin)); } var balance = unspendCoin.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC)); var transId = operationList.Select(t => t.TransactionId.ToString()).FirstOrDefault(); if (publicKeyBalance.Balance == 0) { publicKeyBalance.PublicKey = bitcoinSecret.GetAddress().ToString(); publicKeyBalance.PrivateKey = bitcoinSecret.ToString(); publicKeyBalance.Balance = balance; publicKeyBalance.TransactionId = transId; publicKeyBalance.TransactionUrl = string.Format("<a href='http://tapi.qbit.ninja/transactions/{0}' target='_blank'>{1}</a>", transId, transId); var walletBalanceUpdateResult = db.SaveChanges(); if (walletBalanceUpdateResult > 0) { return(Json(new { State = true, publicKeyBalance.Id, publicKeyBalance.Balance, publicKeyBalance.TransactionUrl }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { State = false, Msg = "Bakiye kaydetme sırasında hata oluştu!" }, JsonRequestBehavior.AllowGet)); } } else { return(Json(new { State = true, publicKeyBalance.Id, publicKeyBalance.Balance, publicKeyBalance.TransactionUrl }, JsonRequestBehavior.AllowGet)); } } } else { return(Json(new { State = false, Msg = "Cüzdan bulunamadı!" }, JsonRequestBehavior.AllowGet)); } }
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 async Task Start() { var data = (await _walletCredentials.GetDataAsync()).ToList(); Console.WriteLine($"Items count: [{data.Count}]"); var idx = 0; foreach (var item in data) { try { var secret = new BitcoinSecret(item.PrivateKey); var address = secret.GetAddress().ToString(); if (await _keyRepository.GetPrivateKey(address) == null) { var encrypted = Encryption.EncryptAesString(secret.ToString(), _password); await _keyRepository.CreatePrivateKey(address, encrypted); } idx++; if (idx % 10 == 0) { Console.WriteLine($"Processed {idx} of {data.Count} records"); } } catch (Exception e) { var c = Console.BackgroundColor; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"Error: db id [{item.RowKey}], exception: [{e.Message}]"); Console.BackgroundColor = c; } } }
/// <summary> /// Publish a wallet contract to blockchain and save the published to local data store. /// </summary> /// <param name="newContract">A to-be-published wallet contract.</param> /// <param name="creator">Private key of the creator</param> /// <returns>Return transaction ID if published. Throw exception if there is an error.</returns> public async Task <string> PublishContract(WalletContract newContract, BitcoinSecret creator) { try { ValidateContract(newContract); } catch (Exception) { throw; } var Data = $"{DomainHex}{newContract.NameHex}{newContract.TokenHex}{BitConverterExtension.GetHexBytes(newContract.TotalSupply)}" + $"{newContract.NoOfDecimal.ToString("x4")}{newContract.Conditions.ByteArrayToString()}"; var transaction = await insightAPI.BuildTransaction(creator, creator.GetAddress(), creator.GetAddress(), Data.ToLower()); var txId = await insightAPI.BroadcastTransaction(transaction); newContract.ID = txId.txid; var status = await insightAPI.GetSync(); newContract.StartingBlock = status.blockChainHeight; newContract.LastSyncedBlock = status.blockChainHeight; UpdateContract(newContract, true); return(newContract.ID); }
/// <summary> /// Create and broadcast a Electronic money wallet contract to blockchain. /// </summary> /// <param name="creator">Private key of the creator of wallet contract</param> /// <param name="Name">Maximum 8 bytes of binary value of token name </param> /// <param name="TokenName">Maximum 8 bytes of binary value of token unit</param> /// <param name="TotalSupply">Maximum supply of electronic money</param> /// <param name="NoOfDecimal">Maximum number of digit after decimal point. Dust value than this will be cut off</param> /// <param name="autopublish">Auto publish the contract to blockchain</param> /// <returns>A local-store of wallet contract. Throw exception if there is invalid provided value.</returns> public async Task <WalletContract> CreateContract(BitcoinSecret creator, byte[] Name, byte[] TokenName, decimal TotalSupply, ushort NoOfDecimal, bool autopublish = true) { var newContract = new WalletContract() { Name = Name, TokenName = TokenName, TotalSupply = TotalSupply, NoOfDecimal = NoOfDecimal, OwnerPublicAddress = creator.GetAddress().ToString(), LastSyncedBlock = 0, Conditions = new byte[8] }; try { ValidateContract(newContract); } catch (Exception) { throw; } if (autopublish) { await PublishContract(newContract, creator); } return(newContract); }
public string GetPaymentTo() { Key privateKey = new Key(); BitcoinSecret bitcoinSecret = privateKey.GetWif(Network.Main); return(bitcoinSecret.GetAddress(ScriptPubKeyType.Legacy).ToString()); }
static void Main(string[] args) { var bitcoinPrivateKey = new BitcoinSecret("L1qVDci614EoauxwWPiWhiHps3mbUnu54Q4ckGFFqDkLBAF66E8H"); var address = bitcoinPrivateKey.GetAddress(); Console.WriteLine("Private Key: " + bitcoinPrivateKey); Console.WriteLine("Address: " + address); var client = new QBitNinjaClient(Network.Main); var balance = client.GetBalance(address).Result; Console.WriteLine(); foreach (var operation in balance.Operations) { Console.WriteLine("Received Transactions"); foreach (var coin in operation.ReceivedCoins) { Console.WriteLine(((Money)coin.Amount).ToDecimal(MoneyUnit.BTC) + " " + operation.TransactionId + " " + operation.FirstSeen); } Console.WriteLine(); Console.WriteLine("Sent Transactions"); foreach (var coin in operation.SpentCoins) { Console.WriteLine(((Money)coin.Amount).ToDecimal(MoneyUnit.BTC) + " " + operation.TransactionId + " " + operation.FirstSeen); } } Console.Read(); }
private void buttonConfirm_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxConfirmation.Text) || string.IsNullOrEmpty(textBoxEncKey.Text) || string.IsNullOrEmpty(textBoxPassword.Text) || string.IsNullOrEmpty(textBoxAddress.Text)) { MessageBox.Show(this, "You need to [Generate Key] first.", "knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (new HourGlass()) { try { BitcoinConfirmationCode confirmationCode = new BitcoinConfirmationCode(textBoxConfirmation.Text, Network.TestNet); BitcoinEncryptedSecretEC encKey = new BitcoinEncryptedSecretEC(textBoxEncKey.Text, Network.TestNet); BitcoinSecret secret = encKey.GetSecret(textBoxPassword.Text); BitcoinAddress address = new BitcoinAddress(textBoxAddress.Text); if (confirmationCode.Check(textBoxPassword.Text, address)) { if (secret.GetAddress() == address) { MessageBox.Show(this, "Confirmation that this Address depends on the Passphrase", "knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, "knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void TestNet() { var secret = new BitcoinSecret("Y5DBpagP98mTdpLXTsK4yXak5khia1QqSGtaTCXyft1d8N9ef8ba", Network.TestNet); var address = secret.GetAddress().ToString(); Assert.IsTrue(address == "whHoBujH1UpxN8uPd5DX23szXqmp7jf1qH"); }
public async Task CanGetPrivateKeysFromLockedAccountAsync() { string accountName = "account"; using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateBitcoinCoreNode(version: BitcoinCoreVersion15); builder.StartAll(); RPCClient rpcClient = node.CreateRPCClient(); var key = new Key(); string passphrase = "password1234"; rpcClient.SendCommand(RPCOperations.encryptwallet, passphrase); // Wait for recepient to process the command. await Task.Delay(300); builder.Nodes[0].Restart(); rpcClient = node.CreateRPCClient(); rpcClient.ImportAddress(key.PubKey.GetAddress(Network.RegTest), accountName, false); BitcoinAddress address = rpcClient.GetAccountAddress(accountName); rpcClient.WalletPassphrase(passphrase, 60); BitcoinSecret secret = rpcClient.DumpPrivKey(address); BitcoinSecret secret2 = rpcClient.GetAccountSecret(accountName); Assert.Equal(secret.ToString(), secret2.ToString()); Assert.Equal(address.ToString(), secret.GetAddress().ToString()); } }
private void buttonVerify_Click(object sender, EventArgs e) { try { using (new HourGlass()) { var fromBase58 = Util.Interpret(textBoxBase58.Text); if (fromBase58 is BitcoinSecret) { secret = fromBase58 as BitcoinSecret; address = secret.GetAddress(); } else { address = fromBase58 as BitcoinAddress; } sig = textBoxSig.Text; msg = textBoxMessage.Text; } string valid = address.VerifyMessage(msg, sig).ToString(); MessageBox.Show(this, valid, "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void SignUsingBuilder() { var secret = new BitcoinSecret("cSmnhYYG2mXRPvi1FoFDihT4bL5qy9DDhephoubJ7mwxb2sgLNGQ", Network.TestNet); BitcoinAddress fromAddressFromSecret = secret.GetAddress(ScriptPubKeyType.Legacy); BitcoinAddress fromAddress = BitcoinAddress.Create("mfk4BVNg4p4m7qPx3u398otHT97M9hotPR", Network.TestNet); BitcoinAddress toAddress = BitcoinAddress.Create("mkQporSV7myJLwfWEVyHMhphY9viiiEMWc", Network.TestNet); Transaction previousTransaction = Transaction.Create(Network.TestNet); previousTransaction.Outputs.Add(new TxOut(new Money(0.0001m, MoneyUnit.BTC), fromAddress)); var coinsToSpend = previousTransaction.Outputs.AsCoins(); TransactionBuilder transactionBuilder = Network.TestNet.CreateTransactionBuilder(); var tx = transactionBuilder .AddCoins(coinsToSpend) .AddKeys(secret) .Send(toAddress, Money.Coins(0.00009m)) .SendFees(Money.Coins(0.00001m)) .SetChange(fromAddress) .BuildTransaction(true); var check = transactionBuilder.Check(tx); if (transactionBuilder.Verify(tx, out var errors)) { Console.WriteLine("COME ON!"); } }
private static List <TransactionReceivedCoins> GetListTransaction(BitcoinSecret sonBitPrivateKey) { List <TransactionReceivedCoins> list = new List <TransactionReceivedCoins>(); try { var address = sonBitPrivateKey.GetAddress(); QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); BalanceModel myBalance = client.GetBalance(address, unspentOnly: true).Result; foreach (BalanceOperation op in myBalance.Operations) { List <Coin> lstCoin = new List <Coin>(); var receivedCoins = op.ReceivedCoins; foreach (Coin e in receivedCoins) { lstCoin.Add(e); } TransactionReceivedCoins objTransactionReceivedCoins = new TransactionReceivedCoins { ListCoins = lstCoin, TransactionID = op.TransactionId, Confirm = op.Confirmations }; list.Add(objTransactionReceivedCoins); } } catch (Exception ex) { Utilitys.WriteLog(fileLog, ex.Message); list = null; } return(list); }
/// <summary> /// Load account from "key.txt" file placed in the root exe directory. Doesnt work in WABS /// </summary> /// <param name="password">Passwotd to decrypt the loaded private key</param> /// <param name="filename">Filename with the key. Default name is dogekey.txt</param> /// <returns></returns> public async Task <bool> LoadAccount(string password, string filename = "dogekey.txt") { if (FileHelpers.IsFileExists(filename)) { try { var k = FileHelpers.ReadTextFromFile(filename); var kdto = JsonConvert.DeserializeObject <KeyDto>(k); AccountKey = new EncryptionKey(kdto.Key, fromDb: true); AccountKey.LoadPassword(password); AccountKey.IsEncrypted = true; Address = kdto.Address; Secret = new BitcoinSecret(AccountKey.GetEncryptedKey(), DogeTransactionHelpers.Network); BAddress = Secret.GetAddress(ScriptPubKeyType.Legacy); await StartRefreshingData(); return(true); } catch { throw new Exception("Cannot deserialize key from file. Please check file key.txt or delete it for create new address!"); } } else { await CreateNewAccount(password); } return(false); }
static void Main() { Key privateKey = new Key(); // generate a random private key BitcoinSecret mainNetPrivateKey = privateKey.GetBitcoinSecret(Network.Main); // get our private key for the mainnet BitcoinSecret testNetPrivateKey = privateKey.GetBitcoinSecret(Network.TestNet); // get our private key for the testnet Console.WriteLine(mainNetPrivateKey); // L5B67zvrndS5c71EjkrTJZ99UaoVbMUAK58GKdQUfYCpAa6jypvn Console.WriteLine(mainNetPrivateKey.GetAddress()); Console.WriteLine(testNetPrivateKey); // cVY5auviDh8LmYUW8conAfafseD6p6uFoZrP7GjS3rzAerpRKE9Wmuz Console.WriteLine(testNetPrivateKey.GetAddress()); bool WifIsBitcoinSecret = mainNetPrivateKey == privateKey.GetWif(Network.Main); Console.WriteLine(WifIsBitcoinSecret); // True BitcoinSecret bitcoinPrivateKey = privateKey.GetWif(Network.Main); // L5B67zvrndS5c71EjkrTJZ99UaoVbMUAK58GKdQUfYCpAa6jypvn Key samePrivateKey = bitcoinPrivateKey.PrivateKey; PubKey publicKey = privateKey.PubKey; BitcoinPubKeyAddress bitcoinPubicKey = publicKey.GetAddress(Network.Main); // 1PUYsjwfNmX64wS368ZR5FMouTtUmvtmTY //PubKey samePublicKey = bitcoinPubicKey.ItIsNotPossible; Console.ReadLine(); }
/// <summary> /// Retrieve key pair from a local data store. /// </summary> /// <returns>A Cryptokeypair object contains seed, private key, and public key. (BIP44)</returns> public CryptoKeyPair GetKey() { try { var data = collection.FindAll().FirstOrDefault(); CryptoKeyPair result = new CryptoKeyPair(); if (!string.IsNullOrEmpty(data?.Seed)) { var hdGenerator = new DigibyteHDGenerator(MainNetwork, "Thai", data.Seed); return(hdGenerator.KeyPair(0)); } else if (!string.IsNullOrEmpty(data?.PrivateKey)) { var secretKey = new BitcoinSecret(data.PrivateKey, MainNetwork); result.SecretKey = secretKey; result.PublicKey = secretKey.GetAddress(); return(result); } else { return(null); } } catch (System.Exception e) { return(null); } }
//-------------------------------------------------------------------------------- void Sample_05_SpendYourCoin() { /* * var network = NBitcoin.Network.TestNet; * var privateKey = new Key(); * var bitcoinPrivateKey = privateKey.GetWif(network); * var address = bitcoinPrivateKey.GetAddress(); * * Debug.Log(bitcoinPrivateKey); // cUwC2Dk7VvVyxF3jGyHdz5HTtxHYqHuQgWX1pnYvqckwCyUGStd3 * Debug.Log(address); // n3x4Q89kqkHSV5d33LaRbnnoDdTuvDjY5D */ var bitcoinPrivateKey = new BitcoinSecret("cUwC2Dk7VvVyxF3jGyHdz5HTtxHYqHuQgWX1pnYvqckwCyUGStd3"); var network = bitcoinPrivateKey.Network; var address = bitcoinPrivateKey.GetAddress(); Debug.Log(bitcoinPrivateKey); Debug.Log(address); // Get coin from https://testnet.manu.backend.hamburg/faucet var transactionID = uint256.Parse("13cb292d07883f6a87b2db52c807e411e6330c9d7756535a7169a3ced8fe4385"); QBitNinja4Unity.QBitNinjaClient.GetTransaction(transactionID, network, Sample_05_01); }
private static void SignTransaction() { string privateKey = "cSmnhYYG2mXRPvi1FoFDihT4bL5qy9DDhephoubJ7mwxb2sgLNGQ"; var secret = new BitcoinSecret(privateKey, Network.TestNet); var fromAddress = BitcoinAddress.Create("mfk4BVNg4p4m7qPx3u398otHT97M9hotPR", Network.TestNet); // == secret.GetAddress(); Script scriptSigFromAddress = fromAddress.ScriptPubKey; Script scriptSigFromSecret = secret.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey; var utxoSignature = "76a914027a52530751c0165299b9b8318746c3739e730388ac"; Script scriptSig = new Script(utxoSignature); string txHash = "581e53621313e977be64deb1b1afa97f000e5c9f352642341837e63733014af0"; uint256 transactionId = uint256.Parse(txHash); var previousOutpoint = new OutPoint(transactionId, 0); Transaction currentTransaction = Network.TestNet.CreateTransaction(); TxIn txInput = new TxIn(previousOutpoint, scriptSigFromAddress); //need to prove you own this input currentTransaction.Inputs.Add(txInput); var toAddress = BitcoinAddress.Create("mkQporSV7myJLwfWEVyHMhphY9viiiEMWc", Network.TestNet); Money fee = Money.Satoshis(1000); var money = new Money(0.0001M, MoneyUnit.BTC) - fee; var txOut = new TxOut(money, toAddress.ScriptPubKey); currentTransaction.Outputs.Add(txOut); currentTransaction.Sign(secret, new Coin(transactionId, 0, new Money(0.0001M, MoneyUnit.BTC), scriptSigFromAddress)); Console.WriteLine(currentTransaction.ToHex()); }
private void getPrivateKeyAndAddress() { PrivateKey = new BitcoinSecret("cSrSUDPKdEBZh9x2MeVaCu6Ce5xiFApU7sQuiS4mLUECJ5xqVqzi"); Address = PrivateKey.GetAddress(); Console.WriteLine($"Key: {PrivateKey}"); // cSrSUDPKdEBZh9x2MeVaCu6Ce5xiFApU7sQuiS4mLUECJ5xqVqzi Console.WriteLine($"Address: {Address}"); // n15TeiYwV65SQjaZnVc1E2g79pVjgSDCQV }
// ------------------------------------------- /* * Display messages on screen and buttons on screen */ void OnGUI() { GUI.skin = SkinUI; float fontSize = 1.2f * 15; // BUTTON CLEAR LOG float yGlobalPosition = 10; if (GUI.Button(new Rect(new Vector2(10, yGlobalPosition), new Vector2(Screen.width - 20, 2 * fontSize)), "Clear Log")) { m_activateTextArea = false; m_displayMessages.Clear(); } yGlobalPosition += 2.2f * fontSize; // GENERATE NEW KEY if (GUI.Button(new Rect(new Vector2(10, yGlobalPosition), new Vector2(Screen.width - 20, 2 * fontSize)), "Create free new address on ++" + (BitCoinController.Instance.IsMainNetwork ? "Main" : "TestNet") + "++ Network")) { Key newKey = new Key(); AddLog("+++GENERATING KEY FOR NETWORK[" + BitCoinController.Instance.Network.ToString() + "]+++"); BitcoinSecret mainNetKey = newKey.GetBitcoinSecret(BitCoinController.Instance.Network); AddLog("++++KEY GENERATED++++"); AddLog("PRIVATE KEY:"); AddLog("" + mainNetKey); AddLog("PUBLIC KEY:"); AddLog("" + mainNetKey.GetAddress()); } yGlobalPosition += 2.2f * fontSize; // LOG DISPLAY GUI.Label(new Rect(0, yGlobalPosition, Screen.width - 20, fontSize), "**PROGRAM LOG**"); yGlobalPosition += 1.2f * fontSize; int linesTextArea = 10; if (m_activateTextArea) { linesTextArea = 10; } else { linesTextArea = 2; } float finalHeighArea = linesTextArea * fontSize; m_scrollPosition = GUI.BeginScrollView(new Rect(10, yGlobalPosition, Screen.width - 20, Screen.height - yGlobalPosition), m_scrollPosition, new Rect(0, 0, 200, m_displayMessages.Count * finalHeighArea)); float yPosition = 0; for (int i = 0; i < m_displayMessages.Count; i++) { string message = m_displayMessages[i]; GUI.TextArea(new Rect(0, yPosition, Screen.width, finalHeighArea), message); yPosition += finalHeighArea; } GUI.EndScrollView(); }
public static void Pay() { // http://www.codeproject.com/Articles/835098/NBitcoin-Build-Them-All var fromSecret = Configuration["fromsecret"]; var toAddress = Configuration["toaddress"]; decimal amountBtc; if (string.IsNullOrWhiteSpace(fromSecret) || string.IsNullOrWhiteSpace(toAddress) || !decimal.TryParse(Configuration["amountbtc"], out amountBtc)) { Console.WriteLine("Usage: dotnet NBitcoin.PaymentServer.TestTool.dll -o pay -f <fromSecret> -t <toAddress> -b <amountBtc>"); return; } var fromBitcoinSecret = new BitcoinSecret(fromSecret); var toBitcoinAddress = BitcoinAddress.Create(toAddress); var amount = new Money(amountBtc, MoneyUnit.BTC); var fees = new Money(PaymentFeeBtc, MoneyUnit.BTC); var client = CreateRpcClient(); var unspentCoins = client.ListUnspent(0, 100000, fromBitcoinSecret.GetAddress()); var coins = unspentCoins.Select(u => u.AsCoin()); var txBuilder = new TransactionBuilder(); var tx = txBuilder .AddCoins(coins) .AddKeys(fromBitcoinSecret) .Send(toBitcoinAddress, amount) .SendFees(fees) .SetChange(fromBitcoinSecret.GetAddress()) .BuildTransaction(true); txBuilder.Verify(tx); Console.WriteLine("Submitting transaction: {0}", tx); client.SendRawTransaction(tx); Console.WriteLine("Transaction sent"); //Script script = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(.GenerateOutputScript(to); }
private void Send_Money_Click(object sender, RoutedEventArgs e) { BitcoinSecret lPrivKey = new BitcoinSecret(privKey.Text, Network.TestNet); string lAddress = lPrivKey.GetAddress().ToString(); address.Text = lAddress; lMw.address.Text = lAddress; Save(privKey.Text, lAddress); }
public static void TestDemo() { Key privKey = new Key(); // var demoSecret = privKey.GetWif(Network.TestNet); var demoSecret = new BitcoinSecret("cQUHRsd1RboEjK96wAfDMXby6yy7Wve2TpMvBHbPuAUksxje4brN"); BitcoinPubKeyAddress address = demoSecret.GetAddress(); string txId = "97967e6bef942ffc75ff920292510eddbd8665b6bb7382f95c63fff735a9cc23"; QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); var txResponse = client.GetTransaction(new uint256(txId)).Result; // Define the input transaction TxIn newInput = new TxIn(txResponse.ReceivedCoins[0].Outpoint, demoSecret.GetAddress().ScriptPubKey); // Define the output transactions TxOut newOut = new TxOut(); int outputSatoshis = 25000; Money newOutputToSend = Money.Satoshis(outputSatoshis); newOut.Value = newOutputToSend; string toAddress = "mg2b7TtbGhvn3rEjqabAdM594MzczbCy7a"; var newDestination = BitcoinAddress.Create(toAddress); newOut.ScriptPubKey = newDestination.ScriptPubKey; // Create the transaction Transaction newTransaction = new Transaction(); newTransaction.AddInput(newInput); newTransaction.AddOutput(newOut); newTransaction.Sign(demoSecret, txResponse.ReceivedCoins[0]); var node = Node.Connect(Network.TestNet, "54.241.159.189:18333"); node.VersionHandshake(); node.SendMessage(new InvPayload(newTransaction)); node.SendMessage(new TxPayload(newTransaction)); Thread.Sleep(4000); node.Disconnect(); int a = 6; }
public LobbyViewModel() { this._wifPrivateKey = "93Loqe8T3Qn3fCc87AiJHYHJfFFMLy6YuMpXzffyFsiodmAMCZS"; this.NetworkPlayers = new ObservableCollection <Peer>(); this.Clients = new List <BitPoker.NetworkClient.INetworkClient>(1); this.Clients.Add(new BitPoker.NetworkClient.APIClient("https://www.bitpoker.io/api/")); //this.Clients.Add(new Clients.NetSocketClient(IPAddress.Parse("127.0.0.1"))); this.Tables = new ObservableCollection <BitPoker.Models.Contracts.Table>(); Wallet = new WalletViewModel(_wifPrivateKey); _secret = new BitcoinSecret(_wifPrivateKey, Constants.Network); BitcoinAddress address = _secret.GetAddress(); //move this this.Me = new TexasHoldemPlayer() { Position = 0, BitcoinAddress = address.ToString(), IsDealer = true, IsBigBlind = true, Stack = 0 }; this.Backend = new ChatBackend(this.ProcessMessage, Wallet.Address.ToString()); this.InComingRequests = new ObservableCollection <IRequest>(); this.SentRequests = new ObservableCollection <IRequest>(); this.InComingResponses = new ObservableCollection <IResponse>(); this.SentResponses = new ObservableCollection <IResponse>(); //Announce IRequest request = new RPCRequest() { Method = "NewPeer", Params = new NewPeerRequest() { BitcoinAddress = Wallet.Address.ToString(), Version = 1.0M, Player = new Peer() { BitcoinAddress = Wallet.Address.ToString() }, TimeStamp = DateTime.UtcNow } }; this.Backend.SendRequest(request); this.SentRequests.Add(request); this.Logs = new ObservableCollection <Models.Log>(); }
public void CanGetPrivateKeysFromAccount() { var rpc = CreateRPCClient(); BitcoinAddress address = rpc.GetAccountAddress(TestAccount); BitcoinSecret secret = rpc.DumpPrivKey(address); BitcoinSecret secret2 = rpc.GetAccountSecret(TestAccount); Assert.Equal(secret.ToString(), secret2.ToString()); Assert.Equal(address.ToString(), secret.GetAddress().ToString()); }
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); }