That makes it a bit clearer. But I still don't fully understand the raw transactions.
Here is an example of how I now think it works. Can someone correct me if a step is wrong?
I'll try to help.
I have an unspent transaction with 1 bitcoin.
More accurately, you have an unspent
transaction OUTPUT valued at 1 bitcoin.
I want to move 0.5 to another address.
You want to create a new transaction that has an output associated with another address and valued at 0.5 bitcoins
But because the unspent transaction is 1 bitcoin, the whole bitcoin will be send.
The unspent transaction
OUTPUT is valued at 1 bitcoin.
Because of that, the whole OUTPUT (valued at 1 bitcoin) will be spent when it is used as an input to your new transaction.
So I send the rest back to my own address.
In your new transaction you create a second output that is associated with an address for which you have the private key and which is valued at 0.5 bitcoins.
So there is going 0.5 to the other user. And 0.5 back to me.
There are two outputs valued at 0.5 bitcoins each. You have the private key associated with one of the outputs, and the other user has the private key associated with the other output.
Does this mean I don't pay any fee?
This means that you built a transaction that did not include any transaction fee.
Or do I pay fee but the user doesn't receive the full 0.5 bitcoins.
If you want to do that, then you will have to reduce the value of the output that you create for the other user.
And if I for example sent 0.49 instead of 0.5 back to me. Do I now pay 0.01 fee?
Correct. If you spend an output that is valued at 1 bitcoin, and you create 2 outputs (one valued at 0.5 bitcoins and the other valued at 0.49 bitcoins) then the transaction has a fee of 0.01 bitcoins.
And do other wallet also work with sending the rest back? I can't remember that I can any incomming transaction after I made a transaction.
This is how the bitcoin transaction protocol works. All transactions are just a list of inputs (previously unspent outputs) that supply value to the transaction, and a list of new unspent outputs that are assigned value. The total value of all the outputs cannot exceed the total value of all the inputs (if the sum of the outputs exceeds the sum of the inputs, then the transaction is INVALID and rejected by all nodes). If the sum of the outputs is LESS THAN the sum of the inputs, then the remaining value is a transaction fee that the miner can assign to themselves.
The user interface of some wallet programs might not be designed to show all these details (since they can confuse those that don't have a technical understanding of what is happening).