How does consensus protect from lying about transactions? I'm really new to the whole concept of blockchain. 

I do understand how consensus protects from changing past blocks and allows to keep a clear and valid blockchain, but I am having a hard time trying to wrap my head around fake transactions.

Let me explain. As I understand it :


Nodes in the network produce transactions.
They are repeated all across the network
At the same time, some nodes try to mine a block.
When someone resolves the hash, they can create their block.
The block is accepted by everybody on the network as they can immediately check Proof of Work (via the hash + the data)


Ok so this basically means that everybody follows the consensus (otherwise, everything said by anybody else would be garbage to a Node, and the other way round : we would have an isolated node). But how do they know that the transactions themselves written in the new block are correct ?

For instance, let A and B be two accounts. What prevents a node from randomly saying "B gave n bitcoins to A", and that information being completely false ? B would obviously benefit from doing that.

Maybe I don't understand how consensus is enforced in nodes themselves as well... is everybody running the same "program" ? Is it something in the protocol itself ? Does the consensus "know" when a transaction cannot be made for some reason ?

Thanks for your help
You can think of a bitcoin address like a machine that produces locks and a bitcoin wallet like a machine that produces unforgeable, labeled keys.

Say Alice received 1 bitcoin from Bob and wants to send it to Charlie. If Alice has 1 bitcoin to send, that means there is 1 bitcoin that is locked with a lock from her lock-making machine.

When Alice wants to send that 1 bitcoin to Charlie, she must have his address. She uses his address as a lock-making machine and makes a lock that only Charlie can unlock. She feeds this to her key-making machine and makes a key to the lock that only she can make a key to but labels it with the lock she got from Charlie's lock making machine.

This new key only opens the 1 bitcoin Alice will send to Charlie, and only Alice could make it. The attached new lock can only be opened by Charlie, since only he has the matching key-making machine.

You consider someone to have "sent you a bitcoin" if they locked it with a lock that only you can open.

So, a block that contains invalid transactions is itself invalid and ignored. You can only form valid transactions that transfer bitcoins with the appropriate keys or the transactions are invalid.

This might make you wonder what you need consensus for at all. And the problem is that Alice could maliciously make multiple keys that open the same lock, transferring the same 1 bitcoin to both Charlie and Dave. We need consensus to agree which of a set of conflicting transaction, each individually valid, we can rely on.