karask / python-bitcoin-utils

Library to interact with the Bitcoin network. Ideal for low-level learning and experimenting.
MIT License
262 stars 99 forks source link

How to accurately estimate fees to determine change? #66

Closed jahvi closed 3 months ago

jahvi commented 3 months ago

I have a script that creates a transaction based on multiple inputs and outputs, I can get the tx vsize with get_vsize and multiply it by a "sat per vb" amount to estimate fees, and subtract that from my total inputs - total outputs to know if I have enough change to send to another address.

The problem is that to add a change address I need to add another output AND sign my inputs again to avoid signature mismatch both of which increase the tx size and invalidates my change amount so I'm stuck in a catch 22.

The way I'm handling it now is to hardcode a fee and manually tweak it until it roughly hits the "sat per vb" number I want to go for but it's not very efficient. Is there a better way to accomplish this?

Great job on the library btw!

karask commented 3 months ago

Hi @jahvi ,

You have two ways of doing this:

  1. You create the tx (inlc. the change address with any value) and sign it. Then calculate the tx fee, update the amount of the fees/change address and re-sign the transaction before broadcasting.
  2. You can pre-calculate the bytes of the inputs and outputs (given that you know the locking/unlocking scripts) since the structure of the tx is known in advance. Example for legacy scripts: https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending-legacy-non-segwit-p2pkh-p2sh

I hope the above helps and thank you for your kind words, Kostas

jahvi commented 3 months ago

@karask Thanks, I'm doing option #1 right now, not the most efficient but it's easy for now 👍🏽