Learn Blockchains by Building One, A simple Blockchain in Python using Flask as a micro web framework.

Overview

Blockchain

forthebadge forthebadge forthebadge

Learn Blockchains by Building One Yourself

Installation

  1. Make sure Python 3.6+ is installed.
  2. Install Flask Web Framework.
  3. Clone this repository
    $ git clone https://github.com/krvaibhaw/blockchain.git
  1. Change Directory
    $ cd blockchain
  1. Install requirements
    $ pip install requirements.txt
  1. Run the server:
    $ python blockchain.py 
  1. Head to the Web brouser and visit
    http://127.0.0.1:5000/

Introduction

Blockchain is a specific type of database. It differs from a typical database in the way it stores information; blockchains store data in blocks that are then chained together. As new data comes in it is entered into a fresh block. Once the block is filled with data it is chained onto the previous block, which makes the data chained together in chronological order. Different types of information can be stored on a blockchain but the most common use so far has been as a ledger for transactions.

What is Blockchain?

A blockchain is essentially a digital ledger of transactions that is duplicated and distributed across the entire network of computer systems on the blockchain. It is a growing list of records, called blocks, that are linked together using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data (generally represented as a Merkle tree). The timestamp proves that the transaction data existed when the block was published in order to get into its hash.

As blocks each contain information about the block previous to it (by cryptographic hash of the previous block), they form a chain, with each additional block reinforcing the ones before it. Therefore, blockchains are resistant to modification of their data because once recorded, the data in any given block cannot be altered retroactively without altering all subsequent blocks.

How does it works?

Blockchains are typically managed by a peer-to-peer network for use as a publicly distributed ledger, where nodes collectively adhere to a protocol to communicate and validate new blocks. Although blockchain records are not unalterable as forks are possible, blockchains may be considered secure by design and exemplify a distributed computing system with high Byzantine fault tolerance.

Why Blockchain?

  • Immutable: Blockchains are resistant to modification of their data because once recorded, the data in any given block cannot be altered retroactively without altering all subsequent blocks.

  • Decentralized: It doesn’t have any governing authority or a single person looking after the framework. Rather a group of nodes maintains the network making it decentralized. It means :

      -> Transparency
      -> User Control
      -> Less Prone to Breakdown
      -> Less chance of Failure.
      -> No Third-Party
    
  • Enhanced Security: If someone wants to corrupt the network, he/she would have to alter every data stored on every node in the network. There could be millions and millions of people, where everyone has the same copy of the ledger.

  • Distributed Ledgers: The ledger on the network is maintained by all other users on the system. This distributed computational power across the computers to ensure a better outcome. It ensures :

      -> No Malicious Changes
      -> Ownership of Verification
      -> Quick Response
      -> Managership
      -> No Extra Favors
    
  • Consensus: The architecture is cleverly designed, and consensus algorithms are at the core of this architecture. The consensus is a decision-making process for the group of nodes active on the network. The consensus is responsible for the network being trustless. Nodes might not trust each other, but they can trust the algorithms that run at the core of it. That’s why every decision on the network is a winning scenario for the blockchain.

  • True Traceability: With blockchain, the supply chain becomes more transparent than ever, as compared to traditional supply chain, where it is hard to trace items that can lead to multiple problems, including theft, counterfeit, and loss of goods.

Understanding the Program

Firstly, we defined the structure of our block, which contains, block index, timestamp of when it has been created, proof of work, along with previous hash i.e., the hash of previous block. In real case seanario along with these there are other contents such as a body or transaction list, etc.

    def createblock(self, proof, prevhash):
        
        # Defining the structure of our block
        block = {'index': len(self.chain) + 1,
                 'timestamp': str(datetime.datetime.now()),
                 'proof': proof,
                 'prevhash': prevhash}

        # Establishing a cryptographic link
        self.chain.append(block)
        return block

The genesis block is the first block in any blockchain-based protocol. It is the basis on which additional blocks are added to form a chain of blocks, hence the term blockchain. This block is sometimes referred to Block 0. Every block in a blockchain stores a reference to the previous block. In the case of Genesis Block, there is no previous block for reference.

    def __init__(self):
        
        self.chain = []
        
        # Creating the Genesis Block
        self.createblock(proof = 1, prevhash = "0")

Proof of Work(PoW) is the original consensus algorithm in a blockchain network. The algorithm is used to confirm the transaction and creates a new block to the chain. In this algorithm, minors (a group of people) compete against each other to complete the transaction on the network. The process of competing against each other is called mining. As soon as miners successfully created a valid block, he gets rewarded.

    def proofofwork(self, prevproof):
        newproof = 1
        checkproof = False

        # Defining crypto puzzle for the miners and iterating until able to mine it 
        while checkproof is False:
            op = hashlib.sha256(str(newproof**2 - prevproof**5).encode()).hexdigest()
            
            if op[:5] == "00000":
                checkproof = True
            else:
                newproof += 1
        
        return newproof

Chain validation is an important part of the blockchain, it is used to validate weather tha blockchain is valid or not. There are two checks performed.

First check, for each block check if the previous hash field is equal to the hash of the previous block i.e. to verify the cryptographic link.

Second check, to check if the proof of work for each block is valid according to problem defined in proofofwork() function i.e. to check if the correct block is mined or not.

    def ischainvalid(self, chain):
        prevblock = chain[0]   # Initilized to Genesis block
        blockindex = 1         # Initilized to Next block

        while blockindex < len(chain):

            # First Check : To verify the cryptographic link
            
            currentblock = chain[blockindex]
            if currentblock['prevhash'] != self.hash(prevblock):
                return False

            # Second Check : To check if the correct block is mined or not

            prevproof = prevblock['proof']
            currentproof = currentblock['proof']
            op = hashlib.sha256(str(currentproof**2 - prevproof**5).encode()).hexdigest()
            
            if op[:5] != "00000":
                return True

            prevblock = currentblock
            blockindex += 1

        return True

Feel free to follow along the code provided along with mentioned comments for
better understanding of the project, if any issues feel free to reach me out.

Contributing

Contributions are welcome!
Please feel free to submit a Pull Request.

Owner
Vaibhaw
A passionate thinker, techno freak, comic lover, a curious computer engineering student. Machine Learning, Artificial Intelligence, Linux, Web Development.
Vaibhaw
Audit of classmate's smart contract in blockchain seminar

Solidity-contract-audit Audit of classmate's smart contract in blockchain seminar Assignment: The task was to create a complete audit, including unit

smrza 0 Feb 04, 2022
Recover bitcon brainwallet

Bitcoin brainwallet recovery tool If you like it give it a star Programmed in Python | PySimpleGUI How it works From seed phrase create bitcoin privat

Adrijan 20 Dec 15, 2022
A Python implementation of CWT/COSE.

Python CWT - A Python implementation of CWT/COSE Python CWT is a CBOR Web Token (CWT) and CBOR Object Signing and Encryption (COSE) implementation com

Ajitomi Daisuke 13 Dec 14, 2022
Historical Crypto Price

Made with Coingecko API, this is a VERY simple python script that asks you the crypto, date and currency you want and then proceeds to give you the price and MarketCap at that precise moment

7 Oct 14, 2022
Django-based Crypto Portfolio Tracker – keep an eye on Shiba Inu and other Crypto

Crypto Tracker 🐍 📈 – Central Portfolio Tracking Easy asset tracking – at a glance 🚀 Dashboard to centrally monitor current crypto portfolio develop

65 Jan 08, 2023
Block Chain for RiceSupply Chain and Agriculture Traceability

Block Chain for RiceSupply Chain and Agriculture Traceability Project Under Development Folder: Building a BlockChain Basic blockchain structure using

Chandru S Raghavan 3 Jan 19, 2022
The Qis|krypt⟩ is a software suite of protocols of quantum cryptography and quantum communications

The Qis|krypt⟩ is a software suite of protocols of quantum cryptography and quantum communications, as well, other protocols and algorithms, built using IBM’s open-source Software Development Kit for

Qiskrypt 14 Oct 31, 2022
This is simple Blockchain ,miner and wallet to send crypto using python

pythonBlockchain-SImple This is simple Blockchain ,miner and wallet to send crypto using python It is simple Blocchain so it can only dobasic work usi

3 Nov 22, 2022
Looks for Bitcoin Wallets starting 1 compresses and Uncompressesed, segwit address and MultiSig starting 3.

Looks for Bitcoin Wallets starting 1 compresses and Uncompressesed, segwit address and MultiSig starting 3. Pick your starting and stop numbers to start looking. Need a database of addresses to check

10 Dec 22, 2022
Cyber Security Starter Kit Platform

Cyber Security Starter Kit Platform (CSSKP) allows to instantiate new self-assessment products such as Fit4Cybersecurity, Fit4Privacy, Fit4Contract and the like.

CASES Luxembourg 3 Oct 21, 2021
Get the SHA256 hash of any file with this Python Script

Hashfile-SHA256 A SHA256 hash verifying script, written in python. Report Bug Table of Contents About The Project Built With Getting Started Prerequis

Ethan Gallucci 1 Nov 01, 2021
Learn Blockchains by Building One, A simple Blockchain in Python using Flask as a micro web framework.

Blockchain ✨ Learn Blockchains by Building One Yourself Installation Make sure Python 3.6+ is installed. Install Flask Web Framework. Clone this repos

Vaibhaw 46 Jan 05, 2023
An encryption format offering better security, performance and ease of use than PGP.

An encryption format offering better security, performance and ease of use than PGP. File a bug if you found anything where we are worse than our competition, and we will fix it.

27 Dec 25, 2022
BOT para o BombCrypto para infinitas contas em simultâneo!!!

BOT - MultiContas para BombCrypto - v 0.4.0 Funções extras: Envios de notificações via Telegram: Aviso de Inicialização do Bot Aviso de Conclusão de M

Rai Zancanaro 19 Dec 20, 2022
Gold(Gold) is a modern cryptocurrency built from scratch, designed to be efficient, decentralized, and secure

gold-blockchain (Gold) Gold(Gold) is a modern cryptocurrency built from scratch, designed to be efficient, decentralized, and secure. Here are some of

zcomputerwiz 3 Mar 09, 2022
Use this script to track the gains of cryptocurrencies using historical data and display it on a super-imposed chart in order to find the highest performing cryptocurrencies historically

crypto-performance-tracker Use this script to track the gains of cryptocurrencies using historical data and display it on a super-imposed chart in ord

Andrei 25 Aug 31, 2022
Discord webhooks for alerting crypto currency price changes & historical data.

Crypto-Discord Discord Webhooks for alerting crypto currency price changes & historical data. Create virtual environment and install requirements. $ s

Филип Арсовски 1 Sep 02, 2022
Best blockchain in the world

alphachain Best blockchain in the world!!! Can be used to implement Layer 2 cryptocurrency protocol just click alphachain.py and it will execute autom

Niño Sison 0 Feb 18, 2022
Crypto-curriences analysis

Crypto_analysis Discription: simple streamlit(screener) app to make MMA and OSC analysis for cyrpto-currenices, and gives resaults for which coins are

13 Nov 01, 2021
theHasher Tool created for generate strong and unbreakable passwords by using Hash Functions.Generate Hashes and store them in txt files.Use the txt files as lists to execute Brute Force Attacks!

$theHasher theHasher is a Tool for generating hashes using some of the most Famous Hashes Functions ever created. You can save your hashes to correspo

SR18 6 Feb 02, 2022