How to Create Your Own Cryptocurrency Using Python

With the current rise of cryptocurrencies, blockchain is creating a buzz in the technology world. This technology has attracted so much attention mainly because of its ability to guarantee security, enforce decentralization, and quicken processes to several industries—especially to the financial industry.

basically, a blockchain is a public database that irreversibly documents and authenticates the possession and transmission of digital assets. Digital currencies, like Bitcoin and Ethereum, are based on this concept. Blockchain is an exciting technology that you can use to transform the capabilities of your applications. Of late, we ’ ve been seeing governments, organizations, and individuals using the blockchain engineering to create their own cryptocurrencies—and avoid being left behind. notably, when Facebook proposed its own cryptocurrency, called Libra, the announcement stirred many waters across the worldly concern. What if you could besides follow lawsuit and create your own interpretation of a cryptocurrency ? I thought about this and decided to develop an algorithm that creates a crypto.

I decided to call the cryptocurrency fccCoin. In this tutorial, I ’ megabyte going to illustrate the bit-by-bit process I used to build the digital currentness ( I used the object-oriented concepts of the Python program lyric ). hera is the basic blueprint of the blockchain algorithm for creating the fccCoin :

class Block:

    def __init__():

    #first block class

        pass
    
    def calculate_hash():
    
    #calculates the cryptographic hash of every block
        
    
class BlockChain:
    
    def __init__(self):
     # constructor method
    pass
    
    def construct_genesis(self):
        # constructs the initial block
        pass

    def construct_block(self, proof_no, prev_hash):
        # constructs a new block and adds it to the chain
        pass

    @staticmethod
    def check_validity():
        # checks whether the blockchain is valid
        pass

    def new_data(self, sender, recipient, quantity):
        # adds a new transaction to the data of the transactions
        pass

    @staticmethod
    def construct_proof_of_work(prev_proof):
        # protects the blockchain from attack
        pass
   
    @property
    def last_block(self):
        # returns the last block in the chain
        return self.chain[-1]

now, let me explain what is taking place…

1. Building the first Block class

A blockchain comprises of several blocks that are joined to each other ( that sounds familiar, right ? ). The chain of blocks takes invest such that if one block is tampered with, the stay of the chain becomes invalid. In applying the above concept, I created the follow initial blocking class :

import hashlib
import time

class Block:

    def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp or time.time()

    @property
    def calculate_hash(self):
        block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        return hashlib.sha256(block_of_string.encode()).hexdigest()

    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)

As you can see from the code above, I defined the __init__() function, which will be executed when the Block class is being initiated, barely like in any other Python classify. I provided the follow parameters to the trigger function :

  • self—this refers to the instance of the Block class, making it possible to access the methods and attributes associated with the class;
  • index—this keeps track of the position of the block within the blockchain;
  • proof_no—this is the number produced during the creation of a new block (called mining);
  • prev_hash—this refers to the hash of the previous block within the chain;
  • data—this gives a record of all transactions completed, such as the quantity bought;
  • timestamp—this places a timestamp for the transactions.

The second method acting in the class, calculate_hash, will generate the hashish of the blocks using the above values. The SHA-256 faculty is imported into the project to assist in obtaining the hashes of the blocks.
After the values have been inputted into the cryptanalytic hash algorithm, the function will return a 256-bit string representing the contents of the block.
This is how security is achieved in blockchains—every freeze will have a hash and that hash will rely on the hash of the previous engine block. As such, if person tries to compromise any jam in the chain, the other blocks will have disable hashes, leading to break of the entire blockchain network.
ultimately, a forget will look like this :

{
    "index": 2,
    "proof": 21,
    "prev_hash": "6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823",
    "transactions": [
        {'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}
    ],
    "timestamp": 1521646442.4096143
}

2. Building the Blockchain class

The independent estimate of a blockchain, precisely as the name implies, involves “ chaining ” several blocks to one another. consequently, I ’ meter going to construct a Blockchain class that will be useful in managing the workings of the whole chain. This is where most of the action is going to take rate. The Blockchain course will have respective helper methods for completing respective tasks in the blockchain. Let me explain the function of each of the methods in the class .

a. Constructor method

This method ensures the blockchain is instantiated .

class BlockChain:

    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()

here are the roles of its attributes :

  • self.chain—this variable keeps all blocks;
  • self.current_data—this variable keeps all the completed transactions in the block;
  • self.construct_genesis()—this method will take care of constructing the initial block.

b. Constructing the genesis block

The blockchain requires a construct_genesis method acting to build the initial forget in the chain. In the blockchain convention, this forget is extra because it symbolizes the beginning of the blockchain.
In this shell, let ’ s reconstruct it by plainly passing some default option values to the construct_block method. I gave both proof_no and prev_hash a prize of zero, although you can provide any respect you want.

def construct_genesis(self):
    self.construct_block(proof_no=0, prev_hash=0)


def construct_block(self, proof_no, prev_hash):
    block = Block(
        index=len(self.chain),
        proof_no=proof_no,
        prev_hash=prev_hash,
        data=self.current_data)
    self.current_data = []

    self.chain.append(block)
    return block

c. Constructing new blocks

The construct_block method acting is used for creating new blocks in the blockchain.

here is what is taking target with the versatile attributes of this method acting :

  • index—this represents the length of the blockchain;
  • proof_nor & prev_hash—the caller method passes them;
  • data—this contains a record of all the transactions that are not included in any block on the node;
  • self.current_data—this is used to reset the transaction list on the node. If a block has been constructed and the transactions allocated to it, the list is reset to ensure that future transactions are added into this list. And, this process will take place continuously;
  • self.chain.append()—this method joins newly constructed blocks to the chain;
  • return—lastly, a constructed block object is returned.

d. Checking validity

The check_validity method acting is important in assessing the integrity of the blockchain and ensuring anomalies are lacking.
As mentioned earlier, hashes are essential for the security system of the blockchain as even the slightest deepen in the object will lead to the generation of a completely newly hashish.
consequently, this check_validity method acting uses if statements to check whether the hashish of every block is correct.
It besides verifies if every blocking points to the right previous pulley, through comparing the rate of their hashes. If everything is decline, it returns true ; otherwise, it returns false.

@staticmethod
def check_validity(block, prev_block):
    if prev_block.index + 1 != block.index:
        return False

    elif prev_block.calculate_hash != block.prev_hash:
        return False

    elif not BlockChain.verifying_proof(block.proof_no, prev_block.proof_no):
        return False

    elif block.timestamp <= prev_block.timestamp:
        return False

    return True

e. Adding data of transactions

The new_data method is used for adding the data of transactions to a block. It ’ s a identical simple method : it accepts three parameters ( sender ’ second details, receiver ’ second details, and quantity ) and append the transaction data to self.current_data number.
Anytime a new block is created, this list is allocated to that obstruct and reset once more as explained in the construct_block method.
once the transaction data has been added to the list, the exponent of the following block to be created is returned.
This index is calculated by adding 1 to the exponent of the stream auction block ( which is the last in the blockchain ). The data will assist a user in submitting the transaction in future .

def new_data(self, sender, recipient, quantity):
    self.current_data.append({
        'sender': sender,
        'recipient': recipient,
        'quantity': quantity
    })
    return True

f. Adding proof of work

Proof of work is a concept that prevents the blockchain from abuse. Simply, its objective is to identify a number that solves a problem after a sealed amount of computing work is done. If the trouble level of identifying the number is high, it discourages spamming and tampering with the blockchain. In this case, we ’ ll practice a elementary algorithm that discourages people from mining blocks or creating blocks easily .

@staticmethod
def proof_of_work(last_proof):
    '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''
    proof_no = 0
    while BlockChain.verifying_proof(proof_no, last_proof) is False:
        proof_no += 1

    return proof_no


@staticmethod
def verifying_proof(last_proof, proof):
    #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?

    guess = f'{last_proof}{proof}'.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:4] == "0000"

g. Getting the last block

last, the latest_block method acting is a benefactor method that assists in obtaining the last forget in the blockchain. Remember that the death block is actually the current block in the chain .

@property
    def latest_block(self):
        return self.chain[-1]

Let’s sum everything together

here is the entire code for creating the fccCoin cryptocurrency. You can besides get the code on this GitHub repository .

import hashlib
import time


class Block:

    def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp or time.time()

    @property
    def calculate_hash(self):
        block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        return hashlib.sha256(block_of_string.encode()).hexdigest()

    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)


class BlockChain:

    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()

    def construct_genesis(self):
        self.construct_block(proof_no=0, prev_hash=0)

    def construct_block(self, proof_no, prev_hash):
        block = Block(
            index=len(self.chain),
            proof_no=proof_no,
            prev_hash=prev_hash,
            data=self.current_data)
        self.current_data = []

        self.chain.append(block)
        return block

    @staticmethod
    def check_validity(block, prev_block):
        if prev_block.index + 1 != block.index:
            return False

        elif prev_block.calculate_hash != block.prev_hash:
            return False

        elif not BlockChain.verifying_proof(block.proof_no,
                                            prev_block.proof_no):
            return False

        elif block.timestamp <= prev_block.timestamp:
            return False

        return True

    def new_data(self, sender, recipient, quantity):
        self.current_data.append({
            'sender': sender,
            'recipient': recipient,
            'quantity': quantity
        })
        return True

    @staticmethod
    def proof_of_work(last_proof):
        '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''
        proof_no = 0
        while BlockChain.verifying_proof(proof_no, last_proof) is False:
            proof_no += 1

        return proof_no

    @staticmethod
    def verifying_proof(last_proof, proof):
        #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?

        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

    @property
    def latest_block(self):
        return self.chain[-1]

    def block_mining(self, details_miner):

        self.new_data(
            sender="0",  #it implies that this node has created a new block
            receiver=details_miner,
            quantity=
            1,  #creating a new block (or identifying the proof number) is awarded with 1
        )

        last_block = self.latest_block

        last_proof_no = last_block.proof_no
        proof_no = self.proof_of_work(last_proof_no)

        last_hash = last_block.calculate_hash
        block = self.construct_block(proof_no, last_hash)

        return vars(block)

    def create_node(self, address):
        self.nodes.add(address)
        return True

    @staticmethod
    def obtain_block_object(block_data):
        #obtains block object from the block data

        return Block(
            block_data['index'],
            block_data['proof_no'],
            block_data['prev_hash'],
            block_data['data'],
            timestamp=block_data['timestamp'])

now, let ’ s test our code to see if it works .

blockchain = BlockChain()

print("***Mining fccCoin about to start***")
print(blockchain.chain)

last_block = blockchain.latest_block
last_proof_no = last_block.proof_no
proof_no = blockchain.proof_of_work(last_proof_no)

blockchain.new_data(
    sender="0",  #it implies that this node has created a new block
    recipient="Quincy Larson",  #let's send Quincy some coins!
    quantity=
    1,  #creating a new block (or identifying the proof number) is awarded with 1
)

last_hash = last_block.calculate_hash
block = blockchain.construct_block(proof_no, last_hash)

print("***Mining fccCoin has been successful***")
print(blockchain.chain)

It worked ! here is the output of the mine work :

***Mining fccCoin about to start***
[0 - 0 - 0 - [] - 1566930640.2707076]
***Mining fccCoin has been successful***
[0 - 0 - 0 - [] - 1566930640.2707076, 1 - 88914 - a8d45cb77cddeac750a9439d629f394da442672e56edfe05827b5e41f4ba0138 - [{'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}] - 1566930640.5363243]

Conclusion

There you have it ! That ’ s how you could create your own blockchain using Python. Let me say that this tutorial precisely demonstrates the basic concepts for getting your feet wet in the innovative blockchain engineering. If this coin were deployed as-is, it could not meet the confront grocery store demands for a stable, secure, and easy-to-use cryptocurrency. consequently, it can still be improved by adding extra features to enhance its capabilities for mining and sending fiscal transactions.

however, it ’ s a good start point if you decide to make your diagnose known in the amazing earth of cryptos. If you have any comments or questions, please post them below. felicitous ( crypto ) code !

source : https://coinselected
Category : coin 4u

Leave a Reply

Your email address will not be published.