Cryptocurrency Mining and How It Works

Alexey ErmishkinAugust 17th, 2018

In this blog, we’re going to explain the concept of “mining” – the way that people make money by contributing to the computer systems that run cryptocurrencies. To understand, we’ll look at a fictitious miner named Matthew and his fictitious cryptocurrency MattCoin.

But first, why is it called “mining?” Just like there are scarce nuggets of gold hidden inside rock, there is a predetermined number of coins set by each cryptocurrency network, and each coin can only be extracted by people (known as “miners”) who validate transaction data that record the coins being sent to and from on the blockchain and then discover the missing inputs to complicated math problems attached to each transaction.

What’s innovative about this structure is that people are rewarded for contributing to the network infrastructure in a way that they currently aren’t with today’s Internet. The decentralization of network operations is one of the fundamental differences between Web 2.0 and Web 3.0. And mining is at the core of it all.

So what does this mean for Matthew and Mattcoin?

First, let’s review the definitions of a few important terms:

  •       Block: The fundamental building block of a cryptocurrency that holds the transaction list + wallet number + magic number (which we’ll define later).
  •       Blockchain: A network comprised of a sequence of blocks where each block contains the ID of the previous block, therefore a literal chain of blocks holding network data.
  •       Confirmation: Before a transaction is officially included in a new block on the network, it needs to be verified and confirmed as legitimate. This is done by miners.
  •       Transaction: This is a record of the amount that is transferred into or out of an individual wallet, along with the time and date of the transfer. The hash of this record is signed by the sender’s private key and is sent around to everyone in the cryptocurrency network for validation and inclusion in a block on the network.
  •       Wallet: Each wallet consists of a pair of randomly generated public and private keys used to send and receive cryptocurrencies and to keep a ledger of a user’s cryptocurrency transactions. The wallet’s address is a hash from the public key, which allows it to be uniquely identified.

How MattCoin Works:

Our imaginary miner Matthew has decided to launch his own cryptocurrency called MattCoin. Since this currency has no dedicated servers, everyone who participates in it has an equal right to validate a transaction. Therefore, we need a mechanism to ensure that transactions are irreversible (so that participants cannot edit transactions after the fact) and that any participant is able to verify a transaction’s validity without needing special access or information (which would corrupt the decentralized nature of the cryptocurrency).

Until the very first block is created, we don’t have any transactions. Therefore, we don’t have the number of the previous block which will come into play later. Nothing really exists except the address of Matthew’s wallet and the timestamp.

To create a unit of measurement within the mining process, the MattCoin algorithm stipulates that a new block should be created every 10 minutes. However, this interval can change based on the pace of block creation within the network. If miners are able to create too many blocks within that 10 minute window, then the complexity of the algorithms needed to generate a new block will be adjusted. On MattCoin, this recalculation takes place each time 100 more blocks are generated. When a miner creates a valid block, he or she is entitled to a reward of 50 MattCoins plus a commission, which we’ll dive into more detail on below.

Speed Limit

The miners are verifying the transactions happening on the MattCoin network, which is incredibly important because the currency is completely digital and has no other data source to refer against. The miners should be rewarded for adding this value to the MattCoin network, and that’s why they’re given 50 MattCoins for each block that they “close” plus a commission for each transaction that they successfully verify. But we have to keep an eye on the complexity of the blocks and the speed with which they are built. The blocks need to contain complex algorithms to verify each aspect of the transaction in question but be simple enough to encourage participation by miners. Otherwise, tons of blocks could be created out of thin air, and they wouldn’t have any value. The time and energy that goes into mining one MattCoin establishes the value of the currency on the blockchain. The more time is takes to mine a MattCoin, the more valuable one MattCoin needs to be.

Math Makes it Work

So how exactly does a miner solve these complicated math problems? This is where cryptography comes in.

“Hashes” are special cryptographic functions that are fixed-length arrays of bytes that are like mathematically-generated scrambles of the given inputs. Each block has a corresponding hash that needs to be solved by the miners.

A hash cannot be reverse engineered and is impossible to guess, but it still uniquely corresponds to the set of data from which it’s been calculated. In cryptocurrencies, inputs are concatenates (certain data from different sources linked together in a chain) of the transaction data and a piece of data called “nonce.” Miners have to attempt lots of guesses for what the nonce is until they find one that will generate a winning hash when combined together with the transaction data.

In the case of MattCoin, the hashes are represented by a number between 0-1000. In order for a miner to successfully close a block and win the reward, Matthew (as the creator of MattCoin) determined that a hash has to be less than 500.

Solving for a correct hash involves lots of computer power, so many miners set up their systems in locations with cool weather to offset the heat generated by the computers and cheap electricity to power the computers efficiently.

You can compare the hashes, add them, subtract them and so on. For everyone to recognize the block as valid, its hash must be less than the maximum possible, minus the value defined by all, and this is called the complexity.

For example, we have a hash of four bytes, with a maximum possible value of FFFFFFFF[16] . And the complexity, for example, is 100[10]. When you subtract one from the other, it turns out that our hash should be less than FFFFFF9B[16].

Survival of the Fastest

If you remember, all the blocks consist of several fields. We take these fields, concatenate them (link them together into a chain) and obtain a byte array. We put this byte array into a hash function, check the result and then ask: Is the hash less than maximum value minus complexity, or not? If not, we change the byte array until we get the desired value.

Here are some further specifics:

In each block, there is a field called nonce. This number is made up of several bytes, and it must be increased by adding one unit at a time onto the block, and then again counted as a hash.

Thus, if we have two chains:

A: Block1-> Block2-> Block3

B: Block1-> Block2-> Block3

then the one for which the fourth block is found soonest will win. The shorter chain is thrown out and its transactions are dropped back into the queue for confirmation and the chain with the greatest number of blocks “wins.”

What Motivates Miners

When sending or receiving MattCoin or any other cryptocurrency, a user will see a “commission” field in their wallet. This commission goes to the miners involved in generating blocks. These people will look at all the transactions awaiting confirmation and first choose those that contain a commission. After the block is formed, the entire commission that was contained in those transactions will be paid to the block’s creator.

Thus, when the reward for generating the block is completed (if it is written into the currency algorithm), then the miners will receive a commission. Free transactions are never processed because there’s no incentive to do so. Again, this is a fundamental distinction of a blockchain system like MattCoin.

Let’s test what we’ve learned by attempting to generate some MattCoins for Matthew.

The program generates two random key pairs (each with one public and private key) and when a user sends MattCoin to another user, a transaction is generated that needs to be verified by a miner like Matthew.

The transaction is signed using the keys, so everything is done honestly.

Then the MattCoin system looks for nonce, such that the first two bytes of the hash are zero. This is its type of difficulty.

It works for a couple of minutes and then it produces a hash, which can be quickly checked by concatenating transaction bytes and counters.

Program Code

package com.paranoim.money;

import java.math.BigInteger;
import java.util.Arrays;

import junit.framework.TestCase;

import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.util.Pack;
import org.bouncycastle.math.ec.ECPoint;

import com.paranoim.TestsAll;
import com.paranoim.crypto.assymetric.ECDSA;
import com.paranoim.crypto.digest.SHA3_512;
import com.paranoim.crypto.utils.ByteUtils;

public class MiningTest extends TestCase
{

    
    private byte[] counter = new byte[4];

    private byte[] getAddressFromPublicKey(ECPublicKeyParameters publicKey)
    {
        ECPoint q = publicKey.getQ();
        byte[] encoded = q.getEncoded(true);
        return SHA3_512.process(encoded); // reciever's address is it's pubkic key hash
    }
    
    public void testMining()
    {
        ECPublicKeyParameters fromKey = (ECPublicKeyParameters) TestsAll.ALICE.getPublic();
        ECPublicKeyParameters toKey = (ECPublicKeyParameters) TestsAll.BOB.getPublic();
        
        
        byte[] from = getAddressFromPublicKey(fromKey);
        byte[] to = getAddressFromPublicKey(toKey);
        
        int amount = 100; //100 HabraCoin
        long now = System.currentTimeMillis();
        
        //compose the message for signing
        
        byte[] fromTo = ByteUtils.concat(from, to);
        
        byte[] bAmount = Pack.intToBigEndian(amount);
        byte[] bTime = Pack.longToBigEndian(now);
        
        byte[] amountAndTime = ByteUtils.concat(bAmount, bTime);
        
        byte[] msg = ByteUtils.concat(fromTo, amountAndTime);
        
        BigInteger[] sigCoords = ECDSA.signDigest(TestsAll.ALICE.getPrivate(), SHA3_512.process(msg));
        byte[] signature = ByteUtils.concat(sigCoords[0].toByteArray(), sigCoords[1].toByteArray());
        
        // MSG contains from, to, amount, time and signature
        msg = ByteUtils.concat(msg, signature); 
        
        
        ECPublicKeyParameters minersKey = (ECPublicKeyParameters) TestsAll.ALICE1.getPublic();
        byte[] bminersKey = getAddressFromPublicKey(minersKey);
        
        //msg = msg + miner's address
        msg = ByteUtils.concat(msg, bminersKey);
        
        byte[] hash = doTheMining(msg);
        
        msg = ByteUtils.concat(msg, counter);
        
        assertTrue(Arrays.equals(hash, SHA3_512.process(msg)));
                
    }

    private byte[] doTheMining(byte[] msg)
    {
        byte[] hash = SHA3_512.process(ByteUtils.concat(msg, counter));
        
        while(hash[0] != 0 || hash[1] != 0 )
        {
            incrementCounter();
            hash = SHA3_512.process(ByteUtils.concat(msg, counter));
        }
        
        return hash;
    }
    
    private  void incrementCounter()
    {
        for (int i = 0; i < counter .length; i++)
        {
            counter[i]++;
            if (counter[i] != 0)
                break;
        }
    }
}

An example of the resulting block:

1824B9ADF09908222CF65069FDE226D32F165B3CF71B7AA0039FDFEF75EAA61610909EBFFBAC023480FC87FCF640C4A
009B82C4A6D25A0F4B8A732AE54EF733E792681137BA378577DFDC2732D192DAF323966EAD4ADC9635D7A12EDD50E34
9F660622D186AF3C03BF7D265F2AA7EB125056F4BF45BE519E8B22B845B28065110000006400000142E5D667CB01CEE
EDD0AC15EC4C491819A99030BD5FEF7CD2B469F2B90BA13D7981EDCD0708353D13390B8564F496C44FAC2777B0AF79D
C94CBF36D0CC0F047E807889F34C4DC5FEB724699C257391F84F3DDD70B84F841D115F4EFEAF4E58779042F35257E5C
035046037DE740718D199A8F06AD7A58E37CCCD4CC5E95295DCC2C5F3C70847BD59FA57BCC5FF4B208F93948FCFD763
EC1E5C85B61C43EB64B77A9F53B28785D7DE2335333003260A0839D53927976751A8D8967B2BB325909D86E82BC4125
2A28ECF6F0E7476BB99B29585EB0E75410000

And here’s the hash for it:

000008ACF935A8E3E453AC538706F560155943C6B0A77E5F5FCA7939D5FFE589676A6B3CD7AC78845786C50449D1A6F
91003EDCA7B5D8B12AC36CCA36A00844A

So, that’s how we earned couple of coins for Matthew.

Now you should have a basic knowledge of how and why mining works. It’s a self-adjustable system that makes miners calculate more and more hashes as difficulty grows. That’s why they need more power and special devices that can efficiently hash data over and over again.

This article only provides an introductory overview, so we invite your comments and questions. Join our Slack community to start a conversation.

Alexey Ermishkin is Chief Product Security Officer at Virgil Security and co-author of the NoiseSocket Protocol

Originally posted on habr.ru

Virgil Security, Inc. enables developers to eliminate passwords & encrypt everything, in hours, without having to become security experts. Get started today at VirgilSecurity.com.

Previous
Faces of Virgil Security – Dmytro Matviiv
Rebecca YarbroughAugust 10th, 2018