Esempio n. 1
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Process the bitcoin spend receipt message described by msg. </summary>
        ///
        /// <param name="msg">  The message. This cannot be null. </param>
        ///
        /// <returns>   True if it succeeds, false if it fails. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        bool ProcessBitcoinSpendReceiptMessage(BitcoinSpendReceipt msg)
        {
            WriteLineInColor("Received Bitcoin Spent Receipt", ConsoleColor.Yellow);
            RILogManager.Default?.SendInformation("Received Bitcoin Spent Receipt Message");
            if (msg.success)
            {
                WriteLineInColor("Someone spent " + msg.amount + " of my bitcoins", ConsoleColor.Green);
            }
            else
            {
                WriteLineInColor("Someone tried to spend " + msg.amount + " of my bitcoins", ConsoleColor.Red);
            }

            msg.ID = new Random().Next(1, 1000000);
            using (var _db = new LiteDatabase(connectionString))
            {
                Thread.Sleep(5);
                _db.Shrink();
                var collection = _db.GetCollection <BitcoinSpendReceipt>();
                collection.EnsureIndex(x => x.ID);
                collection.Insert(msg);
            }

            return(true);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <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");
            }
        }