I have a website where users can send and withdraw funds using Bitcoin. I would like to give them the possibility to use different fees (low, medium and high) instead of a fixed fee or to let bitcoind choose the fee. I can't setup a default fee or be changing it at runtime because then if a user decides to use a high fee and a lower one, it could happen that the user with the high fee is assigned as low or vice versa.
Therefore, after researching I have come to the conclusion that it is necessary to build the transaction from the UTXOS that my node has. However, it is difficult for me to finish understanding how to carry out this task. I will give an example to explain my problem: If the node UTXOS is 1BTC, a user has 0.1 BTC in the service wallet and wishes to withdraw 0.07 BTC. I understand that the steps to be taken would be the following:
- List all unspent transactions
- Select one or more inputs to create the transaction
- The fee is calculated as the subtraction between the total of the inputs and the outputs
My doubts at this moment would be:
If I understand correctly, for each incoming transaction we have, we will have an unspent transaction that will allow us to spend the available funds; Then, as long as you have in a database the correct balance to each user (updating that balance with the corresponding fees when withdrawing funds), so I should only use the same UTXO generated by each user when depositing btcs Or is it possible to use other UTXOs as long as the quantity is the same?
I have read in bitcointalk that the inputs of a raw transaction must be less than or equal to the outputs of that transaction. Is it not possible to use inputs higher than the outs and "return" the surplus funds again to a wallet of my node?
How can I calculate the fee used? I mean, I can decide that I want to use X satoshis/kb but how can I calculate the fee that the transaction will need before I create it? Because if I understood correctly, the size of the transaction I get once I have created such transaction. I do not know if there is a way to perform the calculation that the transaction will occupy in bytes / kilobytes
I have not found too much information about it, so if anyone can help me I would appreciate it.