Creating a cryptocurrency
Tags: bitcoin, cryptocurrency
Published: 2022-05-18 15:17:42

Bitcoin is one of the most well-known and widespread cryptocurrencies today. Whether we know how it works or not, we have all heard of Bitcoin. However, there are many others currencies, which are based on the same basic principles. Therefore, to explain cryptocurrencies, let's see what these principles are.

## Creating a cryptocurrency

Suppose we want to create a cryptocurrency, _**DGIIMCoin**_. The first question would be what for, and the second - in case the 'what for' has convinced us - is what we need for it.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e37z3708b7yj9f4ubzwl.png">
  <figcaption>A possible logo for our cryptocurrency</figcaption>
</figure>

> The name _DGIIMCoin_ comes from the University degree I studied, the Double Degree in Computer Engineering and Mathematics, at the University of Granada. This publication is based on an exhibition that me and a colleague, Pedro, did together for the subject Network Fundamentals. Well, now we are all in the same line. ;)

Creating all this would make sense if we want to create an anonymous, decentralized and secure system to exchange money or information. Let's take a good look at what this means:

- **Anonymous:** users must be identifiable to the system, but their identity must be guarded with suspicion.
- **Decentralized:** conventional systems place the trust of institutions in third parties - e.g. Amazon in the shipment of goods, a bank, etc. - in the case of cryptocurrencies their status is maintained thanks to the consensus of the users.
- **Secure:** the system does not allow fraudulent transactions.

Well, for all this our system should have a number of requirements:

1. The system does not require a central authority: its state is maintained by a distributed consensus.
2. The system keeps track of all cryptocurrency units and their owners.
3. The system defines whether new units of the cryptocurrency can be created. If so, the system must define the circumstances of their origin and how to determine who will own them.
4. The ownership of the coins can be proven using only cryptography.
5. The system allows transactions to be carried out in a controlled manner.

Our system will therefore revolve around the following key ideas:

- Decentralization.
- Digital signatures.
- The ledger is the currency itself.
- Consensus mechanisms.
- Blockchain.

Next, we will explain each one of them.

- - -

## Decentralization: P2P networks

In order to meet the first two requirements of our list, thus eliminating centralized authorities, we already have a solution available: peer-to-peer networks, or P2P networks.

A _**peer-to-peer**_ (P2P) network is a network of nodes in which all or some aspects operate without fixed clients or servers, with each node acting simultaneously as client and server for all other nodes in the network. P2P networks allow the direct exchange of information, in any format, between interconnected computers.
Peer-to-peer networks leverage, manage and optimize the bandwidth usage of the other network users through connectivity between them, and thus obtain higher performance in connections and transfers compared to some conventional centralized methods, where a relatively small number of servers provide the total bandwidth of the network.

These networks are very scalable, since as more nodes are connected, the overall performance incrases (as opposed to client-server networks, where adding clients produces overhead). Apart from this, it allows for cost distribution and anonymity. But, above all, these networks are the best way to implement the decentralization we need.

There are various topologies of P2P networks, but ideally our system should have a distributed (also called "decentralized and unstructured") structure.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3qwiidaxb7q25ihutev.png">
  <figcaption>P2P network topologies (from left to right): centralized, decentralized and structured, decentralized and unstructured</figcaption>
</figure>

Using the existing protocols in P2P networks we will be able to implement _DGIIMCoin_. Excellent, let's continue.

## Digital signatures, cryptography and hashing

For our system to work, **digital identities** will be essential, i.e. ways to verify that a transaction has actually been made (someone has actually sent money to someone else). For that, we use **cryptography**.

### Hash functions

Specifically, we will need a hashing algorithm. Essentially, a **hash function** is a function that, given an input of an arbitrary size, gives an output of fixed size, and unreadable.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkfpg9hdxkizax4jcng7.png">
  <figcaption>A good hash function should make your message unrecognizable!</figcaption>
</figure>

A good hash function must guarantee:

1. The output of the hash function must have a fixed size (for example, in the case of SHA256 the size is 256 bits).
2. A minimal change in the input must produce a huge change in the output.
3. The same input will always produce the same output.
4. There must be no way to reverse the change, i.e. from the output the input can be found.
5. Calculating the hash value should be fast; it should not require a great deal of computational work.

It is important to mention that, although the number of possible hash values is limited, collisions are very unlikely, and even if one were to occur, it would be impossible to find the pattern that such collisions follow.

### Digital signatures

However, these functions are especially important when it comes to guaranteeing that transactions in the system are true. Hash functions are used by cryptographic algorithms that guarantee the veracity of transactions.

To make sure that no one can make a transaction on your behalf, we will use the concept of **digital signature**. This is best done using the **private key-public key method**, also called **asymmetric cryptography**.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygnubw9un1z8qaotwdbq.png">
  <figcaption>Summary diagram of asymmetric cryptography: on the left, the signing process; on the right, the verification process</figcaption>
</figure>

Each user will have such a set of keys, each of which will be a particular set of bits.

We will make sure that no one has access to our private key. To produce a signature, we will use the following function:

{% katex %}  Sign(\textbf{Message}, \textbf{Private Key}) = \textbf{Signature} {% endkatex %}

That it depends on the private key means that you are the only one able to sign, and that it also depends on the message ensures that messages cannot be modified once signed, because the result of this function would be radically different. To check, it is enough to use the public key, because it has a relationship with the private key.

{% katex %} Verify(\textbf{Message}, \textbf{Signature}, \textbf{Public Key}) {% endkatex %}

## Sending transactions to the network

We are almost there. We have implemented P2P communication, mechanisms to create digital identities and ways for users to sign and guarantee that the information is correct. Now all that's left is to send information to the system.

As we already know, we don't have a central authority to validate how much money we have, but we don't need to: here lies one of the ideas, that the accounting is the currency itself. This is because to know how much money we have, we simply need to have a list of all the transactions we have made.
we have made. Let's assume that your transaction history contains the information:

> **Example.** _List of transactions of a user in DGIIMCoin_
1. I have 500 coins.
2. I send 20 coins to someone for some Computer Modeling notes (we will include their public key).
3. I want to send 1 coin as transaction tax to the system (we will see it later).

The only thing left is to use the P2P network to send these transactions to the rest of the system users, not forgetting to sign them using our private key. After this, everyone will be able to see the transaction (although the identities of both will be encrypted).

That's it. However, you will not have the notes until the network agrees that you initially had 500 coins, and therefore the transaction can take place. Once the transaction is validated, your partner will give you the notes.

## Blockchain

In order to maintain our system we need to have a history of the transactions that have been made. For this, we use **blockchain** technology, which is essentially a set of blocks containing information (which we will see later), which are linked using cryptography: each block has a hash of the previous block, as well as metadata of its creation.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3csm8im58080gl5up9yg.png">
  <figcaption>Blockchain links the blocks by keeping in its header a hash to the previous block</figcaption>
</figure>

This is precisely what makes our public ledger resistant to modifications: the alteration of one block invalidates all subsequent blocks. Although it is possible to make these alterations, this technology is secure and tolerant to [Byzantine faults](https://en.wikipedia.org/wiki/Byzantine_fault).

### The blocks

Blocks contain a set of transactions that are hashed and encoded in a [**Merkle tree**](https://en.wikipedia.org/wiki/Merkle_tree) (the data structure that maintains the links between blocks by hash functions).

Sometimes two blocks can be created concurrently, generating a temporary _fork_. Because of this, we will need a way to "score" different versions, so that one with a higher score can be selected before the rest. Blocks not selected for inclusion are so-called **orphan blocks**.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/750sjhmziaqoyrbv7ud7.png">
  <figcaption>Example of a blockchain with various _forks_</figcaption>
</figure>

## Transaction verification algorithms: _mining_

Well, since we have mechanisms to generate and store transactions in a decentralized way, we are missing the **trust** factor: how do we know that a transaction is true?

Let's suppose the following situation: María has to pay 100 coins to Jorge, and in fact she has the money available, but she wants to cheat Jorge by making him believe that she has indeed paid him, sending this transaction to Jorge, but not to the rest of the users of our system. For Jorge, María will have settled her debts with him, while in reality Jorge will never have that money.

To avoid this, it is necessary to establish a system by which a criterion can be established to discern which block of our blockchain is more correct. We should, therefore, implement at this time an authentication mechanism supported by the collective interest.

In our blockchain there are some particularly outstanding actors, who provide an essential functionality for the proper functioning of our cryptocurrency. These are the miners, who are in charge of creating new blocks where transactions can be stored. These miners are nothing more than a user of our cryptocurrency who create blocks, using various methods, such as computing mathematical problems.

But, wait a second, _a mathematical problem in a block?_ Indeed, as we discussed earlier, we have a SHA-256 hash function (in the case of Bitcoin), which has as output a number of 256 bits, i.e., 2²⁵⁶ results can be generated. And this is where the mathematical problem arises:

> Find a number that, when entered into the hash function along with the data of the block you want to create, the result is a number that starts with many 0's.

Our miners will try to solve this problem and the number of the miner who gets the most zeros will be chosen. It should be noted that due to the nature of hash functions this problem requires a lot of computational work (unless you are very lucky), a lot of trial and error.

But what motivation do these miners have to work on forming blocks and not corrupting them?

Let's think of a way to benefit those who volunteer to grow the community. We will get various schemes for this, and thereby make the blockchain work independently, securely, transparently and democratically. It also rewards miners with the same cryptocurrencies and encourages them to continue mining cryptocurrencies and to do it honestly.

### Proof-of-work (PoW)

The **proof-of-work (PoW)** scheme is an algorithm that rewards participants who solve cryptographic puzzles to validate transactions and create new blocks. This is the scheme Bitcoin uses. _Those miners who have more computational power working at the disposal of the system are more likely to solve the puzzles._ Hence the name of the system, as it gives priority to those who work the hardest.

In this scheme, miners compete to solve the puzzles to create new blocks of the blockchain, in the case of Bitcoin every 10 minutes. The miners who invest more work in creating the blocks are more likely to find the answer and will be rewarded with cryptocurrencies.

One of the biggest disadvantages of PoW is that it wastes a lot of energy, as the work of all the miners who tried to find the correct answer but did not succeed is wasted.

### Proof-of-burn (PoB)

**Proof-of-burn (PoB)** is an algorithm similar to proof-of-work, but with reduced rates of energy consumption. The block validation process of PoB-based networks does not require the use of powerful computational resources and does not rely on powerful mining hardware (such as ASICs). Instead, cryptocurrencies are intentionally burned as a way of investing" resources in the blockchain, so candidate miners are not required to invest physical resources. In PoB systems, _miners invest in virtual mining platforms_ (or virtual mining power).


In other words, by performing coin burns, users can demonstrate their commitment to the network, obtain the right to "mine" and validate transactions. Since the process of burning coins represents virtual mining power, the more coins a user burns in favor of the system, the more mining power he/she has, and therefore the greater the chances of being chosen as the next block validator.

In short, the process of burning coins consists of sending them to a verifiable audience where they become inaccessible and useless. Typically, these addresses (also known as [_eater addresses_](https://www.blockchain.com/btc/address/1BitcoinEaterAddressDontSendf59kuE)) are randomly generated without having any private key associated with them.

Naturally, the process of burning coins reduces market availability and creates economic scarcity, causing a potential increase in their value. But more than that, coin burning is another way to invest in network security.

### Proof-of-stake (PoS)

**Proof-of-stake (PoS)** is a type of consensus algorithm that relies on the economic participation of a validator in the network. _The importance of this system centers on the ownership of the currency in question._ It does not require labor or computational power, rather it requires owning the cryptocurrency.

Having cryptocurrencies in the digital wallet is what reflects the participation of the users and _the users who have more cryptocurrencies in their account for a longer time have more power in the cryptocurrency_.

The more cryptocurrencies the users hold, the more mining power they have to validate the blockchain blocks and therefore the more cryptocurrencies they will receive as a reward. It is a system that does not waste as much energy as PoW.

However, if a user pledges their cryptocurrencies as proof of participation, then they cannot spend them on other things, therefore, a drawback of this system is that it could inhibit trading with mined cryptocurrencies.

### Proof-of-elapsed time (PoET)

In the case of **proof-of-elapsed time (PoET)**, the algorithm is based on the principle of a fair lottery system, where each node has the same probability of winning. The PoET mechanism is based on distributing the chances of winning fairly among the largest number of participants in the network.

The operation of the PoET algorithm is as follows:

> **Algorithm.** _PoET algorithm_
1. Each participating node in the network is required to wait for a randomly chosen period of time, and the first to complete the designated waiting time wins the new block.
2. Each node in the blockchain network generates a random timeout and goes to sleep for that specified duration.
3. The node with the shortest waiting time wakes up and sends a new block to the blockchain, transmitting the necessary information to the entire peer-to-peer network.
4. The same process is repeated for the discovery of the next block.

### Proof-of-importance (PoI)

**Proof-of-importance (PoI)** gives priority to miners with the best reputation in the system. Reputation is measured by the amount of money invested, the number of transactions made and the amount transferred in those transactions. The reputation of the accounts with which the exchanges are made is also taken into account. This is the system used for the NEM cryptocurrency.

Therefore, if María wanted to create a fraudulent block to scam Jorge, she would have to continue with her lie indefinitely, something that is almost impossible, since to do so she would have to match her computational capacity to that of the rest of the miners.

## Controlling the source of cash

Now, where does the money come from in this type of system? After most cryptocurrencies, the idea is that more money is generated as there is more work, that is, as there are more packages and more miners. This money is generated as a reward for the miners' work, as we have explained before.

A particular case is Bitcoin, where there is an upper limit of 21 million bitcoins. That number has not yet been reached, and it is estimated that, at the current rate, we will reach it in the year 2140.

This limit will not be exceeded, however, because the reward for miners is decreasing as there is more money in the system, becoming an absent reward.

This reward is calculated from three factors:

* **The money already present in the system:** as we get closer to 21 million bitcoins, the reward will get smaller and smaller.
* **The computational work of the miners:** the more miners work, the more complicated it is to reach the solution (see factor below). This is also taken into account when calculating the reward. In the case of other verification mechanisms, your criteria are taken into account.
* **The difficulty of mining:** Bitcoin accepts blocks every 10 minutes, and adjusts the difficulty (the number of base zeros) according to the number of miners there are, and the money on the platform.

Once we reach the limit, the importance will fall on transaction fees. Every time a user makes a transaction in Bitcoin, he or she can include a transaction fee, which the miner will get as a reward, thus incentivizing mining. In addition, because the number of transactions in a Bitcoin block is limited (it is not really the number of transactions that is measured, but the "weight" of each transaction), miners will insert the most profitable transactions for them into the blocks.

- - -

Well, with all these problems solved, we could now launch our cryptocurrency! Now, perhaps it is appropriate to see how we could implement it.

_Part 2 soon!_

### Sources

S. Nakamoto. _Bitcoin: A Peer-to-Peer Electronic Cash System_. <https://bitcoin.org/bitcoin.pdf>

D. Selmanovic. _Bitcoin and cryptocurrency algorithms implementation tutorial_, Toptal Developers. <https://www.toptal.com/bitcoin/cryptocurrency-for-dummies-bitcoin-and-beyond>

3Blue1Brown, _But how does Bitcoin actually work?_ <https://www.youtube.com/watch?v=bBC-nXj3Ng4>

Binance Academy, _Proof of Burn explained_. <https://www.binance.vision/es/blockchain/proof-of-burn-explained>

HackerNoon, _Proof of Work, Proof of Burn and Proof of Stake_. <https://hackernoon.com/proof-of-work-proof-of-stake-and-proof-of-burn-6823eac2776e>