コード例 #1
0
        public UnsignedTransaction SendTransactionToExchage(dynamic transactionDto, string toAddress, string privateKey, string network, string token)
        {
            try
            {
                var      btcnetwork = GetNetwork(network);
                Endpoint endpoint   = Endpoint.BtcTest3;
                if (network.ToUpper() == "MAIN")
                {
                    endpoint = Endpoint.BtcMain;
                }
                Blockcypher          blockCypherLib = new Blockcypher(token, endpoint);
                BitcoinSecret        secret         = new BitcoinSecret(privateKey, btcnetwork);
                NBitcoin.Transaction tx             = NBitcoin.Transaction.Create(btcnetwork);
                TxIn input = new TxIn
                {
                    PrevOut   = new OutPoint(new uint256(transactionDto.TransactionID), transactionDto.Vout),
                    ScriptSig = secret.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey
                };
                tx.Inputs.Add(input);

                TxOut output      = new TxOut();
                Money fee         = Money.Coins(transactionDto.DefaultFees.GetValueOrDefault());
                Money totalAmount = Money.Coins(transactionDto.Amount);
                output.Value = totalAmount - fee;
                BitcoinAddress toaddress = BitcoinAddress.Create(toAddress, btcnetwork);
                output.ScriptPubKey = toaddress.ScriptPubKey;
                tx.Outputs.Add(output);

                var coins = tx.Inputs.Select(txin => new Coin(txin.PrevOut, new TxOut {
                    ScriptPubKey = txin.ScriptSig
                }));
                tx.Sign(secret, coins.ToArray());
                var response = blockCypherLib.PushTransaction(tx.ToHex()).Result;
                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }
コード例 #2
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());
            }
        }
コード例 #3
0
ファイル: LTCLib.cs プロジェクト: Trycoder/DotNet-Wallet
        public dynamic SendToTestNet(dynamic transactionDto, string toAddress, string privateKey, string network, string token)
        {
            try
            {
                var btcnetwork = GetNetwork(network);


                BitcoinSecret        secret = new BitcoinSecret(privateKey, btcnetwork);
                NBitcoin.Transaction tx     = NBitcoin.Transaction.Create(btcnetwork);
                TxIn input = new TxIn
                {
                    PrevOut   = new OutPoint(new uint256(transactionDto.TransactionID), transactionDto.Vout),
                    ScriptSig = secret.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey
                };
                tx.Inputs.Add(input);

                TxOut output      = new TxOut();
                Money fee         = Money.Coins(transactionDto.DefaultFees);
                Money totalAmount = Money.Coins(transactionDto.Amount);
                output.Value = totalAmount - fee;
                BitcoinAddress toaddress = BitcoinAddress.Create(toAddress, btcnetwork);
                output.ScriptPubKey = toaddress.ScriptPubKey;
                tx.Outputs.Add(output);

                var coins = tx.Inputs.Select(txin => new Coin(txin.PrevOut, new TxOut {
                    ScriptPubKey = txin.ScriptSig
                }));
                tx.Sign(secret, coins.ToArray());

                /* Push Data to So Chain*/
                string api            = "https://chain.so/api/v2/send_tx/LTCTEST";
                var    httpWebRequest = (HttpWebRequest)WebRequest.Create(api);
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method      = HttpMethod.Post.Method;
                dynamic reqObj = new ExpandoObject();
                reqObj.tx_hex = tx.ToHex();
                string payload = JsonConvert.SerializeObject(reqObj);

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(payload);
                    var ss = streamWriter.ToString();
                    streamWriter.Flush();
                }
                string responseData = string.Empty;
                var    httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    responseData = streamReader.ReadToEnd();
                }
                dynamic response = new ExpandoObject();
                if (!string.IsNullOrWhiteSpace(responseData))
                {
                    response = JsonConvert.DeserializeObject(responseData);
                }

                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }
コード例 #4
-9
        public static void Pay(BitcoinSecret secret, BitcoinAddress toAddress, Money amount, Transaction fundingTransaction)
        {
            var fee = Money.Coins(0.0001m);

            Transaction payment = new Transaction();
            payment.Inputs.Add(new TxIn()
                {
                    PrevOut = new OutPoint(fundingTransaction.GetHash(), 1)
                });

            payment.Outputs.Add(new TxOut()
                {
                    Value = amount,
                    ScriptPubKey = toAddress.ScriptPubKey
                });

            var output = fundingTransaction.Outputs[0];
            var change = output.Value - amount - fee;
            if (change < 0)
            {
                Console.WriteLine("There is not enough BTC in the funding transaction ({0}) to make this payment ({1})", output.Value, amount);
                Console.WriteLine("No payment being sent");
                return;
            }

            payment.Outputs.Add(new TxOut()
                {
                    Value = output.Value - amount - fee,
                    ScriptPubKey = output.ScriptPubKey
                });

            //Feedback !
            var message = "Thanks ! :)";
            var bytes = Encoding.UTF8.GetBytes(message);
            payment.Outputs.Add(new TxOut()
                {
                    Value = Money.Zero,
                    ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(bytes)
                });

            Console.WriteLine(payment);

            payment.Inputs[0].ScriptSig = fundingTransaction.Outputs[1].ScriptPubKey;
            payment.Sign(secret, false);

            using (var node = Node.Connect(Network.Main))
            {
                Console.WriteLine("Doing version handshake");
                node.VersionHandshake();
                Console.WriteLine("Sending message");
                node.SendMessage(new InvPayload(InventoryType.MSG_TX, payment.GetHash()));
                node.SendMessage(new TxPayload(payment));
                Thread.Sleep(500);
            }
        }