Bitcoin core - How to get transaction size before send BTC to an address

1.3k Views Asked by At

How can I get transaction size before sending BTC to an external address?

I am using Bitcoin core to make the transactions, and I was trying to calculate transaction size. So that I can use it to estimate transaction fee. But couldn't find a way

Could you tell me its logic and method to do it?

2

There are 2 best solutions below

2
On

You can sign the transaction locally in your code, instead of using bitcoind. Then you simply measure the size of the transaction serialised as a byte stream.

0
On

After signing the transaction with either

  • signrawtransactionwithwallet
  • signrawtransactionwithkey
  • signrawtransaction , this is deprecated and fully removed from bitcoind 0.18.0 and above.

It will return hex value in the result. Use decoderawtransaction to view your transaction before sending. In the result it has 'size' attribute showing the size of your transaction. Below is a snippet from bitcoind documentation.

...
  "txid" : "hex",           (string) The transaction id
  "hash" : "hex",           (string) The transaction hash (differs from txid for witness transactions)
  "size" : n,               (numeric) The transaction size
  "vsize" : n,              (numeric) The virtual transaction size (differs from size for witness transactions)
  "weight" : n,             (numeric) The transaction's weight (between vsize*4 - 3 and vsize*4)
 ...

However, if you are planning to broadcast a transaction with a known fee rate in mind, you should use fundrawtransaction to specify your transaction's fee rate etc.