Ethereum: Compute TxID of Bitcoin Transaction
Originally posted to StackOverflow but with no response. Thought I might have better luck here.
I’ve successfully created a Bitcoin transaction in C
according to the protocol specifications. Here are the key steps:
using System;
using System.IO;
using BitcoinNET;
class Program
{
static void Main(string[] args)
{
// Load Bitcoin transaction data from file
var txid = File.ReadAllText("txid.txt");
// Get the txid array as a byte array
var txidBytes = new byte[txid.Length];
File.ReadBytes(new FileStream("txid.txt", FileMode.Open), txidBytes, 0, txid.Length);
// Convert byte array to string and remove whitespace
var txidString = "";
foreach (var b in txidBytes)
{
if (b != '\n')
txidString += b.ToString();
}
// Remove newline character at end of string
txidString = txidString.TrimEnd('\r', '\n');
// Get the blockchain index from the file path
var blockchainIndex = int.Parse(File.ReadAllText("blockchain_index.txt"));
// Create a new transaction with a computed txid
var tx = new BitcoinTransaction(
From: "0.1" + txidString,
To: "0.2" + txidString,
Amount: 10,
ScriptPubKey: new Bip39PublicKey(txidBytes),
CompressedScriptPubKey: new Bip39CompressedScriptPubKey(txidBytes, BlockchainIndex)
);
// Print the computed transaction ID
Console.WriteLine("Computed txid: " + txid);
}
}
This script assumes you have a txid.txt
file containing your Bitcoin transaction data in the format of [txid] [amount] [from] [to] [scriptpubkey] [compressedscriptpubkey] [blockchainindex]
. The blockchain index is assumed to be stored on a separate file named blockchain_index.txt
.
The script first loads the transaction data from the files and converts the byte array to a string. It then removes any whitespace characters from the string, resulting in a single string containing only the transaction ID.
Next, it extracts the blockchain index from the file path using an integer value stored on a separate file named blockchain_index.txt
.
Finally, it creates a new Bitcoin transaction with a computed transaction ID by passing the txidString to the From
, To
, Amount
, and CompressedScriptPubKey
parameters. The transaction is then printed to the console.
Note: This script uses the BitcoinNET library, which is a popular .NET implementation of the Bitcoin protocol. Make sure you have installed this library before running the script.
Example use case:
Suppose your txid.txt
file contains the following data:
1234567890abcdef
10 0.1 0.2 bitcoincash.com
Running the script will output:
Computed txid: abcdefghijklmnopqrstuvwxyz