How To Trust A Stranger With Your Money — Blockchain and Crypto Security Explained

w/Code examples!

Elliott Lindsay
9 min readApr 14, 2023

You and your friends, some work colleagues and the bartender walk into a bar. Everyone buys different drinks but not everyone has enough money. However, after you and your friends borrow some money from the richer ones, everyone is happy and having a good time getting drunk.

You all go home to get your wallets but nobody remembers how much they borrowed.

So, how do we keep track of everyone’s spending?

With a blockchain of course!

Blockchain Explained

Blockchain is a ledger that is usually used to record all of the transactions for a cryptocurrency(s) between two people (or computers) that happen on a certain site and the respective account balances updated based on the transaction recorded.

It’s decentralized meaning that there is no one person, organization, company, etc., who has supreme control over others. For example, YouTube is run and managed by its users. Creators post content and consumers watch it and without anybody using the platform, nobody would be making any money. YouTube relies on its users.

However unlike a blockchain, YouTube has a company who can control the entire site: Google (Yes, google acquired it in 2006). And they can do whatever they want with it. But nobody can control a blockchain since nobody has “god powers”.

The blockchain is made up of blocks which contain transactions, all chained together, hence the name: blockchain. You can think of the blockchain as a piece of paper or a list, a block as a line, and the transactions as the words on a line — but digital.

In blocks, there is a limit of one megabyte worth of transaction data. This is to prevent attackers from filling up a block with a bunch of fraudulent transactions and potentially overloading the network.

In addition, one block should be added every 10 minutes to the blockchain and having a larger block size could slow down the system. Why 10 minutes? Since blockchain is decentralized, it may take a while for other people to catch up so the 10 minutes is to ensure that everyone is caught up and their blockchains are in sync. This’ll make more sense later.

The Rules Of Blockchain

Blockchains are complicated, so instead, let’s use a simple piece of paper to simplify.

Back at the bar, you’ve gotten a time machine and went back in time. And you return with a piece of paper (the blockchain)!

In this instance of time, you all write down on a piece of paper (the Blockchain) what everyone should pay back. For example, “Bob pays Jeff $15" as Bob borrowed $15 from Jeff, thus Bob must pay Jeff the money back.

Blockchain should be decentralized meaning that everyone should be able to contribute and add their debt to the piece of paper, not having one person go around the room to write down everything. Then the piece of paper will be centralized around that one person.

And so the first two rules of our piece of paper have been developed: Anyone can write a line, thus anyone can view the paper.

But this leads to a problem. Charlie, who’s already drunk on his vodka writes “Jeff pays Charlie $60". Being drunk, he accidentally swapped the names and it was actually Charlie who borrowed the $60. Fortunately Jeff caught the mistake before he lost his $60 but what if he didn’t?

Let’s rewind again.

In this timeline, a new rule is added: All lines must be signed.

There’s one major flaw with our current rules. Who’s stopping Charlie from saying that Jeff owes him $600? “Jeff pays Charlie $600”? Maybe Jeff just really likes to be in debt, who knows?

So what does signing a payer mean, why do it? To prevent mistakes or scams such as these, all transactions must be signed and be given the stamp of approval with a signature. In digital “papers” such as a blockchain, this can also help prevent hacking and attackers.

Blockchains use public key cryptography (or asymmetric cryptography) for signatures. Everyone has a public key and a private key, otherwise known as a secret key.

A public key could be something like your email. Something that you can share with others. For example, Charlie could send a link to Jeff’s email (public key) that when clicked, will add $600 to his bank account. But in order to access the email and click on the link you will need the secret key, or the “password”.

Let’s digest what really happens when a blockchain transaction happens:

Let’s say that Bob is paying Jeff $10. First, Bob must sign the transaction using his secret key. This shows that Bob has the power to send crypto from his account as he is the only one who (should) know his secret key and this proves that the person sending the money is actually Bob and that he consents to this transaction.

The transaction is encrypted using Jeff’s public key which can then be decrypted by Jeff with his private key. Most blockchains use Elliptic Curve Digital Signature Algorithm (ECDSA) as their public-private key algorithm which honestly, is far too complicated to explain in this article.

But let’s be honest here. On a computer, anything can be copied. Why can’t you just copy the signature? Who needs a secret key to make a signature, when you can just get the signature itself?

Well, what if the signature constantly changes? Signatures are generated based on two things: the secret key of the sender and the message (e.g. “Bob pays Jeff $10” ← That entire string would be the message). It’s like a math formula: message × secret key = signature (except a lot more complicated). This also means that if one thing changes, the output signature changes. For example:

$10 × (let’s say that Bob’s secret key is:) 89 = 890

However, if some sort of hacker tries to tamper with the message, trying to bankrupt Bob and make him pay $10000 instead of only $10:

$10000 × 89 = 890000

890 is not equal to 890000, and it is clear that something has gone amiss.

So now that that’s sorted out, all good right? Well, not really because… I lied. Our current blockchain, our current piece of paper is not actually decentralized. Just because the person who is holding the blockchain changes, it’s still centralized around that one person. So how do we solve this issue?

One last iteration. This time, the piece of paper is photocopied and a copy is given to everyone. Now that everyone has their own piece of paper, nothing is centralized around nobody. Nobody has supreme control over all the papers.

Now, whenever someone writes a transaction, they shout it out and everyone writes it down on their own piece of paper.

But how do we know that everyone is actually writing stuff down? Or what if someone shouts out their current piece of paper, and it doesn’t align with what you wrote? Well, the longest paper wins and becomes the “official” new blockchain. If there’s a tie, just wait until a new block is added to one of the blockchains and that one will become the official blockchain.

But what if Bob whispers a transaction to Jeff, let’s say “Bob pays Jeff $100” but nobody else heard? Everyone else thinks Bob still has that $100 and there’s no stopping him from spending it. Jeff’s paper would look something like this: “Alex pays Bob $10”, “Jeff pays Alex $5”, then “Bob pays Jeff $100”

While everyone else’s blockchain would look like this since nobody heard the new transaction on Jeff’s paper: “Alex pays Bob $10” and “Jeff pays Alex $5”.

Now, let’s say a new blockchain is shouted out (the one that everyone else has except for Jeff): “Alex pays Bob $10”, “Jeff pays Alex $5”, “Charlie pays Bob $15”.

Now Jeff has two different blockchains, so which is the “official” blockchain? Since there is a tie, Jeff simply waits for one to become longer. Now, Bob could keep whispering transactions to Jeff but he has to keep up with literally everyone else in the bar.

Say there’s 30 people in the bar. If one person (Bob) can whisper one transaction in one second, then the other 29 can shout 29 transactions in one second too. It’s impossible for Bob to keep his paper as the longest one in Jeff’s hands, if he’s competing with 29 others. After one second, Jeff looks at Bob’s blockchain and the 29 other people’s blockchain.

Bob’s would look like: “Alex pays Bob $10”, “Jeff pays Alex $5”, “Bob pays Jeff $100” while everyone else’s would look like: “Alex pays Bob $10”, “Jeff pays Alex $5”, “Bob pays Jeff $100”, “Charlie pays Bob $15”, “Alex pays Jeff $6”, “Bob pays Alex $25”, “Jeff pays Bob $13.32”, and so on for another 26 transactions. Which one is longer? Not Bob’s for sure. And eventually Jeff may just stop listening to Bob since he trusts everyone else more since they’re giving him a longer blockchain.

We’re still not done here though. One more thing.

Let’s say that Bob supposedly borrow $1000 from Jeff but what if Bob doesn’t have $1000? In the physical world, this wouldn’t be a problem but over in the digital world, if the blockchain says that Bob has to pay Jeff $1000, the transaction will be executed and Jeff will recieve money that never existed. We never implemented a system that checks whether a transaction is actually valid or not. So first of all: No overspending. Bob can’t pay $1000 (money that he doesn’t have) to Jeff.

Secondly, instead of directly shouting out your transactions to the other paper holders, you can shout them out to miners or nodes. These miners will verify all of the information that they receive through a process called proof of work (or some other consensus mechanism) and then relay all the valid transactions to the paper holders so they can write it down. You can find a more detailed explanation of this here.

This ensures that no invalid or suspicious transactions will slip through and be recorded.

The Programming

So how do these blockchain wizards do it? And how could you make one too?

Verifying Transactions With ECDSA

If you remember, ECDSA (Elliptic Curve Digital Signature Algorithm) is how blockchains verify the integrity of transactions and prevent tampering.

ECDSA’s (and elliptic curves in general) code and mathematics are wayyyyyyyyyyy + 10 more Ys, way too complicated to explain in this article, even for me! They could probably even have their own article or two. But here’s a (very) detailed but simple walkthrough of how ECDSA secp256k1 works with some more code examples. Here

But basically, your secret key is multiplied by a point on the curve, to generate your public key. A special type of multiplication for elliptic curves is used called point multiplication and unlike normal multiplication, there is no such thing as point division. So it is impossible to divide the public key by said point to get the private key since there is no such thing as dividing.

But here’s a more simplified version of ECDSA, keys and transactions written in python:

from ellipticcurve.ecdsa import Ecdsa
from ellipticcurve.privateKey import PrivateKey

def createTxn(sender, reciever, amount): # create new transaction
return f"{sender} pays {reciever} ${amount}"

message = createTxn("Bob","Jeff",50) # Output > "Bob pays Jeff $50"

# ------- keys --------
bobPrivateKey = PrivateKey()
bobPublicKey = bobPrivateKey.publicKey()

signature = Ecdsa.sign(message, bobPrivateKey)

# check whether the signature is valid:
# - message not tampered with
# - correct private key used
print(Ecdsa.verify(message, signature, bobPublicKey))

Output:
> True

And if we change up the private key or use an incorrect private key:

from ellipticcurve.ecdsa import Ecdsa
from ellipticcurve.privateKey import PrivateKey

def createTxn(sender, reciever, amount): # create new transaction
return f"{sender} pays {reciever} ${amount}"

message = createTxn("Bob","Jeff",50) # Output > "Bob pays Jeff $50"

# ------- keys --------
bobPrivateKey = PrivateKey()
bobPublicKey = bobPrivateKey.publicKey()

randomPrivateKey = PrivateKey() #<--- random invalid key

signature = Ecdsa.sign(message, randomPrivateKey)
# made with incorrect private key ↑↑

# ↓↓ message was tampered with
print(Ecdsa.verify("Bob pays Jeff $9999", signature, bobPublicKey))

Output:
> False

Pro Tip: If you want to look at the inside of the Ecdsa and PrivateKey modules you can write import inspect then print(inspect.getsource(Ecdsa)) to view the code inside of the modules.

Broadcast the Transactions

Here is an example code snippet of how one might create a broadcasting system.

# note that this snippet of code is seperate from the other one
# bc for blockchain
instances = []
class Person():
def __init__(self):
self.bc = []
instances.append(self)

#generate people in the bar
bob = Person()
jeff = Person()
alex = Person()

def createTxn(sender, reciever, amount): # create new transaction
return f"{sender} pays {reciever} ${amount}"

txn1 = createTxn("Bob","Jeff","50") # Output > "Bob pays Jeff 50"

def broadcast(txn):
print(txn) # broadcast the txn

# assuming everyone adds the txn to their bc
for person in instances:
person.bc.append(txn) # append the txn to everyone's bc

broadcast(txn1)

# view everyone's updated blockchain
for person in instances:
print(person.bc)

Output:
> Bob pays Jeff $50
> ['Bob pays Jeff $50']
> ['Bob pays Jeff $50']
> ['Bob pays Jeff $50']

And we can see that if someone broadcasts the transaction, (assuming that) everyone’s blockchain now has the new one added to it.

Finally, we have our blockchain, and everyone at the bar is happy, except for Charlie because he’s now a hundred dollars behind on his rent payment.

¯\_(ツ)_/¯

--

--

No responses yet