예제 #1
0
        internal static BroadcastResponse ResponseToBroadcastResponse(string response)
        {
            var broadcastResponse = new BroadcastResponse();

            if (response.Contains("SUCCESS"))
            {
                var indexOfEndBracket = response.IndexOf("]", StringComparison.InvariantCulture);
                var indexOfPipe       = response.IndexOf("|", StringComparison.InvariantCulture);
                var lengthOfId        = indexOfPipe - indexOfEndBracket - 2;

                broadcastResponse.Scheduled = true;
                broadcastResponse.Response  = new Response
                {
                    ScheduleId = Convert.ToInt32(response.Substring(indexOfEndBracket + 2, lengthOfId)),
                    Text       = response.Substring(indexOfPipe + 1)
                };
            }
            else
            {
                var messageIndex = response.IndexOf("]", StringComparison.InvariantCulture) + 2;
                broadcastResponse.Scheduled = false;
                broadcastResponse.Error     = response.Substring(messageIndex);
            }

            return(broadcastResponse);
        }
예제 #2
0
        public void create(TransactionTemporaryViewModel transactionVM)
        {
            var secret = new ExtKey().GetWif(_network);
            var source = BitcoinAddress.Create(transactionVM.SourceAddress);
            var client = new QBitNinjaClient(_network);

            Transaction tx    = new Transaction();
            var         input = new TxIn();

            var transactionId = uint256.Parse(transactionVM.PrevTransactionId);

            input.PrevOut   = new OutPoint(new uint256(transactionVM.Hex), 1); //Transaction ID
            input.ScriptSig = source.ScriptPubKey;
            tx.AddInput(input);

            TxOut output       = new TxOut();
            var   desctination = BitcoinAddress.Create(transactionVM.DestinationAddress);
            Money fee          = Money.Satoshis(40000);

            output.Value        = Money.Coins(0.1m) - fee;
            output.ScriptPubKey = desctination.ScriptPubKey;
            tx.AddOutput(output);

            tx.Sign(secret, false);

            BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;
        }
예제 #3
0
        private async Task <BroadcastResponse> BroadcastAsync(ADStreamingCall <Envelope, BroadcastResponse> call, Envelope envelope, CancellationToken token)
        {
            BroadcastResponse resp = null;
            var rtask = Task.Run(async() =>
            {
                if (await call.Call.ResponseStream.MoveNext(token).ConfigureAwait(false))
                {
                    token.ThrowIfCancellationRequested();
                    resp = call.Call.ResponseStream.Current;
                    logger.Debug($"{this} resp status value: {resp.Status}, resp: {resp.Info}");
//TODO: mpiva: Review this, original JAVA code will throw exception on no success, channel init code, check for the status (Not Found) for retrying.
//TODO: mpiva: Report this as an error to the original JAVA SDK repo.

                    /*
                     * if (shutdown)
                     *  throw new OperationCanceledException($"Channel {channelName}, sendTransaction were canceled");
                     * throw new TransactionException($"Channel {channelName} orderer {name} status returned failure code {resp.Status} ({resp.Info}) during order registration");*/
                }
            }, token);
            await call.Call.RequestStream.WriteAsync(envelope).ConfigureAwait(false);

            token.ThrowIfCancellationRequested();
            await rtask.TimeoutAsync(TimeSpan.FromMilliseconds(ordererWaitTimeMilliSecs), token).ConfigureAwait(false);

            logger.Trace($"{this} Broadcast Complete.");
            return(resp);
        }
예제 #4
0
        public Task <bool> Send()
        {
            return(Task.Run(() =>
            {
                try
                {
                    foreach (var transaction in Transactions)
                    {
                        BroadcastResponse broadcastResponse = Api.Broadcast(transaction.Tx).Result;

                        if (!broadcastResponse.Success)
                        {
                            Console.WriteLine($"Broadcast Error {broadcastResponse.Error.ErrorCode}:{broadcastResponse.Error.Reason}");
                        }
                        else
                        {
                            transaction.IsBroadcasted = true;
                        }
                    }

                    return Transactions.Where(tx => tx.IsBroadcasted == true).Any();
                }
                catch (Exception err)
                {
                    Console.WriteLine($"Broadcast Error: {err.Message}");
                    return false;
                }
            }));
        }
예제 #5
0
        //transaction https://live.blockcypher.com/btc-testnet/tx/4761929185a3dd80f23670efb854ba3d7ab5a151f296ea7c38015ceb821ee838/
        public static void Transaction1()
        {
            ////P2WPKH - PS2SH = (Segwit P2PKH wrapped into P2SH for interoperability)
            //https://bitcoin.stackexchange.com/questions/59231/how-to-sign-a-segwit-transaction-via-nbitcoin

            var bitcoinPrivateKey = new BitcoinSecret("cS88F3sJycinEUfGGMQH4w4izaNjEec97VAHsoQZYmDjZJwK1wuf");
            var key = bitcoinPrivateKey.PrivateKey;

            var network = bitcoinPrivateKey.Network;
            var address = bitcoinPrivateKey.GetAddress();

            var client        = new QBitNinjaClient(network);
            var transactionId = uint256.Parse("8722a9a073fc4d7d27cf07540ddee2d4449f36d1470eddedb8bd8a70ded88fe3");


            var transactionResponse = client.GetTransaction(transactionId).Result;

            Coin[] coinsToSpend       = transactionResponse.Transaction.Outputs.AsCoins().ToArray();
            var    destinationAddress = BitcoinAddress.Create("2NA5L1cYrMRQEUYisWCK7bjfM1UFdxumYps", network);

            //coinsToSpend = new  Coin[]{coinsToSpend[83] };

            var coins =
                coinsToSpend
                .Where(c => c.TxOut.ScriptPubKey == bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey.PaymentScript)
                .ToArray();

            //expect just 1 coin, coinsToSpend[83]

            TransactionBuilder builder = new TransactionBuilder();

            builder.AddCoins(coins);
            builder.AddKeys(bitcoinPrivateKey);
            builder.Send(destinationAddress, new Money(0.000000015m, MoneyUnit.BTC));
            builder.SendFees(Money.Coins(0.001m));
            builder.SetChange(address.ScriptPubKey);
            var     signedTx     = builder.BuildTransaction(true);
            String  hexPreVerify = signedTx.ToHex();
            Boolean b            = builder.Verify(signedTx);
            String  hex          = signedTx.ToHex(); //"01000000000101e38fd8de708abdb8eddd0e47d1369f44d4e2de0d5407cf277d4dfc73a0a922875300000017160014a017d15c9cfacea59c4a3984b32f2282e617de8effffffff01f6b4b600000000001976a914a017d15c9cfacea59c4a3984b32f2282e617de8e88ac02473044022028f8440e4d85eca57a99fadda133fc9ce48b523a4b4d2438aaaad0a296d8d7270220112eb54f7e8a1f311b6b4dc0a15c4b3a5311948724a8aa0657da52da6b26fc68012102b6d3f00966c6797c69b98cc7d4f7ec0e9ec8aee68f2fccb5cec061eeaee47f8900000000"

            BroadcastResponse broadcastResponse = client.Broadcast(signedTx).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 transaciton in any block explorer:");
                Console.WriteLine(signedTx.GetHash());
            }
        }
예제 #6
0
        public async Task BroadcastAsync(Transaction tx)
        {
            if (tx == null)
            {
                throw new ArgumentNullException("tx");
            }

            BroadcastResponse broadcastResponse = await Client.Broadcast(tx);

            if (!broadcastResponse.Success)
            {
                throw new QBitNinjaException(broadcastResponse.Error.ErrorCode, broadcastResponse.Error.Reason);
            }
        }
예제 #7
0
        public JsonResult SecondMethodBtcSend(int gondericiId, int aliciId, string miktar)
        {
            var gondericiModel = db.Wallet.Where(t => t.IsActive && t.Id == gondericiId).FirstOrDefault();

            if (gondericiModel != null)
            {
                Transaction        transaction        = new Transaction();
                TransactionBuilder transactionBuilder = new TransactionBuilder();
                QBitNinjaClient    client             = new QBitNinjaClient(network);
                var txRepo            = new NoSqlTransactionRepository();
                var sendAmount        = Money.Parse(miktar);
                var senderKey         = new BitcoinSecret(gondericiModel.PrivateKey);
                var receivedPublicKey = BitcoinAddress.Create(db.Wallet.FirstOrDefault(t => t.IsActive && t.Id == aliciId).PublicKey);
                var balance           = client.GetBalance(senderKey.GetAddress(), true).GetAwaiter().GetResult().Operations.SelectMany(o => o.ReceivedCoins).ToArray();

                transaction = transactionBuilder
                              .AddCoins(balance)
                              .AddKeys(senderKey)
                              .Send(receivedPublicKey, sendAmount)
                              .SendFees("0.0004")
                              .SetChange(senderKey)
                              .BuildTransaction(sign: true);

                transactionBuilder.SignTransaction(transaction);
                transactionBuilder.Verify(transaction);

                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! You can check out the hash of the transaciton in any block explorer:");
                    Console.WriteLine(transaction.GetHash());
                }
                //var result = client.Broadcast(transaction);
                //if (transactionBuilder.Verify(transaction))
                //{
                //    txRepo.Put(transaction.GetHash(), transaction);
                //    var hexResult = transaction.ToHex();
                //}
                return(Json(new { State = false, Msg = "İşlem Başarılı" }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new { State = true, Msg = "İşlem Başarılı" }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #8
0
        public static TransferResult TransferBit(string privateKeyFrom, string addressFrom, string destinationAddressToSendMoney, decimal amountToSend, bool isTest = false, decimal fee = 0.0005m, bool donation = false, decimal donationAmount = 0.001m, string donationAddress = "", string otherInfo = "")
        {
            try
            {
                var transferResult    = new TransferResult();
                var network           = GetNetwork(isTest);
                var totalAmountToSend = amountToSend;                  //Fee is not calculated because it's already deducted from the amountToSend
                if (donation)
                {
                    totalAmountToSend += donationAmount;                     //adding the donation.
                }
                var         txInHelper     = GetUnSpentTransactionFromAddress(addressFrom, totalAmountToSend, isTest);
                decimal     amountToReturn = txInHelper.Sum - totalAmountToSend;
                Transaction transaction    = CreateSignTransaction(privateKeyFrom, destinationAddressToSendMoney, txInHelper.inputs, amountToSend, amountToReturn, isTest, fee, donation, donationAmount, donationAddress, otherInfo);
                if (transaction == null)
                {
                    transferResult.Message = "Transaction Error";
                    return(transferResult);
                }
                transferResult.TransactionHex  = transaction.ToHex().ToString();
                transferResult.TransactionHash = transaction.GetHash().ToString();

                QBitNinjaClient   client            = new QBitNinjaClient(network);
                BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

                transferResult.Success = broadcastResponse.Success;
                //it's appear that even with an error, the broadcast is working.
                if (broadcastResponse.Error != null)
                {
                    transferResult.Message   = "Broadcast Error";
                    transferResult.ErrorCode = broadcastResponse.Error.ErrorCode.ToString();
                    transferResult.Reason    = broadcastResponse.Error.Reason;
                }


                //if (!broadcastResponse.Success || broadcastResponse.Error != null)
                //{
                //	transferResult.Message = "Broadcast Error";
                //	return transferResult;
                //}

                //transferResult.Message = "Success";
                //transferResult.Success = true;
                return(transferResult);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message);
            }
        }
예제 #9
0
        public void Send()
        {
            //later set bitcoin change on new derived adress!
            string amount = this.amount.ToString();
            string fee    = this.fee.ToString();

            transaction = transactionBuilder.AddKeys(bitcoinSecrets)
                          .AddCoins(unspentCoins)
                          .Send(destination, amount)
                          .SetChange(bitcoinSecrets[0].GetAddress())
                          .SendFees(fee)
                          .BuildTransaction(true);

            QBitNinjaClient   client            = new QBitNinjaClient(Network.TestNet);
            BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;
        }
예제 #10
0
        static void Main(string[] args)
        {
            var coin = new Coin(
                fromTxHash: new uint256("668c63369dfb6f6ebcd07aa36a4f1e9f252f8b3f976fcc84d540e03e54cdcc0a"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(2730),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914aef515f8874638687187da27bd008c3e7f5c68c188ac")));
            BitcoinAssetId assetId = new BitcoinAssetId("oPvD7Nn3eKHkWkwwG4i2HRjVJEhv4d6SEW");
            ColoredCoin    colored = coin.ToColoredCoin(assetId, 21000000);

            var book       = BitcoinAddress.Create("mi7TqrUCAKZ3pFuRaLZvFWhjrktbcyZf54");
            var nicoSecret = new BitcoinSecret("cUQo9VhkwZ8zMUJA8cFEY5MLHiQJMhcGKk9SUbRVDCB3yveUq66z");
            var nico       = nicoSecret.GetAddress();       //mwU3UJ1VXX3GxKKQHdscw1TvWSrMKdtymR

            var forFees = new Coin(
                fromTxHash: new uint256("a0c35a09e52af1a116d1e1233b952511ca7cae3aef5e0ea888b77167cb22e0fc"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(300000000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914aef515f8874638687187da27bd008c3e7f5c68c188ac")));

            TransactionBuilder builder = new TransactionBuilder();
            var tx = builder
                     .AddKeys(nicoSecret)
                     .AddCoins(colored, forFees)
                     .SendAsset(book, new AssetMoney(assetId, 100000))
                     .SetChange(nico)
                     .SendFees(Money.Coins(0.001m))
                     .BuildTransaction(true);

            Console.WriteLine(tx);
            Console.WriteLine(builder.Verify(tx));

            var client = new QBitNinjaClient(Network.TestNet);
            BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode);
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success!");
            }
        }
예제 #11
0
        //transaction https://live.blockcypher.com/btc-testnet/tx/ca678d531e9c8a3cd95e1e33a2562cf0b8a44793e51b46ac7602a72cbe7e1bd0/
        public static void Transaction3()
        {
            QBitNinjaClient client;

            Transaction signedTx = getTransaction(out client);

            BroadcastResponse broadcastResponse = client.Broadcast(signedTx).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 transaciton in any block explorer:");
                Console.WriteLine(signedTx.GetHash()); //id: ca678d531e9c8a3cd95e1e33a2562cf0b8a44793e51b46ac7602a72cbe7e1bd0
            }
        }
예제 #12
0
        public static bool PropagarTransacao(Transaction transacao, Network rede)
        {
            var client = new QBitNinjaClient(rede);

            BroadcastResponse broadcastResponse = client.Broadcast(transacao).Result;

            if (!broadcastResponse.Success)
            {
                /*Console.Error.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode);
                 * Console.Error.WriteLine("Error message: " + broadcastResponse.Error.Reason);*/
                return(false);
            }
            else
            {
                /*Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
                 * Console.WriteLine(transacao.GetHash());*/
                return(true);
            }
        }
예제 #13
0
        // 演習5: Androidへ送金してみよう
        public static void txBtcToAndroidWallet(decimal txValue)
        {
            decimal txFee = (decimal)0.01;

            // トランザクションを作成
            Transaction txToAndroid = new Transaction();

            // 入力
            QBitNinjaClient        client     = new QBitNinjaClient(Network.TestNet);
            GetTransactionResponse txForInput = client.GetTransaction(uint256.Parse(txIdToSpend)).Result;
            decimal txFund = (decimal)50.0;
            var     a      = txForInput.ReceivedCoins[indexOutputToSpend].Amount;

            txToAndroid.Inputs.Add(new TxIn()
            {
                PrevOut   = txForInput.ReceivedCoins[indexOutputToSpend].Outpoint,
                ScriptSig = BitcoinAddress.Create(myAddress).ScriptPubKey,
            });

            // 出力1: Andoroidへの送金
            txToAndroid.Outputs.Add(new TxOut()
            {
                Value        = Money.Coins((decimal)txValue),
                ScriptPubKey = new BitcoinPubKeyAddress(myAddress).ScriptPubKey,
            });

            // 出力2: 自分に返ってくるおつり
            txToAndroid.Outputs.Add(new TxOut()
            {
                Value        = Money.Coins((decimal)(txFund - txFee - txValue)),
                ScriptPubKey = new BitcoinPubKeyAddress(AndroidAddress).ScriptPubKey,
            });

            // トランザクションに署名
            txToAndroid.Sign(new BitcoinSecret(myWif), false);

            // ブロックチェーンにメッセージを送信
            BroadcastResponse res = client.Broadcast(txToAndroid).Result;
        }
예제 #14
0
        static void Main(string[] args)
        {
            var coin = new Coin(
                fromTxHash: new uint256("e2b308ea38112ae79ff2cc67d686c3dcd737214290802c1905b76e76c89783d4"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(300000000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a9141c770f57182260756319ca5e0af31e19b37288b288ac"))
                );

            var issuance = new IssuanceCoin(coin);

            var nico    = BitcoinAddress.Create("mwU3UJ1VXX3GxKKQHdscw1TvWSrMKdtymR");
            var bookKey = new BitcoinSecret("cRETrCgfbU273XmpFDQr4GhsqU4cXB7ECQuoGtCrRmgy1U2jLu1f");
            TransactionBuilder builder = new TransactionBuilder();

            var tx = builder
                     .AddKeys(bookKey)
                     .AddCoins(issuance)
                     .IssueAsset(nico, new AssetMoney(issuance.AssetId, quantity: 21000000))
                     .SendFees(Money.Coins(0.001m))
                     .SetChange(bookKey.GetAddress())
                     .BuildTransaction(true);

            Console.WriteLine(tx);
            Console.WriteLine(builder.Verify(tx));

            var client = new QBitNinjaClient(Network.TestNet);
            BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode);
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success!");
            }
        }
예제 #15
0
        public IActionResult About(string transactonHex = "dc7268d85689fe3a4dade2a5886794237221fb0161e59f12d8128c46ca7fab90")
        {
            ViewData["Message"] = "Your application description page.";

            var network = Network.TestNet;

            //mysLDbXCoie81EysydNHfSTva5sy4rRzKB

            var secret = new ExtKey().GetWif(network); //new BitcoinSecret("943b00f1-1488-4d44-91fa-f3bcc5789099");
            var key    = secret.PrivateKey;
            var client = new QBitNinjaClient(network);

            Transaction tx    = new Transaction();
            var         input = new TxIn();

            var transactionId = uint256.Parse("dc7268d85689fe3a4dade2a5886794237221fb0161e59f12d8128c46ca7fab90");

            //  var transactionResponse = client.GetTransaction(transactionId).Result;

            input.PrevOut   = new OutPoint(new uint256(transactonHex), 1); //Transaction ID
            input.ScriptSig = key.GetBitcoinSecret(network).GetAddress().ScriptPubKey;
            tx.AddInput(input);

            TxOut output       = new TxOut();
            var   desctination = BitcoinAddress.Create("mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf");
            Money fee          = Money.Satoshis(40000);

            output.Value        = Money.Coins(0.1m) - fee;
            output.ScriptPubKey = desctination.ScriptPubKey;
            tx.AddOutput(output);

            tx.Sign(secret, false);

            BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;

            return(View());
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Spend money. </summary>
        ///
        /// <exception cref="Exception">    Thrown when an exception error condition occurs. </exception>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        private void SpendMoney()
        {
            using (var scope = _container?.BeginLifetimeScope())
            {
                var logger = scope?.Resolve <MSBaseLogger>();
                logger?.LogInformation(Name + " Bitcoin SpendMoney");
                Console.WriteLine("Spending Money", Color.Aqua);

                #region IMPORT PRIVKEY

                var bitcoinPrivateKey = new BitcoinSecret("cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x");
                var network           = bitcoinPrivateKey.Network;

                #endregion

                var address = bitcoinPrivateKey.GetAddress();
                logger?.LogInformation(bitcoinPrivateKey.ToString());
                logger?.LogInformation(address?.ToString());


                var client              = new QBitNinjaClient(network);
                var transactionId       = uint256.Parse("e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3");
                var transactionResponse = client.GetTransaction(transactionId)?.Result;

                logger?.LogInformation(transactionResponse?.TransactionId.ToString());
                logger?.LogInformation(transactionResponse?.Block.Confirmations.ToString());


                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");
                }
                logger?.LogInformation("We want to spend " + outPointToSpend.N + 1 + ". outpoint:");
                Console.WriteLine("We want to spend " + outPointToSpend.N + 1 + ". outpoint:", Color.Aqua);

                var transaction = new Transaction();
                transaction.Inputs?.Add(new TxIn()
                {
                    PrevOut = outPointToSpend
                });

                var hallOfTheMakersAddress = new BitcoinPubKeyAddress("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB");

                // How much you want to TO
                var hallOfTheMakersAmount = new Money((decimal)0.5, MoneyUnit.BTC);
                var minerFee = new Money((decimal)0.0001, MoneyUnit.BTC);
                // How much you want to spend FROM
                var   txInAmount       = (Money)receivedCoins[(int)outPointToSpend.N]?.Amount;
                Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;

                TxOut hallOfTheMakersTxOut = new TxOut()
                {
                    Value        = hallOfTheMakersAmount,
                    ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
                };

                TxOut changeBackTxOut = new TxOut()
                {
                    Value        = changeBackAmount,
                    ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
                };

                transaction.Outputs?.Add(hallOfTheMakersTxOut);
                transaction.Outputs?.Add(changeBackTxOut);

                var message = "Our first bitcoin transaction together!";
                var bytes   = Encoding.UTF8.GetBytes(message);
                transaction.Outputs?.Add(new TxOut()
                {
                    Value        = Money.Zero,
                    ScriptPubKey = TxNullDataTemplate.Instance?.GenerateScriptPubKey(bytes)
                });

                // It is also OK:
                transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;
                transaction.Sign(bitcoinPrivateKey, false);

                BroadcastResponse broadcastResponse = client.Broadcast(transaction)?.Result;

                BitcoinSpendReceipt r = new BitcoinSpendReceipt();
                if (!broadcastResponse.Success)
                {
                    logger?.LogError($"ErrorCode: {broadcastResponse.Error.ErrorCode}");
                    Console.WriteLine($"ErrorCode: {broadcastResponse.Error.ErrorCode}", Color.Red);
                    logger?.LogError("Error message: " + broadcastResponse.Error.Reason);
                    Console.WriteLine("Error message: " + broadcastResponse.Error.Reason, Color.Red);
                    r.success = false;
                }
                else
                {
                    logger?.LogInformation("Success! You can check out the hash of the transaction in any block explorer:");
                    Console.WriteLine("Success! You can check out the hash of the transaction in any block explorer:", Color.Green);
                    logger?.LogInformation(transaction.GetHash()?.ToString());
                    Console.WriteLine(transaction.GetHash()?.ToString(), Color.Green);
                    r.success = true;
                }

                r.time   = SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc();
                r.amount = txInAmount.ToDecimal(MoneyUnit.BTC);
                Bus.Publish(r, "Bitcoin");
            }
        }
예제 #17
0
        /// <summary>
        /// Send a message of 80 bytes or less
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool SendMessage(string message)
        {
            var messageBytes = Encoding.UTF8.GetBytes(message);

            //Create a client for our QBitNinja API calls
            var client = new QBitNinjaClient(_network);

            var privateKey = (_contractorHdRoot.Derive(new KeyPath("m/44'/0'/0'/0/0"))).PrivateKey.GetWif(_network);
            var secret     = new BitcoinSecret(privateKey.ToString(), _network);

            var changeAddress = secret.GetAddress().ScriptPubKey;
            int changeAmount  = 166712111;

            string previousOutputTxId = "af6836c0ced8dad52ae7a02d5f81185a2cd5c369e11e368b35d2bc2bea960e2e";
            int    unspentOutputIndex = 0; //<-- The index of the unspent output from the previous transaction


            try
            {
                var transaction = new Transaction();

                //Previous input with spendable assets
                transaction.Inputs.Add(new TxIn()
                {
                    PrevOut   = new OutPoint(new uint256(previousOutputTxId), unspentOutputIndex), //<-- The output we are spending from
                    ScriptSig = secret.GetAddress().ScriptPubKey
                });

                //The message
                transaction.Outputs.Add(new TxOut()
                {
                    Value        = Money.Zero,
                    ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(messageBytes)
                });

                // The change address for the contractor
                transaction.Outputs.Add(new TxOut()
                {
                    ScriptPubKey = changeAddress,
                    Value        = Money.Satoshis(changeAmount)
                });


                transaction.Sign(secret, false);


                Console.WriteLine("Transaction signed and broadcast.");

                BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;


                Console.WriteLine("Transaction ID: " + transaction.GetHash().ToString());
                Console.WriteLine();

                if (broadcastResponse.Success)
                {
                    Console.WriteLine("Broadcast succeeded!");
                }
                else
                {
                    Console.WriteLine("Broadcase Error!");
                    Console.WriteLine();
                    Console.WriteLine(broadcastResponse.Error.Reason);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }



            Console.WriteLine();
            return(true);
        }
예제 #18
0
        /// <summary>
        /// Simple transaction that is locked for x amount of hours before being processed
        /// </summary>
        public static bool SimpleTimeLockContract()
        {
            //Create a client for our QBitNinja API calls
            var client = new QBitNinjaClient(_network);

            var contractorPrivateKey = (_contractorHdRoot.Derive(new KeyPath("m/44'/0'/0'/0/0"))).PrivateKey.GetWif(_network);
            var contractorSecret     = new BitcoinSecret(contractorPrivateKey.ToString(), _network);

            var contracteeAddress = BitcoinAddress.Create("n4bEeKENL9rED2cG31TjSNzPs6T15TCq96", _network);

            //Calculate all payments and fees
            var contracteePaymentAmount = new Money(0.1m, MoneyUnit.BTC);
            var minerFee = new Money(0.00007m, MoneyUnit.BTC);


            int lockTimeMinutes = 5; // <-- Minutes to wait until transaction is allowed to process
            var lockTime        = new LockTime(DateTimeOffset.UtcNow.AddMinutes(5));

            Console.WriteLine("LockTime set to:" + lockTime.ToString());



            //Collect the spendable coins from a previous transction
            GetTransactionResponse transactionResponse = client.GetTransaction(uint256.Parse("e4a06cac11b257908a908e90dda19b4b5e3d5a0f172d6b90ad8b0950878507be")).Result;
            List <ICoin>           receivedCoins       = transactionResponse.ReceivedCoins;

            OutPoint outPointToSpend = null;

            Console.WriteLine("------ Available Coins ------");
            Console.WriteLine();

            foreach (var coin in receivedCoins)
            {
                if (coin.TxOut.ScriptPubKey == contractorPrivateKey.ScriptPubKey)
                {
                    outPointToSpend = coin.Outpoint;

                    Money amount        = (Money)coin.Amount;
                    var   paymentScript = coin.TxOut.ScriptPubKey;
                    var   address       = paymentScript.GetDestinationAddress(_network);

                    Console.WriteLine("Amount: " + amount.ToDecimal(MoneyUnit.BTC) + " | " + paymentScript + " | " + address);
                    Console.WriteLine();
                }
            }


            if (outPointToSpend == null)
            {
                Console.WriteLine("Transaction does not contain our ScriptPubKey!");
                return(false);
            }

            Console.WriteLine("-----------------------------");



            //calculate change amount (not actually used, TransactionBuilder will handle for us):
            var txInAmount   = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            var changeAmount = txInAmount - contracteePaymentAmount - minerFee;


            #region Console Output (Payment Details)

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("------ Payment Details ------");
            Console.WriteLine();

            Console.WriteLine("Total available: " + txInAmount.ToString() + " btc");
            Console.WriteLine();
            Console.WriteLine("Total payments: " + contracteePaymentAmount.ToString() + " btc");
            Console.WriteLine();
            Console.WriteLine("Total fees: " + minerFee.ToString() + " btc");
            Console.WriteLine();
            Console.WriteLine("Change: " + changeAmount.ToString() + " btc");
            Console.WriteLine();


            Console.WriteLine("-----------------------------");

            Console.WriteLine("");
            Console.WriteLine("Press any key to create transaction...");
            Console.ReadLine();

            #endregion



            try
            {
                //Now we can build a transaction where we send a timelock payment to the contractor
                var txBuilder = new TransactionBuilder();
                var tx        = txBuilder
                                .AddCoins(receivedCoins)
                                .AddKeys(contractorSecret.PrivateKey)
                                .Send(contracteeAddress.ScriptPubKey, contracteePaymentAmount)
                                .SendFees(minerFee)
                                .SetChange(contractorSecret.GetAddress())
                                //.SetLockTime(lockTime)
                                .BuildTransaction(true);

                tx.LockTime = 500123;

                if (txBuilder.Verify(tx))
                {
                    Console.WriteLine(tx.ToString());

                    Console.WriteLine("Timelock contract created, signed and verified!");

                    Console.WriteLine("");
                    Console.WriteLine("Press any key to broadcast...");
                    Console.ReadLine();

                    //Console.WriteLine();
                    //Console.WriteLine(tx.ToString()); //<-- Print out entire transaction as JSON

                    #region Broadcast transaction using NBitcoin with node connection

                    /*
                     * //Use Bitnodes to find a node to connect to: https://bitnodes.earn.com/  |  https://bitnodes.earn.com/nodes/
                     * //For Testnet you may have to find a faucet provider that also provides node information.
                     *
                     *
                     * var node = NBitcoin.Protocol.Node.Connect(_network, "52.10.6.141:18333"); //<-- ReadMe has Terminal commands for looking up available Testnet Nodes. All Testnodes use :18333
                     * node.VersionHandshake();
                     *
                     * // var payload = NBitcoin.Protocol.Payload(tx);
                     *
                     * //inform the server
                     * node.SendMessage(new InvPayload(tx));
                     * Thread.Sleep(1000);
                     *
                     * //send the transaction
                     * node.SendMessage(new TxPayload(tx));
                     * Thread.Sleep(5000);
                     *
                     * node.Disconnect();
                     *
                     * Console.WriteLine("Transaction ID: " + tx.GetHash().ToString());
                     * Console.WriteLine();
                     *
                     */

                    #endregion

                    #region Broadcast transaction using QbitServerClient


                    //Broadcast using QBit server:
                    BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;


                    Console.WriteLine("Transaction ID: " + tx.GetHash().ToString());
                    Console.WriteLine();

                    if (broadcastResponse.Success)
                    {
                        Console.WriteLine("Broadcast succeeded!");
                    }
                    else
                    {
                        Console.WriteLine("Broadcast Error!");
                        Console.WriteLine();
                        Console.WriteLine(broadcastResponse.Error.Reason);
                    }



                    #endregion
                }
                else
                {
                    Console.WriteLine("Timelock contract has some issues.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }



            Console.WriteLine();
            return(true);
        }
예제 #19
0
        static void Main()
        {
            RandomUtils.Random = new UnsecureRandom();

            //====================================================================================
            //Chapter7. Spend your coin


            //====================================================================================
            //Section1. Review and pre stage for spend you coin


            //            So now that you know what a bitcoin address, a ScriptPubKey, a private key and a miner are, you will make your first transaction by hand.

            //As you proceed through this lesson, you will add codes line by line as it is presented to build a method that will leave feedback for the book in a Twitter style message.

            //Let’s start by looking at the transaction that contains the TxOut that you want to spend as we did previously:

            //Create a new Console Project(>.net45) and install QBitNinja.Client NuGet.

            //Have you already generated and noted down a private key yourself? Have you already get the corresponding bitcoin address and sent some funds there? If not, don't worry. I'm quickly going to reiterate how you can do it:


            //Set the network type to the MainNet.
            var network = Network.Main;
            //Generate a random private key.
            var privateKeyForReviewExample = new Key();
            //Generate a Bitcoin secret from a private key with supplying a network identifier, which is nothing but a private key represented in Base58Check, to be used in UI layer like a wallet software.
            var bitcoinSecretFromPKFRE = privateKeyForReviewExample.GetWif(network);
            //Get a Bitcoin address from the Bitcoin secret, which is a representation of the recipient in a human-readable format. A representation of the recipient in a Blockchain-readable format is a ScriptPubKey in a TxOut of a transaction.
            var bitcoinAddressFromBS = bitcoinSecretFromPKFRE.GetAddress();

            Console.WriteLine($"bitcoinSecretFromPKFRE: {bitcoinSecretFromPKFRE}");
            //Output:
            //L2Bm76rotkP6UtYv6cKHv9ptPKQzSqVQTNLkkeAzRCnvxm864ExR
            Console.WriteLine($"bitcoinAddressFromBS: {bitcoinAddressFromBS}");
            //Output:
            //18xuBMyVPA9ovVj3hjW5k9xLY9dBroBZij



            //Note the bitcoinPrivateKey and the address. And send some coins there and note the transaction id(you can find it, probably, in your wallet software or with a blockexplorer like blockchain.info).



            //And import your private key:

            //Pass a value represented in Base58 and a network type into BitcoinSecret constructor arguments, to generate a private key which will be imported into a Wallet software.
            var bitcoinPrivateKey    = new BitcoinSecret("cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x");
            var networkForEx2        = bitcoinPrivateKey.Network;
            var bitcoinAddressForEx2 = bitcoinPrivateKey.GetAddress();

            Console.WriteLine(bitcoinPrivateKey);
            //Output:
            //cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x
            Console.WriteLine(networkForEx2);
            //Output:
            //TestNet
            Console.WriteLine(bitcoinAddressForEx2);
            //Output:
            //mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv


            //Get the transaciton informations by using the QBitNinja.
            var client = new QBitNinjaClient(networkForEx2);
            //Parse the string represented in hex to the string represented in uint256.
            var uint256ForTransactionId = uint256.Parse("e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3");

            Console.WriteLine($"uint256ForTransactionId: {uint256ForTransactionId}");
            //Output:
            //e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
            var transactionResponse = client.GetTransaction(uint256ForTransactionId).Result;

            //Put the uint256ForTransactionId into GetTransaction() method as a transactionID.
            Console.WriteLine($"client.GetTransaction(uint256ForTransactionId): { client.GetTransaction(uint256ForTransactionId)}");
            //Output:
            //System.Threading.Tasks.Task`1[QBitNinja.Client.Models.GetTransactionResponse]

            Console.WriteLine($"client.GetTransaction(uint256ForTransactionId).Result: {client.GetTransaction(uint256ForTransactionId).Result}");
            //Output:
            //QBitNinja.Client.Models.GetTransactionResponse

            Console.WriteLine(transactionResponse.TransactionId);
            //Output:
            //e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
            Console.WriteLine(transactionResponse.Block.Confirmations);
            //Output:
            //384336



            //Now we have every bit of information we need to create our transactions.The main questions are: from where, to where and how much?



            //=========================================================================================
            //Section1. From where?


            //In our case, we want to spend the second outpoint. Here's how we have figured this out:
            //Recall that outpoint is composed of a TransactionId and an index of TxOut in the previous transaction.
            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}th output", outPointToSpend.N + 1);

            //For the payment, you will need to reference this outpoint in the TxIn in the current transaciton. You create a transaciton as follows.
            var transaction = new Transaction();

            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });



            //=======================================================================================
            //Section2. To where?


            //Do you remember the main questions? From where, to where and how much?
            //Constructing the TxIn and adding it to the transaction is the answer to the "from where" question in terms of the coin.
            //Constructing the TxOut and adding it to the transaction is the answer to the remaining ones.

            //The donation address of this book is:
            //1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB

            //This money goes into my "Coffee and Sushi Wallet" that will keep me fed and compliant while writing the rest of the book.
            //If you succeed in completing this challenge, you will be able to find your contribution amongst the Hall of the Makers on http://n.bitcoin.ninja/ (ordered by generosity).

            //This is for a mainnet.
            // var hallOfTheMakersAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");

            //If you are working on the testnet, send the testnet coins to any testnet address.
            //This is for a testnet.
            var hallOfTheMakersAddress = new BitcoinPubKeyAddress("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB");



            //==========================================================================================
            //Section3. How much?


            //If you want to send 0.5 BTC from a transaction input with 1 BTC you actually have to spend it all! And you will get the changes back to your bitcoin address.
            //As the diagram shows below, your transaction output specifies 0.5 BTC to Hall of The Makers and 0.4999 back to you.
            //What happens to the remaining 0.0001 BTC? This is the miner fee in order to incentivize them to add this transaction into their next block.

            //By this codes, we're going to generate TxOuts with hardcoded amount of coins
            //Generate a TxOut for hallOfTheMakers.
            //TxOut hallOfTheMakersTxOut = new TxOut()
            //{
            //    //Set 0.5 bitcoins to be sent.
            //    Value = new Money((decimal)0.5, MoneyUnit.BTC),
            //    //Set a ScriptPubKey for the recipient.
            //    ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            //};

            ////Generate a TxOut for changeBack(1-0.5-fee).
            //TxOut changeBackTxOut = new TxOut()
            //{
            //    Value = new Money((decimal)0.4999, MoneyUnit.BTC),
            //    ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            //};

            //transaction.Outputs.Add(hallOfTheMakersTxOut);
            //transaction.Outputs.Add(changeBackTxOut);

            //Console.WriteLine($"hallOfTheMakersTxOut: {hallOfTheMakersTxOut}");
            //Console.WriteLine($"changeBackTxOut: {changeBackTxOut}");



            //We can do some fine tuning here.
            //You can check the address I am working with in this chapter's examples on a blockexplorer.
            //I am working on the testnet:
            //http://tbtc.blockr.io/address/info/mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv

            //By this codes, we're going to generate TxOuts by calculating coins not with hardcoded amounts of ones.

            //First, set the amount of coin to be sent.
            var hallOfTheMakersAmount = new Money((decimal)0.5, MoneyUnit.BTC);

            //Secend, set the amount of a transaction fee which will be sent to the miner who created the block including a transaction I'm writing.
            //At the time of writing, the mining fee is 0.05usd, depending on the market price and on the currently advised mining fee.
            //You may consider to increase or decrease it.
            var minerFee = new Money((decimal)0.0001, MoneyUnit.BTC);

            //How much you want to spend FROM
            //Get the entire coins that are sent from a specific TxOut(in this case, second one since its index is 1) of another previous transaction.
            var   txInAmount       = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;



            //Let's add our calculated values to our TxOuts:
            TxOut hallOfTheMakersTxOut = new TxOut()
            {
                Value        = hallOfTheMakersAmount,
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            TxOut changeBackTxOut = new TxOut()
            {
                Value        = changeBackAmount,
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            //And add them to our transaction.
            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);

            Console.WriteLine($"hallOfTheMakersTxOut: {hallOfTheMakersTxOut}");
            Console.WriteLine($"changeBackTxOut: {changeBackTxOut}");



            //====================================================================================
            //Section4. Message on The Blockchain.


            //Now add your feedback!This must be less than 40 bytes, or it will crash the application.
            //TThis feedback, along with your transaction, will appear after your transaction is confirmed in the Hall of The Makers.

            var message = "nopara73 loves NBitcoin!";
            var bytes   = Encoding.UTF8.GetBytes(message);

            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });


            //To sum up take a look at my whole transaction before we sign it:
            Console.WriteLine(transaction);

            //I have 3 TxOut, 2 with value, 1 without value which contains just a message. You can notice the differences between the scriptPubKeys of the "normal" TxOuts and the scriptPubKey of the TxOut with the message:



            //Take a closer look at TxIn. We have prev_out and scriptSig there.

            //Exercise: Try to figure out what scriptSig will be and how to get it in our code before you read further!
            //Let's check out the hash of prev_out in a blockexplorer:
            //http://tbtc.blockr.io/api/v1/tx/info/e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3



            //In prev_out, n is 1.Since we are indexing from 0, this means I want to spend the second output of the transaction.
            //In the blockexplorer we can see the corresponding address is:
            //mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv
            //and I can get and set the scriptSig from the address via ScriptPubKey like this:

            var bitcoinAddressForScriptSig = BitcoinAddress.Create("mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv");

            transaction.Inputs[0].ScriptSig = bitcoinAddressForScriptSig.ScriptPubKey;



            //====================================================================================
            //Section5. Sign your transaction



            //Now that we have created the transaction, we must sign it. In other words, you will have to prove that you own the TxOut located in another previous transaction, that you referenced in the input.
            //Signing can be complicated, but we’ll make it simple.
            //First let's revisit the scriptSig of input and see how we can get it from code. Remember, we copy/pasted the address above from a blockexplorer. As we've already seen how to get and set a ScriptSig from above code, similarly, now let's get and set a ScriptPubKey from a private key via a ScriptPubKey by using our QBitNinja transactionResponse:

            transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;

            //Then you need to provide your private key in order to sign the transaciton.
            transaction.Sign(bitcoinPrivateKey, false);



            //====================================================================================
            //Section5. Propagate your transactions


            //Congratulations, you have signed your first transaction!Your transaction is ready to roll!All that is left is to propagate it to the network so the miners can see it.


            //With QBitNinja:
            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! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }


            //With your own Bitcoin Core:

            //Connect to the node.
            //using (var node = Node.ConnectToLocal(network))
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, transaction.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(transaction));
            //    Thread.Sleep(500); //Wait a bit
            //}
        }
예제 #20
0
        /// <summary>
        /// Simple transaction that is locked for x amount of hours before being processed
        /// </summary>
        public static void SendSimpleTransation()
        {
            var privKey = (_contractorHdRoot.Derive(new KeyPath("m/44'/0'/0'/0/0"))).PrivateKey.GetWif(_network);

            var secret        = new BitcoinSecret(privKey.ToString(), _network);
            var key           = secret.PrivateKey;
            var changeAddress = secret.GetAddress().ScriptPubKey;

            string previousOutputTxId = "26b3a2ff92a918ad8c46c2da7dbf4c27c7a12bd24655c9d12f03d0f18edcede6";
            int    unspentOutputIndex = 0; //<-- The index of the unspent output from the previous transaction

            string contracteePublicAddress = "n4bEeKENL9rED2cG31TjSNzPs6T15TCq96";

            int feeAmount     = 2000;
            int paymentAmount = 1002000;
            int changeAmount  = 51993000;

            #region Inputs

            var transaction = new Transaction();
            transaction.Inputs.Add(new TxIn()
            {
                PrevOut   = new OutPoint(new uint256(previousOutputTxId), unspentOutputIndex), //<-- The output we are spending from
                ScriptSig = secret.GetAddress().ScriptPubKey
            });

            #endregion

            #region Outputs

            var   destination = BitcoinAddress.Create(contracteePublicAddress);
            Money fee         = Money.Satoshis(feeAmount);


            transaction.Outputs.Add(new TxOut()
            {
                ScriptPubKey = destination.ScriptPubKey,
                Value        = Money.Satoshis(paymentAmount)
            });


            // The change address for the contractor
            transaction.Outputs.Add(new TxOut()
            {
                ScriptPubKey = changeAddress,
                Value        = Money.Satoshis(changeAmount)
            });

            #endregion

            transaction.Sign(secret, false);


            Console.WriteLine("Transaction signed and broadcast.");


            #region Broadcast transaction using NBitcoin rather than QBitServerClient

            /*
             * //Use Bitnodes to find a node to connect to: https://bitnodes.earn.com/  |  https://bitnodes.earn.com/nodes/
             * //For Testnet you may have to find a faucet provider that also provides node information.
             * var node = NBitcoin.Protocol.Node.Connect(_network, "185.28.76.179:18333");
             * node.VersionHandshake();
             *
             * var payload = NBitcoin.Protocol.Payload()
             * node.SendMessage(new NBitcoin.Protocol.Payload().);
             *
             * Thread.Sleep(4000);
             * node.Disconnect();
             */

            #endregion


            //Broadcast using QBit server:
            var client = new QBitNinjaClient(_network);
            BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;


            Console.WriteLine("Transaction ID: " + transaction.GetHash().ToString());
            Console.WriteLine();

            if (broadcastResponse.Success)
            {
                Console.WriteLine("Broadcast succeeded!");
            }
            else
            {
                Console.WriteLine("Broadcase Error!");
                Console.WriteLine();
                Console.WriteLine(broadcastResponse.Error.Reason);
            }
        }
예제 #21
0
        static void Main()
        {
            var    amount = new Money((decimal)0.0001, MoneyUnit.BTC);
            string s      = SendBitcoin("cSQDiofrk7gz8w1hHArT5ZEDvRAJ5nJDFjxMi7tBuAk3tHwAyAeE", "mizpKSUZzwNG3jaFSbQf1C5k3VB7XvdZaq", amount, Network.TestNet);

            return;


            /*
             #region CiREATE NEW PRIVKEY
             * //var network = Network.TestNet;
             * //Key privateKey = new Key();
             * //var bitcoinPrivateKey = privateKey.GetWif(network);
             #endregion
             *
             */

            #region IMPORT PRIVKEY
            var bitcoinPrivateKey = new BitcoinSecret("cSQDiofrk7gz8w1hHArT5ZEDvRAJ5nJDFjxMi7tBuAk3tHwAyAeE");
            var network           = bitcoinPrivateKey.Network;
            #endregion

            var address = bitcoinPrivateKey.GetAddress();

            Console.WriteLine(bitcoinPrivateKey); // cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x
            Console.WriteLine(address);           // mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv
            Console.WriteLine();



            var client              = new QBitNinjaClient(Network.TestNet);
            var transactionId       = uint256.Parse("a20d27e9341f90fd0c5d6b47e1565c6eeb0b40997213f51ba7d0e747b86922aa");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            Console.WriteLine(transactionResponse.TransactionId); // e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
            Console.WriteLine(transactionResponse.Block.Confirmations);
            Console.WriteLine();

            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 = new Transaction();
            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            // var hallOfTheMakersAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
            //var hallOfTheMakersAddress = new BitcoinPubKeyAddress("2MsNF9f3nsdkEMV6un9u3pMVKcTNJPauqaU");


            //var hallOfTheMakersAddress = new BitcoinScriptAddress("2MtBDuoyhPa8athzErp8nj4NXMKgUQ2qGq8", Network.TestNet);
            var hallOfTheMakersAddress = BitcoinAddress.Create("mizpKSUZzwNG3jaFSbQf1C5k3VB7XvdZaq");

            // How much you want to TO
            var hallOfTheMakersAmount = new Money((decimal)0.004, MoneyUnit.BTC);

            /* At the time of writing the mining fee is 0.05usd
             * Depending on the market price and
             * On the currently advised mining fee,
             * You may consider to increase or decrease it
             */
            var minerFee = new Money((decimal)0.0001, MoneyUnit.BTC);
            // How much you want to spend FROM
            var   txInAmount       = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;

            Money balace = GetBalance(bitcoinPrivateKey.GetAddress());
            List <BalanceOperation> list = GetPending(bitcoinPrivateKey.GetAddress());
            TxOut hallOfTheMakersTxOut   = new TxOut()
            {
                Value        = hallOfTheMakersAmount,
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            TxOut changeBackTxOut = new TxOut()
            {
                Value        = changeBackAmount,
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);


            var message = "nopara73 loves NBitcoin!";
            var bytes   = Encoding.UTF8.GetBytes(message);
            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            //Console.WriteLine(transaction);

            //var address = new BitcoinPubKeyAddress("mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv");
            //transaction.Inputs[0].ScriptSig = address.ScriptPubKey;

            // It is also OK:
            transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;
            transaction.Sign(bitcoinPrivateKey, false);

            BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine(string.Format("ErrorCode: {0}", broadcastResponse.Error.ErrorCode));
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }

            //using (var node = Node.ConnectToLocal(network)) //Connect to the node
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, transaction.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(transaction));
            //    Thread.Sleep(500); //Wait a bit
            //}


            Console.ReadLine();

            Console.ReadLine();
        }
예제 #22
0
 /// <summary>
 ///  Broadcast a message
 /// </summary>
 /// <returns> BroadcastResponse object </returns>
 /// <param name="request"> BroadcastRequest object</param>
 /// <param name='jsonRpcCallId'>
 /// The json rpc call identifier. This is a string generated by the client, which can be used to correlate the response to the request. Max length is 256 characters. A JSON-RPC id must be generated on a per call invocation basis. The Rogerthat platform uses the id of the call to store the call result for a certain amount of time so that if something fails during the communication, the same call (having the same JSON-RPC id) can be resent to the Rogerthat service, allowing to fetch the result, without actually executing the call again. This avoids annoying problems such as duplicate delivery of messages.
 /// 
 /// You should use a different JSON-RPC id for every call you make.
 /// 
 /// In case of an intermittent failure such as a network connectivity problem, you can retry the same call using the same JSON-RPC id, without running the risk of duplicate execution of your call (e.g. duplicate message delivery).
 /// </param>
 public BroadcastResponse Broadcast(BroadcastRequest request, string jsonRpcCallId)
 {
     BroadcastResponse result = new BroadcastResponse();
     WireRequest(0, jsonRpcCallId, "messaging.broadcast", (writer) =>
     {
         request.Write(writer, false);
     }, (reader) =>
     {
         result.Read(reader);
     }
     );
     return result;
 }
예제 #23
0
        static void Main(string[] args)
        {
            //var network = Network.TestNet;
            //var privateKey = new Key();
            //var bitcoinPrivateKey = privateKey.GetWif(network);
            //var address = bitcoinPrivateKey.GetAddress();
            //Console.WriteLine(bitcoinPrivateKey);
            //Console.WriteLine(address);



            var bitcoinPrivateKey = new BitcoinSecret("cN5YQMWV8y19ntovbsZSaeBxXaVPaK4n7vapp4V56CKx5LhrK2RS");
            //var bitcoinPrivateKey = new BitcoinSecret("cNtGg1k1PoyoMnZwBvqkWHFKT3R2nWhMnW5Mw1gULuqS2iURxh8E"); // Testnet
            //var bitcoinPrivateKey = new BitcoinSecret("KwJaEZnTZPZ1wSsFdzMrcCvfCh5bp6CyqJrep4ERT84WJ5pAvyTE"); // Mainnet
            var network = bitcoinPrivateKey.Network;
            var address = bitcoinPrivateKey.GetAddress();

            var client = new QBitNinjaClient(network);
            //var transactionId = uint256.Parse("0acb6e97b228b838049ffbd528571c5e3edd003f0ca8ef61940166dc3081b78a");
            var transactionId       = uint256.Parse("481e4ba7cc989970052b669693a1b74bc75d7910a3279a09335c6052bc18bcbb");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            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
            });


            var hallOfTheMakersAddress = BitcoinAddress.Create("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB", network);

            var hallOfTheMakersAmount = new Money(0.0004m, MoneyUnit.BTC);
            var minerFee = new Money(0.00007m, MoneyUnit.BTC);

            var   txInAmount           = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            var   changeAmount         = txInAmount - hallOfTheMakersAmount - minerFee;
            TxOut hallOfTheMakersTxOut = new TxOut()
            {
                Value        = hallOfTheMakersAmount,
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            TxOut changeTxOut = new TxOut()
            {
                Value        = changeAmount,
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeTxOut);

            var message = "Long live test";
            var bytes   = Encoding.UTF8.GetBytes(message);

            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            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! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }
        }
예제 #24
0
        public void send_btc(BitcoinSecret sender, BitcoinAddress receiver, decimal amount, decimal fee)
        {
            var network = sender.Network;
            var address = sender.GetAddress();

            Console.WriteLine(sender);                                                                                 // cN5YQMWV8y19ntovbsZSaeBxXaVPaK4n7vapp4V56CKx5LhrK2RS
            Console.WriteLine(address);                                                                                // mkZzCmjAarnB31n5Ke6EZPbH64Cxexp3Jp
            var client              = new QBitNinjaClient(network);
            var transactionId       = get_transaction_id(sender.PubKeyHash.GetAddress(BtcNetwork).ToString(), amount); // uint256.Parse("18ea7047ac70bbc16f53587e4fc28f7f9a6bb9117c0a810e1e65e424852b40ca");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            Console.WriteLine(transactionResponse.TransactionId);       // 0acb6e97b228b838049ffbd528571c5e3edd003f0ca8ef61940166dc3081b78a
            Console.WriteLine(transactionResponse.Block.Confirmations); // 91
            var      receivedCoins   = transactionResponse.ReceivedCoins;
            OutPoint outPointToSpend = null;

            foreach (var coin in receivedCoins)
            {
                if (coin.TxOut.ScriptPubKey == sender.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 = new NBitcoin.Transaction();

            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            // How much you want to spend
            var hallOfTheMakersAmount = new Money(amount, MoneyUnit.BTC);

            // How much miner fee you want to pay

            /* Depending on the market price and
             * the currently advised mining fee,
             * you may consider to increase or decrease it.
             */
            var minerFee = new Money(fee, MoneyUnit.BTC);

            // How much you want to get back as change
            var txInAmount   = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            var changeAmount = txInAmount - hallOfTheMakersAmount - minerFee;

            TxOut hallOfTheMakersTxOut = new TxOut()
            {
                Value        = hallOfTheMakersAmount,
                ScriptPubKey = receiver.ScriptPubKey
            };

            TxOut changeTxOut = new TxOut()
            {
                Value        = changeAmount,
                ScriptPubKey = sender.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeTxOut);

            var message = "Long live NBitcoin and its makers!";
            var bytes   = Encoding.UTF8.GetBytes(message);

            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });
            transaction.Inputs[0].ScriptSig = sender.ScriptPubKey;

            transaction.Sign(sender, false);

            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! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }
        }
예제 #25
0
        private static void Blockchain()
        {
            var bitcoinPrivateKeySecret = new BitcoinSecret("cVX7SpYc8yjNW8WzPpiGTqyWD4eM4BBnfqEm9nwGqJb2QiX9hhdf");
            var network = bitcoinPrivateKeySecret.Network;
            var address = bitcoinPrivateKeySecret.GetAddress();

            Console.WriteLine(bitcoinPrivateKeySecret); // cVX7SpYc8yjNW8WzPpiGTqyWD4eM4BBnfqEm9nwGqJb2QiX9hhdf - this is my private testnet
            Console.WriteLine(address);
            // mtjeFt6dMKqvQmYKcBAkSX9AmX8qdynVKN - THIS is my first public bitcoin testnet address!!!!!!!
            Console.WriteLine(network);

            //tx IDS: 7a73b2fa89315be9a1292bf817c5e97296cdd14019c112ebbdf2cbfeecc60e7d
            // 9ed5bc5b2b8c81bcf6585377fb20b4b5b82eb413981d3e01145c7b1c55c3179c
            // a034c8d913960e1135175f915ad1bb32f2a13270fd73ece1c6d717f2f3d1c2b4
            // e6beb1f58a14d2fc2dc041329cd09cadd86e364dbc46ebd950228a0740c00b9c

            // transaction inspection:
            // for test-net http://tapi.qbit.ninja/transactions/9ed5bc5b2b8c81bcf6585377fb20b4b5b82eb413981d3e01145c7b1c55c3179c
            // or for main-net http://api.qbit.ninja/transactions/....

            var client        = new QBitNinjaClient(network);
            var transactionId = uint256.Parse("e6beb1f58a14d2fc2dc041329cd09cadd86e364dbc46ebd950228a0740c00b9c"); // see this trans above!
                                                                                                                   // from this string we get all transaction info making a web request!
            var transactionResponse = client.GetTransaction(transactionId).Result;

            var      receivedCoins   = transactionResponse.ReceivedCoins;
            OutPoint outPointToSpend = null;

            foreach (var coin in receivedCoins)
            {
                if (coin.TxOut.ScriptPubKey == bitcoinPrivateKeySecret.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);

            Console.WriteLine(transactionResponse.TransactionId);
            // 9ed5bc5b2b8c81bcf6585377fb20b4b5b82eb413981d3e01145c7b1c55c3179c
            Console.WriteLine(transactionResponse.Block != null
          ? transactionResponse.Block.Confirmations.ToString()
          : "null block");

            var transaction = new Transaction();

            TxIn txIn = new TxIn
            {
                PrevOut = outPointToSpend
            };

            transaction.Inputs.Add(txIn);

            //blockexplorer of addresses or transactions/blocks
            // https://testnet.manu.backend.hamburg/faucet - load test bitcoins into my account - to show this
            // https://testnet.blockexplorer.com/address/mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB
            // https://live.blockcypher.com/btc-testnet/address/mtjeFt6dMKqvQmYKcBAkSX9AmX8qdynVKN/ -  to present this!
            var hallOfTheMakersAddress = BitcoinAddress.Create("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB");

            TxOut hallOfTheMakersTxOut = new TxOut
            {
                Value        = new Money(7, MoneyUnit.Satoshi),
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };
            var   minerFee        = new Money(1, MoneyUnit.Satoshi); // accepts 500! not 100! show example of rejected out-funds!
            TxOut changeBackTxOut = new TxOut
            {
                Value        = (Money)receivedCoins[(int)outPointToSpend.N].Amount - hallOfTheMakersTxOut.Value - minerFee,
                ScriptPubKey = bitcoinPrivateKeySecret.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);

            transaction.Outputs.Add(new TxOut
            {
                Value        = Money.Zero,
                ScriptPubKey =
                    TxNullDataTemplate.Instance.GenerateScriptPubKey(Encoding.UTF8.GetBytes("danson loves NBitcoin!"))
            });

            transaction.Inputs[0].ScriptSig = bitcoinPrivateKeySecret.ScriptPubKey;
            //transaction.Sign(bitcoinPrivateKey, false);
            transaction.Sign(bitcoinPrivateKeySecret, false); // Byzantine generals problem! to show/explain!

            //return;

            // qbit ninja client works
            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! You can check out the hash of the transaction in any block explorer:");
                Console.WriteLine(transaction.GetHash());
                // my first successful transactions on testnet!
                // d9d7e05bf7a1d66bc0324824bf898d2fdd6771b2fc676eaa98efa04bd94312aa
                // 71d6f6193fc0d0959f47e7d05cc2772ad0493298120d0d7d68000a0b231665eb
                // 773d6ca5b18b875602f0058435422ed16a150c05fba8d086a599a361227ad047
                // https://live.blockcypher.com/btc-testnet/tx/d9d7e05bf7a1d66bc0324824bf898d2fdd6771b2fc676eaa98efa04bd94312aa/
                // https://live.blockcypher.com/btc-testnet/address/mtjeFt6dMKqvQmYKcBAkSX9AmX8qdynVKN/
            }

            // much slower version - direct library
            //using (var node = Node.Connect(network)) //Connect to the node
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, transaction.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(transaction));
            //    Thread.Sleep(500); //Wait a bit
            //}
        }
예제 #26
0
        public static void SpendingYourCoins()
        {
            var privateKey        = new Key();
            var bitcoinPrivateKey = privateKey.GetWif(NETWORK);
            var address           = bitcoinPrivateKey.GetAddress();

            Console.WriteLine(bitcoinPrivateKey);
            Console.WriteLine(address);
            Console.WriteLine();

            var client              = new QBitNinjaClient(NETWORK);
            var transactionId       = uint256.Parse("cfb97ef3257af7251cd5fe41d264e732bf1299630943fcf904fc43d9c7c5b413");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            Console.WriteLine(transactionResponse.TransactionId);
            //Console.WriteLine(transactionResponse.Block.Confirmations);

            var      receivedCoins   = transactionResponse.ReceivedCoins;
            OutPoint outPointToSpend = receivedCoins.Last(c => c.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey).Outpoint;

            Console.WriteLine(outPointToSpend == null ? "TxOut doesn't contain our ScriptPubKey." : "We want to spend " + (outPointToSpend.N + 1).ToString() + ". outpoint:");

            var transaction = new Transaction();

            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });
            // You need to reference the outpoint to spend the coins

            var hallOfTheMakersAddress = BitcoinAddress.Create("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB", Network.TestNet);
            // book challenge address
            // 1 bitcoin = 1000000 bits
            // 1 bit = 100 stoshis

            // An unspent output holds 0.001 BTC, so to donate 0.0004 BTC you need to send all of it.
            // 0.0004 BTC goes to Hall of the Makers, 0.00053 BTC goes to you, and 0.00007 BTC goes to the miner.
            // This fee incentivizes the miners to add this transaction to their next block.
            // If you set the miner fee to zero, your transaction might never be confirmed.

            // Add a message (must be <= 80 bytes)
            var message = "Long live NBitcoin and its makers!";
            var bytes   = Encoding.UTF8.GetBytes(message);

            transaction.Outputs.Add(
                new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            }
                );

            // Signing
            transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;
            transaction.Sign(bitcoinPrivateKey, false);

            //Sending it with QBitNinja
            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! You can check out the hash of the transaction in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }
        }
예제 #27
0
        public bool gastar(string txIdOrigem, string enderecoDestino)
        {
            // Private key da transação "Enviando pra mim mesmo1" que gastarei: mthg7QduM2ba3AJ5UwvQwvkuJDjLJsu9Rt
            string chavePrivada      = "cTQA9XcNUcS7CVtvAvz6BipKn5xzWTn3ppFTGCkEwe8QS9dVZPDw";
            var    bitcoinPrivateKey = new BitcoinSecret(chavePrivada);
            var    rede    = bitcoinPrivateKey.Network;
            var    address = bitcoinPrivateKey.GetAddress();

            Console.WriteLine("Endereço de origem dos fundos: " + address);

            //Consulta transação que gastarei (Um output de troco e um "Enviando pra mim mesmo1" que gastarei
            var client        = new QBitNinjaClient(rede);
            var transactionId = uint256.Parse(txIdOrigem);

            Console.WriteLine("Endereço direto da rede: " + transactionId);
            var transactionResponse = client.GetTransaction(transactionId).Result; //?



            //Verifica outpoints da transação que gastarei
            var      receivedCoins   = transactionResponse.ReceivedCoins;
            OutPoint outPointToSpend = null;

            foreach (var coin in receivedCoins)
            {
                Console.WriteLine(coin.TxOut.ScriptPubKey);
                Console.WriteLine(bitcoinPrivateKey.ScriptPubKey);
                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);

            //Criando transação e adicionando o output que quero gastar no input da transação
            transacao = Transaction.Create(rede);
            transacao.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            //Destinação
            var destino = BitcoinAddress.Create(enderecoDestino, rede);


            //Criação do Output
            TxOut txOut = new TxOut()
            {
                Value        = new Money(0.0004m, MoneyUnit.BTC),
                ScriptPubKey = destino.ScriptPubKey
            };

            TxOut trocoTxOut = new TxOut()
            {
                Value        = new Money(0.00053m, MoneyUnit.BTC),
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            transacao.Outputs.Add(txOut);
            transacao.Outputs.Add(trocoTxOut);

            //Mensagem na transação
            var mensagem = "Olá Mundo!";
            var bytes    = Encoding.UTF8.GetBytes(mensagem);

            transacao.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            Console.WriteLine("\n" + transacao);

            //Assinando a transação

            //Pegando pubkey script do endereço de origem
            transacao.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;

            //assinando com a private key referente ao pubkey script da origem
            transacao.Sign(bitcoinPrivateKey, receivedCoins.ToArray());

            Console.WriteLine("\n" + transacao);


            //Propagar a transação...

            BroadcastResponse broadcastResponse = client.Broadcast(transacao).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 transaciton in any block explorer:");
                Console.WriteLine(transacao.GetHash());
                return(true);
            }

            return(false);
        }
예제 #28
0
        private static void Send(string walletPassword, string walletName, string walletAddress, string outPoint)
        {
            string walletFilePath = @"Wallets\";

            NBitcoin.BitcoinExtKey privateKey = null;
            try
            {
                Safe loadedSafe = Safe.Load(walletPassword, walletFilePath + walletName + ".json");
                for (int i = 0; i < 10; i++)
                {
                    if (loadedSafe.GetAddress(i).ToString() == walletAddress)
                    {
                        Write("Enter private key: ");
                        privateKey = new BitcoinExtKey(ReadLine());
                        if (!privateKey.Equals(loadedSafe.FindPrivateKey(loadedSafe.GetAddress(i))))
                        {
                            WriteLine("ERROR: Wrong private key!");
                            return;
                        }
                        break;
                    }
                }
            }
            catch (Exception)
            {
                WriteLine("ERROR: Wrong wallet or password!");
            }

            QBitNinjaClient client          = new QBitNinjaClient(Network.TestNet);
            var             balance         = client.GetBalance(BitcoinAddress.Create(walletAddress), false).Result;
            OutPoint        outPointToSpend = null;

            foreach (var entry in balance.Operations)
            {
                foreach (var coin in entry.ReceivedCoins)
                {
                    if (coin.Outpoint.ToString().Substring(0, coin.Outpoint.ToString().Length - 2) == outPoint)
                    {
                        outPointToSpend = coin.Outpoint;
                        break;
                    }
                }
            }

            var transaction = new Transaction();

            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            Write("Enter address to send to: ");
            string addressToSendTo        = ReadLine();
            var    hallOfTheMakersAddress = BitcoinAddress.Create(addressToSendTo);

            Write("Enter amount to send: ");
            decimal amountToSend         = decimal.Parse(ReadLine());
            TxOut   hallOfTheMakersTxOut = new TxOut()
            {
                Value        = new Money(amountToSend, MoneyUnit.BTC),
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            Write("Enter amount to get back: ");
            decimal amountToGetBack = decimal.Parse(ReadLine());
            TxOut   changeBackTxOut = new TxOut()
            {
                Value        = new Money(amountToGetBack, MoneyUnit.BTC),
                ScriptPubKey = privateKey.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);

            Write("Enter message: ");
            var message = ReadLine();
            var bytes   = Encoding.UTF8.GetBytes(message);

            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            transaction.Inputs[0].ScriptSig = privateKey.ScriptPubKey;
            transaction.Sign(privateKey, false);
            BroadcastResponse broadcast = client.Broadcast(transaction).Result;

            WriteLine(transaction);

            if (broadcast.Success)
            {
                WriteLine("TRANSACTION SUCCESSFULLY SENT!");
            }
            else
            {
                WriteLine("INTERNAL ERROR: Something went wrong!");
            }
        }
예제 #29
0
        static void Main()
        {
            #region CREATE NEW PRIVKEY
            //var network = Network.TestNet;
            //Key privateKey = new Key();
            //var bitcoinPrivateKey = privateKey.GetWif(network);
            #endregion

            #region IMPORT PRIVKEY
            var bitcoinPrivateKey = new BitcoinSecret("cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x");
            var network           = bitcoinPrivateKey.Network;
            #endregion

            var address = bitcoinPrivateKey.GetAddress();

            Console.WriteLine(bitcoinPrivateKey); // cSZjE4aJNPpBtU6xvJ6J4iBzDgTmzTjbq8w2kqnYvAprBCyTsG4x
            Console.WriteLine(address);           // mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv
            Console.WriteLine();

            var client              = new QBitNinjaClient(network);
            var transactionId       = uint256.Parse("e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3");
            var transactionResponse = client.GetTransaction(transactionId).Result;

            Console.WriteLine(transactionResponse.TransactionId); // e44587cf08b4f03b0e8b4ae7562217796ec47b8c91666681d71329b764add2e3
            Console.WriteLine(transactionResponse.Block.Confirmations);
            Console.WriteLine();

            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 = new Transaction();
            transaction.Inputs.Add(new TxIn()
            {
                PrevOut = outPointToSpend
            });

            // var hallOfTheMakersAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
            var hallOfTheMakersAddress = new BitcoinPubKeyAddress("mzp4No5cmCXjZUpf112B1XWsvWBfws5bbB");

            // How much you want to TO
            var hallOfTheMakersAmount = new Money((decimal)0.5, MoneyUnit.BTC);

            /* At the time of writing the mining fee is 0.05usd
             * Depending on the market price and
             * On the currently advised mining fee,
             * You may consider to increase or decrease it
             */
            var minerFee = new Money((decimal)0.0001, MoneyUnit.BTC);
            // How much you want to spend FROM
            var   txInAmount       = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            Money changeBackAmount = txInAmount - hallOfTheMakersAmount - minerFee;

            TxOut hallOfTheMakersTxOut = new TxOut()
            {
                Value        = hallOfTheMakersAmount,
                ScriptPubKey = hallOfTheMakersAddress.ScriptPubKey
            };

            TxOut changeBackTxOut = new TxOut()
            {
                Value        = changeBackAmount,
                ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
            };

            transaction.Outputs.Add(hallOfTheMakersTxOut);
            transaction.Outputs.Add(changeBackTxOut);

            var message = "nopara73 loves NBitcoin!";
            var bytes   = Encoding.UTF8.GetBytes(message);
            transaction.Outputs.Add(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
            });

            //Console.WriteLine(transaction);

            //var address = new BitcoinPubKeyAddress("mzK6Jy5mer3ABBxfHdcxXEChsn3mkv8qJv");
            //transaction.Inputs[0].ScriptSig = address.ScriptPubKey;

            // It is also OK:
            transaction.Inputs[0].ScriptSig = bitcoinPrivateKey.ScriptPubKey;
            transaction.Sign(bitcoinPrivateKey, false);

            BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine(string.Format("ErrorCode: {0}", broadcastResponse.Error.ErrorCode));
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success! You can check out the hash of the transaciton in any block explorer:");
                Console.WriteLine(transaction.GetHash());
            }

            //using (var node = Node.ConnectToLocal(network)) //Connect to the node
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, transaction.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(transaction));
            //    Thread.Sleep(500); //Wait a bit
            //}


            Console.ReadLine();
        }
예제 #30
0
        static void Main(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 chimaTestDestinationAddress = new BitcoinPubKeyAddress("mxgN2AiqHjKfGvo6Y57fAe4Y754rPdKf4P");

            var ugoCoins = new HashSet <ICoin>();

            foreach (var operation in balance.Operations)
            {
                foreach (var coin in operation.ReceivedCoins)
                {
                    if (coin.TxOut.ScriptPubKey.GetDestinationAddress(network) == address)
                    {
                        ugoCoins.Add(coin);
                    }
                }
            }

            var txBuilder = new TransactionBuilder();
            var trans     = txBuilder
                            .AddCoins(ugoCoins)
                            .AddKeys(bitcoinPrivateKey)
                            .Send(chimaTestDestinationAddress.ScriptPubKey.GetDestination(), "0.10")
                            .SendFees("0.01")
                            .SetChange(bitcoinPrivateKey.GetAddress())
                            .BuildTransaction(true);
            bool isSigned = txBuilder.Verify(trans);

            SmartBitClient smartBitClient = new SmartBitClient(network);

            PushTransaction(trans);

            //HttpResponseMessage response =  httpClient.PostAsync(new SmartBit() { hex = ""}).Result;

            BroadcastResponse broadcast = client.Broadcast(trans).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: " + trans.GetHash());
            }


            Console.ReadKey();
        }
예제 #31
0
        static void GetTransaction(Network network, string btcPrivateKey, string transId, bool spending)
        {
            var client              = new QBitNinjaClient(network);
            var transactionId       = uint256.Parse(transId);
            var transactionResponse = client.GetTransaction(transactionId).Result;
            var privateKey          = new BitcoinSecret(btcPrivateKey);

            Console.WriteLine(transactionResponse.TransactionId);

            if (null != transactionResponse.Block)
            {
                Console.WriteLine("Confirmations: " + transactionResponse.Block.Confirmations);
            }
            else
            {
                Console.WriteLine("Block is not yet set.");
            }

            var message = "Asemco leaves their record on the blockchain.";
            var bytes   = Encoding.UTF8.GetBytes(message);

            //foreach (var output in transactionResponse.Transaction.Outputs)
            //{

            //    Console.WriteLine(output.Value);
            //}

            if (spending)
            {
                var      receivedCoins   = transactionResponse.ReceivedCoins;
                OutPoint outPointToSpend = null;
                foreach (var coin in receivedCoins)
                {
                    if (coin.TxOut.ScriptPubKey == privateKey.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 = new Transaction();
                transaction.Inputs.Add(new TxIn()
                {
                    PrevOut = outPointToSpend
                });

                var receiverAddress = BitcoinAddress.Create("2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF", network);
                var outgoingAmount  = new Money(0.0004m, MoneyUnit.BTC);
                var minerFee        = new Money(0.00007m, MoneyUnit.BTC);

                var txInAmount   = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
                var changeAmount = txInAmount - outgoingAmount - minerFee;

                TxOut testBTCOut = new TxOut()
                {
                    Value        = outgoingAmount,
                    ScriptPubKey = receiverAddress.ScriptPubKey
                };

                TxOut changeBackTxOut = new TxOut()
                {
                    Value        = changeAmount,
                    ScriptPubKey = privateKey.ScriptPubKey
                };

                //var message = "Asemco leaves their record on the blockchain.";
                //var bytes = Encoding.UTF8.GetBytes(message);
                TxOut transMessage = new TxOut()
                {
                    Value        = Money.Zero,
                    ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
                };

                transaction.Outputs.Add(testBTCOut);
                transaction.Outputs.Add(changeBackTxOut);
                transaction.Outputs.Add(transMessage);
                transaction.Inputs[0].ScriptSig = privateKey.ScriptPubKey;
                transaction.Sign(privateKey, false);

                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!  You've hit the blockchain!  The transaction hash is below.");
                    Console.WriteLine(transaction.GetHash());
                }
            }
        }