Search code examples
cryptographyhexblockchainbitcoinpycrypto

Convert bitcoin transaction hash to raw hexcode


I have a list of Bitcoin transaction hashes like this one: a4ad67ea73c88b635e003700290239e6beab7dc5c9b31f58cd34084418b7316d

I would like to convert this hash to raw format (in hexcode). For example, the blockchain API converts this transaction hash to the following (https://blockchain.info/rawtx/a4ad67ea73c88b635e003700290239e6beab7dc5c9b31f58cd34084418b7316d?format=hex):

01000000000101b6e447e3730b6c22a4312c51e98a013b8e1514ebe592a75767349b659dd1eb4b0000000000ffffffff020000000000000000536a4c50000d2ab10002ce909734abc6014d89e07b7d1d5aa1d324eb6af71e2860a470d612483853e078120e105d3ea910720edbb89fc9025e3b4d8e0701e44510686281d5484fbb48444129251371047bf8ad5b5fb9010000000000160014841996f8ff255c875c4f8875a7bd036bf64209210246304302203c5ef41b9f17525714ab840dbd1716c2baae14e14db84a18716f97b5d1c3aa3c021f6be45f733d3ce5094b470385d997e797ffab976610c015833b395197be586601210380a033803cdcfae4dda162741774cbf38af31ebdd11e9bba414590d7fe36835400000000

One way to get the raw transaction bytes isto query the API, but this is very time consuming since my dataset is large. I am therefore wondering if there is an easier way to do this conversion. I am using Python.

Thanks in advance for your help.


Solution

  • As you have a local copy of the blockchain you can use getrawtransaction and decoderawtransaction from python-bitcoinlib.

    from bitcoinlib.services.bitcoind import BitcoindClient
    bdc = BitcoindClient.from_config('/usr/local/src/.bitcoinlib/config/bitcoin.conf') txid = 'a4ad67ea73c88b635e003700290239e6beab7dc5c9b31f58cd34084418b7316d'
    rt = bdc.getrawtransaction(txid)
    print("Raw: %s" % rt)
    
    > Raw: 01000000000101b6e447e3730b6c22a4312c51e98a013b8e1514ebe592a75767349b659dd1eb4b0000000000ffffffff020000000000000000536a4c50000d2ab10002ce909734abc6014d89e07b7d1d5aa1d324eb6af71e2860a470d612483853e078120e105d3ea910720edbb89fc9025e3b4d8e0701e44510686281d5484fbb48444129251371047bf8ad5b5fb9010000000000160014841996f8ff255c875c4f8875a7bd036bf64209210246304302203c5ef41b9f17525714ab840dbd1716c2baae14e14db84a18716f97b5d1c3aa3c021f6be45f733d3ce5094b470385d997e797ffab976610c015833b395197be586601210380a033803cdcfae4dda162741774cbf38af31ebdd11e9bba414590d7fe36835400000000
    

    Remember, in Bitcoin transaction hashes are shown little-endian rather than big-endian.