How to calculate transaction size before sending (Legacy Non-Segwit - P2PKH/P2SH) I know that I pay the transaction fee per kB, so how can I calculate how large the transaction will be before I send it via the RPC api. I run a site using bitcoins, and I cannot let the user's balance go negative, so I need to know if they have enough balance to cover the cost.
Assuming all the inputs you are spending are from regular "pay to address" transactions, each input will contribute 180 (plus or minus 1) bytes to the transaction.  Each output adds 34 bytes to the transaction.  And there's a fixed extra 10 bytes which are always present.

The "plus or minus 1" comes from the fact that each input needs a signature to be claimed.  The signature contains two 32 byte values, but if either of the values has a first byte of 0x80 or more, it has a 0x00 byte prepended to it.  So I'm assuming one of the two is high and the other is low.  That way I'm off by at most one byte per input.

So if your transaction has in inputs and out outputs, the transaction size, in bytes will be:

in*180 + out*34 + 10 plus or minus 'in'


For example, this transaction has 40 inputs and 16 outputs.  That gives us a transaction size of

40*180 + 16*34 + 10 +- 40


i.e. 7754 +- 40 bytes.  The actual size is 7761 bytes.

If the inputs are from "pay to pubkey" transactions then the inputs are smaller than for "pay to address" transactions.  And this will be different also for "pay to script hash" inputs too, depending on how/if that's implemented.

Edit: This transaction was made with bitcoins stolen in the Linode heist and shows a transaction size of 1337, possibly a deliberate use of leetspeak in the blockchain.

Edit2: Now that compressed public keys are commonplace, each input is 32 bytes shorter and so the transaction size is now:

in*148 + out*34 + 10 plus or minus 'in'