public static BlockchainTransaction ConvertToBlockchainTransaction(this GetTransactionResponse item, bool isMainNet, string address) { var network = isMainNet ? Network.Main : Network.RegTest; return(new BlockchainTransaction { Confirmations = item.Block.Confirmations, Hash = item.TransactionId.ToString(), BlockId = item.Block.BlockId.ToString(), Height = item.Block.Height, ReceivedCoins = item.ReceivedCoins.Select( x => new InputOutput { Address = x.TxOut.ScriptPubKey.GetDestinationAddress(network)?.ToString(), Amount = (x as ColoredCoin)?.Amount.Quantity ?? ((Coin)x).Amount.Satoshi, BcnAssetId = (x as ColoredCoin)?.AssetId.ToString(network) }).Where(x => x.Address == address).ToArray(), SpentCoins = item.SpentCoins.Select( x => new InputOutput { Address = x.TxOut.ScriptPubKey.GetDestinationAddress(network)?.ToString(), Amount = (x as ColoredCoin)?.Amount.Quantity ?? ((Coin)x).Amount.Satoshi, BcnAssetId = (x as ColoredCoin)?.AssetId.ToString(network) }).Where(x => x.Address == address).ToArray() }); }
/// <summary> /// Return Affected Row Or Error If Exist /// </summary> /// <param name="request">Transaction Information</param> /// <returns>Affected Row Or Error If Exist</returns> public static GetTransactionResponse Transaction(GetTransactionResponse request) { GetTransactionResponse response = new GetTransactionResponse(); try { tblTransaction bussines = new tblTransaction() { id = request.Transaction.id, amount = request.Transaction.amount, detail = request.Transaction.detail, idProvide = request.Transaction.idProvide, createDate = DateTime.Now, upDateDate = null, deleteDate = null, state = "Active" }; var result = TransactionData.Update.Transaction(bussines); if (result.Item1.Error) { response.Error.InfoError(result.Item1); } else { response.Message = result.Item2; } } catch (Exception ex) { response.Error.InfoError(ex); } return(response); }
public static void Run(string[] args) { /* * query of transactions * - https://www.blockchain.com/btc/tx/930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72 * - http://api.qbit.ninja/transactions/930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72 * * - https://bitcoinsays.com/930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72 */ // Create a client QBitNinjaClient client = new QBitNinjaClient(Network.Main); // Parse transaction id to NBitcoin.uint256 so the client can eat it uint256 transactionId = uint256.Parse("930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72"); // Query the transaction GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; NBitcoin.Transaction transaction = transactionResponse.Transaction; Console.WriteLine(transactionResponse.TransactionId); // f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94 Console.WriteLine(transaction.GetHash()); // f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94 printAddressesAsAcii(transactionResponse.ReceivedCoins); }
public GetTransactionResponse GetTransaction(GetTransactionRequest getTransactionRequest) { Log(Logger.LogMessageType.Info, "-> -------------------- Comienza la ejecución del método Sales.GetTransaction", Logger.LoggingLevelType.Medium); GetTransactionRequestInternal getTransactionRequestInternal = new GetTransactionRequestInternal() { SessionID = getTransactionRequest.Request.SessionID, DeviceType = getTransactionRequest.Request.DeviceType, ParameterType = (GetTransactionRequestInternalParameterType)getTransactionRequest.Request.ParameterType, ParameterValue = getTransactionRequest.Request.Parameter }; GetTransactionResponseInternal internalResponse = GetTransactionInternal(getTransactionRequestInternal); GetTransactionResponse getTransactionResponse = new GetTransactionResponse(); GetTransactionResponseBody responseBody = new GetTransactionResponseBody() { Amount = internalResponse.Amount, Recipient = internalResponse.Recipient, ResponseCode = internalResponse.ResponseCode, ResponseMessage = internalResponse.ResponseMessage, TransactionDate = internalResponse.TransactionDate, TransactionID = internalResponse.TransactionID, TransactionResult = internalResponse.TransactionResult, TransactionType = internalResponse.TransactionType, Initiator = internalResponse.Initiator, Debtor = internalResponse.Debtor, Creditor = internalResponse.Creditor }; getTransactionResponse.Response = responseBody; Log(Logger.LogMessageType.Info, "-> -------------------- Termina la ejecución del método Sales.GetTransaction", Logger.LoggingLevelType.Medium); return(getTransactionResponse); }
private void UseQbitValues(GetTransactionResponse result) { // transaction is unconfirmed if (result.Block == null) { BlockHeight = "NA"; BlockHash = "NA"; IsBlockPresent = false; } // transaction has at least 1 confirmation else { BlockHeight = result.Block.Height.ToString("N0"); BlockHash = result.Block.BlockId.ToString(); IsBlockPresent = true; } TxHash = result.TransactionId.ToString(); TxAction = _tx.ActionString; ActionAmount = _tx.AbsBalance; ActionAmountCurr = _tx.BalanceCurr; Fee = result.Fees; FeeCurr = Converters.Btc2Currency(Fee); Confirmations = result.Block.Confirmations.ToString("N0"); Date = _tx.DateDisplay; TxStatus = this.DetermineTxStatus(result.Block.Confirmations); LoadingData = false; }
private static void wait_for_transaction_confirmation(uint256 transaction_hash, int nbr_block_confirmations, int sleep_millis) { QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); Console.WriteLine("Waiting for confinrmation ..."); int confirmations = 0; GetTransactionResponse resp = client.GetTransaction(transaction_hash).Result; if (resp.Block == null) { Console.WriteLine("Transaction not confirmed yet.."); } while (confirmations < nbr_block_confirmations) { resp = client.GetTransaction(transaction_hash).Result; if (resp.Block == null) { Console.Write("."); } else if (confirmations != resp.Block.Confirmations) { confirmations = resp.Block.Confirmations; Console.WriteLine("[{0}] New block confirmation! Confirmed now: {1}", DateTime.Now.ToString("H:mm:ss"), confirmations); } Thread.Sleep(sleep_millis); } Console.WriteLine("Done. The transaction has {0} Blocks confirmation(s)!", resp.Block.Confirmations); }
/// <summary> /// Polls confirmations for pending transactions /// </summary> public void PollConfirmations() { // List to temporarily save the transactions whose confirmations have reached the count of 7, these confirmations // are going to be deleted from the _pendingTransactions List List <Tuple <string, int> > confirmedDeposits = new List <Tuple <string, int> >(); for (int i = 0; i < _pendingTransactions.Count; i++) { // Get the number of confirmations of each pending confirmation (deposit) GetTransactionResponse getTransactionResponse = _dogecoinClientService.GetTransaction(_pendingTransactions[i].Item1); // Add new confirmations and raise events AddNewConfirmation(getTransactionResponse, i, confirmedDeposits); } // Remove the confirmed deposits from the list of _pendingTransactions. Do it here as we cannot do that when iterating // the _pensingTransactions list above if (confirmedDeposits.Any()) { foreach (Tuple <string, int> deposit in confirmedDeposits) { _pendingTransactions.Remove(deposit); Log.Debug(string.Format("Verified Deposit removed from list of pending deposits: Transaction ID = {0}", deposit.Item1)); } } }
public static void Run(string[] args) { /* * String hex = "6a4dd7035765277265206e6f20737472616e6765727320746f206c6f76650a596f75206b6e6f77207468652072756c657320616e6420736f20646f20490a412066756c6c20636f6d6d69746d656e74277320776861742049276d207468696e6b696e67206f660a596f7520776f756c646e27742067657420746869732066726f6d20616e79206f74686572206775790a49206a7573742077616e6e612074656c6c20796f7520686f772049276d206665656c696e670a476f747461206d616b6520796f7520756e6465727374616e640a0a43484f5255530a4e6576657220676f6e6e61206769766520796f752075702c0a4e6576657220676f6e6e61206c657420796f7520646f776e0a4e6576657220676f6e6e612072756e2061726f756e6420616e642064657365727420796f750a4e6576657220676f6e6e61206d616b6520796f75206372792c0a4e6576657220676f6e6e612073617920676f6f646279650a4e6576657220676f6e6e612074656c6c2061206c696520616e64206875727420796f750a0a5765277665206b6e6f776e2065616368206f7468657220666f7220736f206c6f6e670a596f75722068656172742773206265656e20616368696e672062757420796f7527726520746f6f2073687920746f207361792069740a496e7369646520776520626f7468206b6e6f7720776861742773206265656e20676f696e67206f6e0a5765206b6e6f77207468652067616d6520616e6420776527726520676f6e6e6120706c61792069740a416e6420696620796f752061736b206d6520686f772049276d206665656c696e670a446f6e27742074656c6c206d6520796f7527726520746f6f20626c696e6420746f20736565202843484f525553290a0a43484f52555343484f5255530a284f6f68206769766520796f75207570290a284f6f68206769766520796f75207570290a284f6f6829206e6576657220676f6e6e6120676976652c206e6576657220676f6e6e6120676976650a286769766520796f75207570290a284f6f6829206e6576657220676f6e6e6120676976652c206e6576657220676f6e6e6120676976650a286769766520796f75207570290a0a5765277665206b6e6f776e2065616368206f7468657220666f7220736f206c6f6e670a596f75722068656172742773206265656e20616368696e672062757420796f7527726520746f6f2073687920746f207361792069740a496e7369646520776520626f7468206b6e6f7720776861742773206265656e20676f696e67206f6e0a5765206b6e6f77207468652067616d6520616e6420776527726520676f6e6e6120706c61792069742028544f2046524f4e54290a0a"; * byte[] ascii = Encoders.Hex.DecodeData(hex); * String str = System.Text.Encoding.Default.GetString(ascii); * * Console.WriteLine(str); */ /* * query of transactions * - https://www.blockchain.com/btc/tx/d29c9c0e8e4d2a9790922af73f0b8d51f0bd4bb19940d9cf910ead8fbe85bc9b * - http://api.qbit.ninja/transactions/d29c9c0e8e4d2a9790922af73f0b8d51f0bd4bb19940d9cf910ead8fbe85bc9b * * - https://bitcoinsays.com/d29c9c0e8e4d2a9790922af73f0b8d51f0bd4bb19940d9cf910ead8fbe85bc9b */ // Create a client QBitNinjaClient client = new QBitNinjaClient(Network.Main); // Parse transaction id to NBitcoin.uint256 so the client can eat it uint256 transactionId = uint256.Parse("d29c9c0e8e4d2a9790922af73f0b8d51f0bd4bb19940d9cf910ead8fbe85bc9b"); // Query the transaction GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; NBitcoin.Transaction transaction = transactionResponse.Transaction; printScriptsAsAcii(transactionResponse.ReceivedCoins); }
/// <summary> /// Return Transaction Information /// </summary> /// <param name="request">Transaction ID</param> /// <returns>Transaction Information</returns> public static GetTransactionResponse GetEmployee(GetTransactionRequest request) { GetTransactionResponse response = new GetTransactionResponse(); response.Error = new Handler.ErrorObject(); response.Transaction = new Transactions(); try { var bussines = TransactionData.Select.GetTransaction(request.TransactionID); if (!bussines.Item1.Error) { response.Transaction = new Transactions() { id = bussines.Item2.id, amount = bussines.Item2.amount, idProvide = bussines.Item2.idProvide, detail = bussines.Item2.detail, createDate = bussines.Item2.createDate, upDateDate = bussines.Item2.upDateDate, deleteDate = bussines.Item2.deleteDate, state = bussines.Item2.state }; } else { response.Error.InfoError(bussines.Item1); } } catch (Exception ex) { response.Error.InfoError(ex); } return(response); }
private bool QbitQueryOK(GetTransactionResponse query) { if (query == null) { return(false); } return(true); }
protected long GetTransactionTime(GetTransactionResponse transaction, string category) { if (string.Compare("send", category, StringComparison.OrdinalIgnoreCase) == 0) { return(transaction.Time); } return(string.Compare("receive", category, StringComparison.OrdinalIgnoreCase) == 0 ? transaction.TimeReceived : 0); }
static void Main(string[] args) { Console.WriteLine("Hello World! " + new Key().GetWif(Network.Main)); // generate a random private key //Key privateKey = new Key(); //From the private key, we use a one-way cryptographic function, to generate a public key. PubKey publicKey = privateKey.PubKey; Console.WriteLine(publicKey); //we can easily get your bitcoin address from your public key // and the network on which this address should be used. Console.WriteLine(publicKey.GetAddress(Network.Main)); Console.WriteLine(publicKey.GetAddress(Network.TestNet)); /* var publicKeyHash = publicKey.Hash; * Console.WriteLine(publicKeyHash); * var mainNetAddress = publicKeyHash.GetAddress(Network.Main); * var testNetAddress = publicKeyHash.GetAddress(Network.TestNet); * Console.WriteLine(mainNetAddress); * Console.WriteLine(testNetAddress); */ var publicKeyHash = new KeyId("14836dbe7f38c5ac3d49e8d790af808a4ee9edcf"); var testNetAddress = publicKeyHash.GetAddress(Network.TestNet); var mainNetAddress = publicKeyHash.GetAddress(Network.Main); Console.WriteLine(mainNetAddress.ScriptPubKey); Console.WriteLine(testNetAddress.ScriptPubKey); var paymentScript = publicKeyHash.ScriptPubKey; var sameMainNetAddress = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine(mainNetAddress == sameMainNetAddress); var samePublicKeyHash = (KeyId)paymentScript.GetDestination(); Console.WriteLine(publicKeyHash == samePublicKeyHash); // True var sameMainNetAddress2 = new BitcoinPubKeyAddress(samePublicKeyHash, Network.Main); Console.WriteLine(mainNetAddress == sameMainNetAddress2); // Key privateKey = new Key(); // generate a random private key // generate our Bitcoin secret(also known as Wallet Import Format or simply WIF) from our private key for the mainnet BitcoinSecret mainNetPrivateKey = privateKey.GetBitcoinSecret(Network.Main); BitcoinSecret testNetPrivateKey = privateKey.GetBitcoinSecret(Network.TestNet); // generate our Bitcoin secret(also known as Wallet Import Format or simply WIF) from our private key for the testnet Console.WriteLine(mainNetPrivateKey); Console.WriteLine(testNetPrivateKey); bool WifIsBitcoinSecret = mainNetPrivateKey == privateKey.GetWif(Network.Main); Console.WriteLine(WifIsBitcoinSecret); // True // Create a client QBitNinjaClient client = new QBitNinjaClient(Network.Main); // Parse transaction id to NBitcoin.uint256 so the client can eat it var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94"); // Query the transaction GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; }
internal async Task <GetTransactionResponse> JsonTransaction(uint256 txId, bool colored) { var client = Configuration.Indexer.CreateIndexerClient(); var tx = await client.GetTransactionAsync(true, colored, txId); if (tx == null || (tx.ColoredTransaction == null && colored) || tx.SpentCoins == null) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, ReasonPhrase = "Transaction not found" }); } var response = new GetTransactionResponse() { TransactionId = tx.TransactionId, Transaction = tx.Transaction, IsCoinbase = tx.Transaction.IsCoinBase, Fees = tx.Fees, Block = FetchBlockInformation(tx.BlockIds), FirstSeen = tx.FirstSeen }; for (int i = 0; i < tx.Transaction.Outputs.Count; i++) { var txout = tx.Transaction.Outputs[i]; ICoin coin = new Coin(new OutPoint(txId, i), txout); if (colored) { var entry = tx.ColoredTransaction.GetColoredEntry((uint)i); if (entry != null) { coin = new ColoredCoin(entry.Asset, (Coin)coin); } } response.ReceivedCoins.Add(coin); } if (!response.IsCoinbase) { for (int i = 0; i < tx.Transaction.Inputs.Count; i++) { ICoin coin = new Coin(tx.SpentCoins[i].OutPoint, tx.SpentCoins[i].TxOut); if (colored) { var entry = tx.ColoredTransaction.Inputs.FirstOrDefault(ii => ii.Index == i); if (entry != null) { coin = new ColoredCoin(entry.Asset, (Coin)coin); } } response.SpentCoins.Add(coin); } } return(response); }
public void TestTransactionInfo() { QBitNinjaClient client = new QBitNinjaClient(Network.Main); var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94"); GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; NBitcoin.Transaction transaction = transactionResponse.Transaction; Console.WriteLine(transactionResponse.TransactionId); Console.WriteLine(transaction.GetHash()); Console.WriteLine(); //Received Coins Console.WriteLine("Outputs:"); var outputs = transaction.Outputs; foreach (TxOut output in outputs) { Money amount = output.Value; Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC)); var paymentScript = output.ScriptPubKey; Console.WriteLine("ScriptPubKey: " + paymentScript); // It's the ScriptPubKey var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine("address: " + address); Console.WriteLine(); } //Spent Coins Console.WriteLine("Inputs:"); Money receivedAmount = Money.Zero; var inputs = transaction.Inputs; foreach (TxIn input in inputs) { OutPoint previousOutpoint = input.PrevOut; Console.WriteLine("Prev Outpoint Hash: " + previousOutpoint.Hash); // hash of prev tx Console.WriteLine("Prev Outpoint Index: " + previousOutpoint.N); // idx of out from prev tx, that has been spent in the current tx Console.WriteLine(); } Console.WriteLine("Amount of inputs: " + transaction.Inputs.Count); var spentCoins = transactionResponse.SpentCoins; foreach (var spentCoin in spentCoins) { receivedAmount = (Money)spentCoin.Amount.Add(receivedAmount); } Console.WriteLine("Bitcoin Received: " + receivedAmount.ToDecimal(MoneyUnit.BTC)); var fee = transaction.GetFee(spentCoins.ToArray()); Console.Write("Fees (in Satoshis): "); Console.WriteLine(fee); }
public static BcnTransaction ToDomain(this GetTransactionResponse src) { return(new BcnTransaction { Id = src?.TransactionId?.ToString(), Amount = src?.SpentCoins?.Sum(x => x?.TxOut?.Value?.ToDecimal(MoneyUnit.BTC) ?? 0) ?? 0, Confirmations = src?.Block?.Confirmations ?? 0, BlockId = src?.Block?.BlockId?.ToString(), Blockchain = BlockchainType.Bitcoin, AssetId = nameof(MoneyUnit.BTC) }); }
static void Main(string[] args) { QBitNinjaClient client = new QBitNinjaClient(Network.Main); var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94"); GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result; NBitcoin.Transaction transaction = transactionResponse.Transaction; Console.WriteLine("Getting the transaction ID from GetTransactionResponse: " + transactionResponse.TransactionId); Console.WriteLine("Getting the transaction ID from Transaction: " + transaction.GetHash()); Console.WriteLine(); Console.WriteLine("Getting received coins info:"); List <ICoin> receivedCoins = transactionResponse.ReceivedCoins; foreach (var coin in receivedCoins) { Money amount = (Money)coin.Amount; Console.WriteLine("Amount: " + amount.ToDecimal(MoneyUnit.BTC)); var paymentScript = coin.TxOut.ScriptPubKey; Console.WriteLine("ScriptPubKey: " + paymentScript); var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine("BitcointAddress: " + address); } Console.WriteLine(); Console.WriteLine("Getting spent coins info:"); decimal totalSpent = 0; List <ICoin> spentCoins = transactionResponse.SpentCoins; foreach (var coin in spentCoins) { Money amount = (Money)coin.Amount; totalSpent += amount.ToDecimal(MoneyUnit.BTC); Console.WriteLine("Amount: " + amount.ToDecimal(MoneyUnit.BTC)); var paymentScript = coin.TxOut.ScriptPubKey; Console.WriteLine("ScriptPubKey: " + paymentScript); var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine("BitcointAddress: " + address); } Console.WriteLine(); Console.WriteLine("Total Spent: " + totalSpent); }
// get transaction response object by transaction id public GetTransactionResponse GetTransactionResponseObject(string transactionId) { // parse transaction id to NBitcoin.uint256 so the client can eat it var parsedTransactionId = uint256.Parse(transactionId); // query the transaction GetTransactionResponse transactionResponse = _client.GetTransaction(parsedTransactionId).Result; // get transaction if (transactionResponse != null) { return(transactionResponse); } else { throw new Exception("Can not get info for transaction with this ID or transaction does not exist."); } }
private GetTransactionResponse GetTransactionInfo(TransactionEntry tx, bool colored, BlockInformation block) { var response = new GetTransactionResponse() { TransactionId = tx.TransactionId, Transaction = tx.Transaction, IsCoinbase = tx.Transaction.IsCoinBase, Fees = tx.Fees, Block = block, FirstSeen = tx.FirstSeen }; for (int i = 0; i < tx.Transaction.Outputs.Count; i++) { var txout = tx.Transaction.Outputs[i]; NBitcoin.ICoin coin = new NBitcoin.Coin(new NBitcoin.OutPoint(tx.TransactionId, i), txout); if (colored) { var entry = tx.ColoredTransaction.GetColoredEntry((uint)i); if (entry != null) { coin = new NBitcoin.ColoredCoin(entry.Asset, (NBitcoin.Coin)coin); } } response.ReceivedCoins.Add(coin); } if (!response.IsCoinbase) { for (int i = 0; i < tx.Transaction.Inputs.Count; i++) { NBitcoin.ICoin coin = new NBitcoin.Coin(tx.SpentCoins[i].OutPoint, tx.SpentCoins[i].TxOut); if (colored) { var entry = tx.ColoredTransaction.Inputs.FirstOrDefault(ii => ii.Index == i); if (entry != null) { coin = new NBitcoin.ColoredCoin(entry.Asset, (NBitcoin.Coin)coin); } } response.SpentCoins.Add(coin); } } return(response); }
/// <summary> /// Gets general information for a given transaction /// </summary> /// <param name="transactionResponse">Object containing the transaction in QBitNinja format</param> public void FetchGeneralTxInfo(GetTransactionResponse transactionResponse) { try { TxId = transactionResponse.Transaction.GetHash().ToString(); TotalTxAmount = transactionResponse.Transaction.TotalOut.ToString(); Fee = transactionResponse.Fees.ToString(); DateReceived = transactionResponse.FirstSeen.ToString(); TxConfirmations = transactionResponse.Block.Confirmations.ToString(); BlockHash = transactionResponse.Block.GetHashCode().ToString(); BlockHeight = transactionResponse.Block.Height.ToString(); //Transaction Index pending Txsize = transactionResponse.Transaction.GetSerializedSize().ToString(); Version = transactionResponse.Transaction.Version.ToString(); //relayedBy pending } catch { } }
public static PoliCompleteResponse ToPoliCompleteResponse(this GetTransactionResponse instance) { var response = new PoliCompleteResponse { Status = instance.TransactionStatusCode }; if (instance.ErrorMessage.IsNotNullOrWhiteSpace()) { response.AddError(instance.ErrorMessage); } if (instance.AmountPaid.NotEquals(instance.PaymentAmount)) { response.AddError("Expected {0} to be paid, but was actually {1}".FormatWith(instance.PaymentAmount, instance.AmountPaid)); } return(response); }
/// <summary> /// Work with previous transactions to build out available coin data /// </summary> public static void WorkingWithCoins() { //Create a client for our QBitNinja API calls var client = new QBitNinjaClient(_network); //Get the unspent outputs/coins from the last transaction for the contractor that can be used //GetTransactionResponse transactionResponse = client.GetTransaction(uint256.Parse("3fd79e0843b8f834737abfb7c39a65bcab164d3229a1da3b71224989c2ab048b")).Result; GetTransactionResponse transactionResponse = client.GetTransaction(uint256.Parse("26b3a2ff92a918ad8c46c2da7dbf4c27c7a12bd24655c9d12f03d0f18edcede6")).Result; //Generate a list of receive coins from the transaction List <ICoin> receivedCoins = transactionResponse.ReceivedCoins; List <ICoin> spentCoins = transactionResponse.SpentCoins; Console.WriteLine("--------------- RECEIVED COINS------------------"); Console.WriteLine(); foreach (var coin in receivedCoins) { 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(); } Console.WriteLine(); Console.WriteLine("--------------- SPENT COINS ------------------"); Console.WriteLine(); foreach (var coin in spentCoins) { 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(); } }
internal TransactionInfo(GetTransactionResponse transactionResponse, Network network) { if (transactionResponse == null) { throw new NullReferenceException("Transaction does not exists"); } _network = Convert.ToNBitcoinNetwork(network); _spentCoins = transactionResponse.SpentCoins; _receivedCoins = transactionResponse.ReceivedCoins; Id = transactionResponse.TransactionId.ToString(); Confirmed = transactionResponse.Block != null; Fee = transactionResponse.Fees.ToDecimal(MoneyUnit.BTC); AllInOutsAdded = FillInOutInfoList(out _inputs, _spentCoins) && FillInOutInfoList(out _outputs, _receivedCoins); }
public static IEnumerable <XlsxTransactionInputOutput> Create(GetTransactionResponse source, IDictionary <string, IAssetDefinition> assetDictionary, Network network) { var index = 0; foreach (var inOut in source.SpentCoins) { var addr = inOut.TxOut?.ScriptPubKey?.GetDestinationAddress(network); yield return(Create(addr, inOut, source.Block, source.TransactionId, assetDictionary, index, network, CoinType.Input)); index++; } index = 0; foreach (var inOut in source.ReceivedCoins) { var addr = inOut.TxOut?.ScriptPubKey?.GetDestinationAddress(network); yield return(Create(addr, inOut, source.Block, source.TransactionId, assetDictionary, index, network, CoinType.Output)); index++; } yield return(CreateFees(source.Fees, source.Block, source.TransactionId, index)); }
/// <summary> /// Return Affected Row Or Error If Exist /// </summary> /// <param name="request">Transaction Information</param> /// <returns>Affected Row Or Error If Exist</returns> public static GetTransactionResponse Transaction(GetTransactionResponse request) { GetTransactionResponse response = new GetTransactionResponse(); response.Error = new Handler.ErrorObject(); try { tblTransaction bussines = new tblTransaction() { id = request.Transaction.id, amount = request.Transaction.amount, detail = request.Transaction.detail, idProvide = request.Transaction.idProvide, createDate = request.Transaction.createDate, idConditionProduct = request.Transaction.idConditionProduct, expeditionDate = request.Transaction.expeditionDate, upDateDate = null, deleteDate = null, state = "Active" }; var result = TransactionData.Insert.Transaction(bussines); if (result.Item1.Error) { response.Error.InfoError(result.Item1); } else { response.Message = result.Item2.ToString(); } } catch (Exception ex) { response.Error.InfoError(ex); } return(response); }
/// <summary> /// Return Affected Row Or Error If Exist /// </summary> /// <param name="TransactionID">Transaction ID</param> /// <param name="state">State</param> /// <returns>Affected Row Or Error If Exist</returns> public static GetTransactionResponse TransactionDisable(int TransactionID, string state) { GetTransactionResponse response = new GetTransactionResponse(); try { var result = TransactionData.Delete.TransactionDisable(TransactionID, state); if (result.Item1.Error) { response.Error.InfoError(result.Item1); } else { response.Message = result.Item2; } } catch (Exception ex) { response.Error.InfoError(ex); } return(response); }
// 演習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; }
private static void RecursivelyInspectForCoinbaseTransaction(QBitNinjaClient client, NBitcoin.Transaction transaction, TxInList inputs) { foreach (TxIn input in transaction.Inputs) { uint256 previousTransactionId = input.PrevOut.Hash; GetTransactionResponse previousTransactionResponse = client.GetTransaction(previousTransactionId).Result; NBitcoin.Transaction previousTransaction = previousTransactionResponse.Transaction; var previousTransactionOutputs = previousTransaction.Outputs; foreach (TxOut previousTransactionOutput in previousTransactionOutputs) { Money amount = previousTransactionOutput.Value; Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC)); var paymentScript = previousTransactionOutput.ScriptPubKey; Console.WriteLine(paymentScript); // It's the ScriptPubKey var address = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine(address); Console.WriteLine(); } } }
/// <summary> /// Adds a new confirmation if it is greater than the last number of confirmations /// </summary> /// <param name="getTransactionResponse"></param> /// <param name="transactionIndex"></param> /// <param name="depositsConfirmed"></param> private void AddNewConfirmation(GetTransactionResponse getTransactionResponse, int transactionIndex, List <Tuple <string, int> > depositsConfirmed) { // If the current confirmation count in the block chain is greater than the one we have stored, update // confirmations if (getTransactionResponse.Confirmations > _pendingTransactions[transactionIndex].Item2) { Log.Debug(string.Format("Dogecoin Confirmation received from network: Transaction ID = {0}, Confirmations = {1}", _pendingTransactions[transactionIndex].Item1, getTransactionResponse.Confirmations)); _pendingTransactions[transactionIndex] = new Tuple <string, int>(_pendingTransactions[transactionIndex].Item1, getTransactionResponse.Confirmations); try { if (DepositConfirmed != null) { // Raise the event and sned the TransacitonID and the no. of confirmation respectively DepositConfirmed(_pendingTransactions[transactionIndex].Item1, getTransactionResponse.Confirmations); } } catch (Exception exception) { Log.Error(exception); } finally { // If the no of confirmations is >= 7, add to the list of confirmed deposits to be deleted outside this // loop if (getTransactionResponse.Confirmations > 6) { // Add the confirmed trnasactions into the list of confirmed deposits depositsConfirmed.Add(_pendingTransactions[transactionIndex]); Log.Debug(string.Format("Verified deposit added to confirmed deposits list: Transaction ID = {0}", _pendingTransactions[transactionIndex].Item1)); } } } }
// get transction information public TransactionInfo GetTransactionInfo(string transactionId, TransactionActions actionType) { GetTransactionResponse transactionResponse = GetTransactionResponseObject(transactionId); TransactionInfo transactionInfo = new TransactionInfo(); transactionInfo.transactionType = actionType; switch (actionType) { case TransactionActions.ReceiveCoins: List <ICoin> receivedCoins = transactionResponse.ReceivedCoins; transactionInfo.TransactionFee = GetTransactionFee(transactionResponse.Transaction, receivedCoins); transactionInfo.outputsInfo = GetInfoAboutCoins(receivedCoins); break; case TransactionActions.SpendCoins: List <ICoin> spentCoins = transactionResponse.SpentCoins; transactionInfo.TransactionFee = GetTransactionFee(transactionResponse.Transaction, spentCoins); transactionInfo.outputsInfo = GetInfoAboutCoins(spentCoins); break; } return(transactionInfo); }
/// <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); }
private static bool TryGetTransaction(string txid, out GetTransactionResponse tx) { tx = default(GetTransactionResponse); try { tx = nxtClient.GetTransactionAsync(txid).Result; return true; } catch (NXTCallException ex) { Log.Warn("TryGetTransaction访问出错:" + ex.Message); return false; } }
private static void ProcessTx(int userID, GetTransactionResponse tx, UInt64 nxtAccountID, CurrencyType currency) { var cacheKey = currency.ToString() + tx.SenderRS + tx.Transaction + "create"; if (tx.Type != TransactionType.Ordinary || tx.Recipient != nxtAccountID) { //如果交易类型不是普通交易或者收款账户非当前账户(非收款),忽略,并加入忽略名单,防止多次请求交易明细,浪费资源 Cache.Add(cacheKey, tx.Confirmations); return; } object obj = null; if (Cache.TryGet(cacheKey, out obj)) return; Log.Info("发现新的交易...."); var actualAmount = tx.AmountNQT / 100000000; #region 发送交易到处理消息队列 var mqname = "NXTReceiveTransactionListener"; _channel = _mqpool.GetMQChannel(mqname); var exchangeName = Utilities.GenerateVirtualCoinReceivePaymentExchangeAndQueueName(currency).Item1; var build = new BytesMessageBuilder(_channel); var cmd = new CreateReceivePaymentTransaction(tx.Transaction, tx.RecipientRS, actualAmount, currency); build.WriteBytes(Encoding.UTF8.GetBytes(IoC.Resolve<IJsonSerializer>().Serialize(cmd))); ((IBasicProperties)build.GetContentHeader()).DeliveryMode = 2; try { Log.Info("交易将被发送到Exchange->{0}", exchangeName); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); Log.Info("交易成功发送到Exchange->{0}", exchangeName); Cache.Add(cacheKey, tx.Confirmations); } catch (RabbitMQ.Client.Exceptions.AlreadyClosedException ex) { Log.Error("发送{0}新交易创建指令时发现消息队列服务器已关闭".FormatWith(Config.CoinCode), ex); try { _channel = _mqpool.GetMQChannel(mqname); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); Log.Info("交易成功发送到Exchange->{0}", exchangeName); } catch (Exception eex) { Log.Fatal("重新链接消息队列发送NXT新交易仍然出错了".FormatWith(Config.CoinCode), eex); } } catch (Exception ex) { Log.Error("发送{0}新交易创建指令时出现错误".FormatWith(Config.CoinCode), ex); } #endregion #region 提取币到总账户中 try { var nxtclient = new NXTClient4Net(Config.NXTServer, Config.SecretPhrase + userID); var result = nxtclient.SendMoneyAsnc(Config.NxtSumAccount, actualAmount - 1).Result; Log.Info("用户充值的币发送到总帐户成功"); } catch (Exception ex) { Log.Fatal("用户ID={0}充值的{1}NXT发送到总帐户失败了,请及时处理".FormatWith(userID, actualAmount), ex); } #endregion }
private static bool ExistConfirmTx(GetTransactionResponse tx, CurrencyType currency) { bool isExist = false; var cacheKey = currency.ToString() + tx.Transaction + "_" + (tx.AmountNQT / 100000000) + "confirm"; var tmp = new object(); if (Cache.TryGet(cacheKey, out tmp)) { isExist = true; } return isExist; }
private static void ProcessTx(GetTransactionResponse tx, CurrencyType currency) { if (!ExistConfirmTx(tx, currency)) { Log.Info("txid={0}的交易确认已达到{1}个,开始发送确认消息..", tx.Transaction, tx.Confirmations); var mqname = "NXTTransactionConfirmationValidator"; _channel = _mqpool.GetMQChannel(mqname); var build = new BytesMessageBuilder(_channel); var exchangeName = Utilities.GenerateVirtualCoinReceivePaymentExchangeAndQueueName(currency).Item1; try { var amount = tx.AmountNQT / 100000000; var cmd = new ConfirmReceivePaymentTransaction(tx.Transaction, tx.RecipientRS, tx.Confirmations, amount, currency); build.WriteBytes(Encoding.UTF8.GetBytes(IoC.Resolve<IJsonSerializer>().Serialize(cmd))); ((IBasicProperties)build.GetContentHeader()).DeliveryMode = 2; _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); var cacheKey = currency.ToString() + tx.Transaction + "_" + amount + "confirm"; Cache.Add(cacheKey, tx.Confirmations); Log.Info("txid={0}的交易确认消息发送完毕", tx.Transaction, tx.Confirmations); } catch (RabbitMQ.Client.Exceptions.AlreadyClosedException ex) { Log.Error("发送{0}新交易创建指令时发现消息队列服务器已关闭".FormatWith(Config.CoinCode), ex); try { _channel = _mqpool.GetMQChannel(mqname); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); } catch (Exception eex) { Log.Fatal("NXTTransactionConfirmationValidator消息队列服务器连接重试后仍无法连接成功,可能消息队列服务器已经挂掉,请尽快处理!", eex); } } catch (Exception ex) { Log.Error("发送{0}新交易创建指令时出现错误".FormatWith(Config.CoinCode), ex); } } }