Skip to content

Proof of Work Blockchain and Cryptocurrency Built using Python

License

Notifications You must be signed in to change notification settings

safesploitOrg/monoblockchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MonoBlockchain

MonoBlockchain is a decentralised proof of work blockchain with the backend written in Python.

The cryptocurrency individually is referred to as an MB Coin (Mono Block Coin).

Preview Video

MonoBlockchain Preview

Features

  • Immutable Ledger
  • Distributed P2P Network
  • Proof of Work (SHA-256)
  • Consensus Protocol
  • Easy to Use Transaction System
  • HTML User Interface
  • Developer Friendly:
    • API-Based Backend
    • Frameworks: Bootstrap, DataTables, FontAwesome, jQuery

Table of Contents

Setup and Usage

Python Version

$ python3.10
Python 3.10.5

Dependencies

Node (Server)

pip3.10 install Crypto \
                Flask \
                Flask_CORS \ 
                PyCryptoDome

### Client pip3.10 install Crypto
Flask
PyCryptoDome

Initialising Servers

Initialisation can be done in two ways. One is via PyCharm the other is running multiple Python instances via the command line.

PyCharm

Node1 (Server)

Within PyCharm under Run/Debug Configurations > Add New Configuration > Python, the following Configuration should be chosen:

  • Name: Node1
  • Script path: ~/PycharmProjects/MonoBlockchain/blockchain/blockchain.py
  • Parameters: -p 5001
  • Python interpreter: Python 3.10

PyCharm Configuration Node1
PyCharm Configuration Node1

Node2 (Server)

  • Name: Node2
  • Script path: ~/PycharmProjects/MonoBlockchain/blockchain/blockchain.py
  • Parameters: -p 5002
  • Python interpreter: Python 3.10

Alice (Client)

  • Name: Alice
  • Script path: ~/PycharmProjects/MonoBlockchain/blockchain_client/blockchain_client.py
  • Parameters: -p 8081
  • Python interpreter: Python 3.10

PyCharm Configuration Alice
PyCharm Configuration Alice

Bob (Client)

  • Name: Bob
  • Script path: ~/PycharmProjects/MonoBlockchain/blockchain_client/blockchain_client.py
  • Parameters: -p 8082
  • Python interpreter: Python 3.10

PyCharm Configuration Bob
PyCharm Configuration Bob

Running the Configuration

PyCharm Configurations

PyCharm Configurations are outlined in greater detail here.

Command-Line

CMD.exe / Terminal / Shell

Node1 (server)

$ python3 ~/MonoBlockchain/blockchain/blockchain.py

Alice (client)

$ python3 ~/MonoBlockchain/blockchain-client/blockchain-client.py -p 8081

Bob (client)

$ python3 ~/MonoBlockchain/blockchain-client/blockchain-client.py -p 8082

Blockchain Concepts

Proof of Work

MonoBlockchain is based on Proof of Work (PoW).

Hashing Algorithm

PoW relies on SHA256 due to requiring:

Immutable Ledger

The idea of an immutable ledger is to ensure the previous hash is linked cryptographically to the last block. Which then can be traversed back to the genesis (initial) block.

Immutable Ledger Example
Immputable Ledger

If block 2 were to be maliciously altered, the previous hash on block 3 would reflect this alteration. As the hash of block 2 would not be equal to the previous hash of block 3.

Distributed P2P

Explanation of Distributed P2P

A distributed peer-to-peer (P2P) network ensures that the blockchain ledger's network is not centralised.

image
Distributed P2P Network: Showing Computers (Servers) as Nodes

Having a decentralised network provides several benefits:

  • More nodes in the network
  • Potentially faster as not relying on a single node
  • More secure as the ledger has no single point of failure

Distributed P2P Network Showing Blocks
Distributed P2P Network Showing Blocks

Attacking Distributed P2P Network

Because of the immutable ledger, the attack must modify earlier blocks to reflect the hash change. Which requires much processing power as the SHA-256 algorithm is computationally demanding.

The attack vector of computing forged blocks is demonstrated below:

Distributed P2P Network Being Attacked
Distributed P2P Network Being Attacked

However, for the example above, seven nodes maintain an independent version of the ledger. The attacker has successfully modified blocks and forged the ledger cryptographically to reflect an action that did not occur. However, the attacker did this for a single node. As the attacker only makes up 14% of the distributed P2P network. For the attacker to successfully perform their attack, they must control 51% or more of the network's nodes.

See, 51% attack.

Mining

Mining is the competitive process that verifies and adds new transactions to the Blockchain for a cryptocurrency that uses the proof of work (PoW) method. The miner that wins the competition is rewarded with some amount of the currency and/or transaction fees - source.

Consider further reading PoW - Wikipedia.

The main point with mining is hard to solve, easy to verify.

Explanation of How Mining Works (Abstract)

Bitcoin Mining in 4 Minutes - Computerphile will give a ver clear outline of Bitcoin mining. MonoBlockchain is based on the same concept, and the PoW hashing algorithm is also SHA-256. So, there is little difference from a mining perspective between Bitcoin and MonoBlockchain.

Nonce (number once) is an arbitrary number that can be used just once in a cryptographic communication. The nonce is used to ensure old communications cannot be reused.

Abstract Overview of a Block
Abstract Overview of a Block

Why is Mining Necessary?

The short answer is to prevent abuse of the network. Requiring computational power to prove work is a logical method for mitigating DoS attacks while still keeping the usage of the network feasible.

Consensus Protocol

A consensus protocol aims to achieve agreement between nodes regarding what a blockchain should contain at a given time (including new blocks).

First Challenege

Referring back to Attacking Distributed P2P Network, we saw the attacker achieved a tampered version of the Blockchain but only contributed 14% of the entire distributed network. The other 86% naturally outnumbered the malicious blockchain node.

Second Challenege

Because each node in the distributed P2P network will mine the next block independently, a problem arises; overlapping nodes during synchronisation.

Second Challenege to Overcome
Consensus Protocol - Second Challenege: Overlapping Nodes

The consensus to avoid overlapping nodes is to wait for a new block to be mined before synchronising with other nodes in the network. Once a node has mined a new block, the other nodes will be asked to add it to their blockchain.

Essentially, the longest chain wins is a consensus between nodes.

Orphan Block

Another issue to consider as a blockchain PoW network user is orphan blocks.

An orphan block is a block that has been solved within the blockchain network but was not accepted by the network.

An orphan block can occur because there can be two miners who solve valid blocks simultaneously. The network uses both blocks until one chain has more verified blocks. Then, the blocks in the shorter chain are orphaned.

Ideally, to avoid falling victim to an orphan block, users would be advised to wait for 4-6 blocks after their transaction was verified before considering the transaction as 'fully' verified.

Programming Logic

How Mining Works (Technical)

This section is still under development.

The backend code is be viewed in blockchain/blockchain.py.

Mining Values

Within blockchain/blockchain.py the following values are assigned:

MINING_SENDER = "Blockchain - Miner Reward"
MINING_REWARD = 1
MINING_DIFFICULTY = 2

A possible future development could include writing functions to progressively change the MINING_REWARD and MINING_DIFFICULTY. However, for now the values are constant.

Hash Calculation

Proof of Work

def proof_of_work(self):

User Interface

To reduce development time with the user interface (UI), I have opted for using HTML with frameworks and host via HTTP using the render_template function in the Flask library.

JavaScript

Within blockchain_client/static/js/script.js is the location for user-written JavaScript, which is contained within the blockchain_client/templates/*. The same logic applies to blockcahin/static/js/script.js.

Blockchain Frontend

Because of the length of a public key 30819f300d06092a864886f70d010101050003818d00308189028181009f148fb25857801a51cb3a294af9707b27ce92e99a7c65604210a4675b855dc7166127a651bc2ae47f38ce726e3b9aeb978b869d67fb0b4ed24bfbd31c8cc8fb289a8f986eca64a993db4426f6307f307e3139d648d44ad7428b487a79642a2c43783f48bf60f9795a848f182459b14bb9c41553f4d3363732b7786eb2589d270203010001 I decided to use JavaScript to render public keys longer than 25-characters using ellipsis for the transactions table.

The following logic can be found in blockchain/static/js/script.js:

columnDefs: [{targets: [1,2,3,4,5], render: $.fn.dataTable.render.ellipsis(25)}]
Transactions on the Blockchain

Within blockchain/static/js/script.js is the timestamp for transactions.

formattedTimestamp = date.toLocaleTimeString('en-GB', options);

Currently, the timezone is configured to British English en-GB, but feel free to change this, possibly to UTC.

An outline of the toLocaleTimeString() function available via Mozilla.

Transactions on the Blockchain Client

Similar behaviour is seen within blockchain_client/static/js/script.js

var formattedDateTime = date.toLocaleTimeString("en-GB", options);

Frameworks

The following frameworks are used:

  • Bootstrap v4.0.0
  • DataTables 1.10.16
  • Font Awesome 4.7.0
    • Font Awesome webfont
  • jQuery JavaScript Library v3.3.1

CDNs and SRI Hashes

CDNs have been used and where the CDN did not provide an SRI Hash for integrity checks of the href/src I manually created the SRI Hash.

Possibly in a future revision, CDN files will be loaded locally via './static/vendor/' and have a local copy instead.

Specifying Node on Client-Side

Within blockchain-client/template/make_transactions.html the input tag contains value="http://127.0.0.1:5001"

Do chnage the value="" as necessary.

<div class="row">
  <label class="col-sm-12">Blockchain Node URL:</label>
  <div class="col-sm-12">
    <input type="text" name="node_url" id="node_url" rows="2" class="form-control" value="http://127.0.0.1:5001">
  </div>
</div>

The value is changeable when generating a transaction, as the client allows choosing which node to send the transaction to.

Confirm Transaction Details
Make Transaction page displaying Confirm Transaction Details

Encoding

Throughout the project, communication between the node (server) and client data is passed via JSON. Because of this, data is converted into a String and then encoded.

Public-key

Here the hexlify function is used.

Hash

SHA-256 hashes are encoded using UTF-8, as indicated within blockchain/blockchain.py

def verify_transaction_signature(self, sender_public_key, signature, transaction):
  ...
  h = SHA.new(str(transaction).encode('utf8'))

Verification

Because MonoBlockchain was developed for educational purposes, some lightweight basic validation choices were made, which do not offer real-world protection.

New Transaction

Within blockchain/blockchain.py, the following logic for validating a new transaction has been implemented.

def new_transaction():
    values = request.form
    required = ['confirmation_sender_public_key', 'confirmation_recipient_public_key', 'transaction_signature',
                'confirmation_amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

Please take care with if not all(k in values for k in required): as the logic was only to check if all values were present, nothing more. Erroneous values can be entered into the blockchain.

Preview Images of the Blockchain Client

Alice Generating a Wallet

image

Bob Generating a Wallet

image

Making a Transaction

image
Alice Sending Bob 100 MB Coin

image image

Successful Transaction

image
The Prompt of a Successful Transaction

Viewing Transactions

Onced mined transactions for the specified node are displayed.

image
Bob Viewing Transactions on Node1

Preview Images of the Blockchain Server

Viewing Transactions to be Mined

image
Viewing Transactions to be Mined on Node1

Mining

image
Mining Transaction on Node1

Configuring the Blockchain

image
Configuring the Blockchain Node

image Configuring the Blockchain Node

Consensus Between Nodes Blockchain

image Consensus Between Node 1 and Node 2

image Consensus Between Node 1 and Node 2

Preview Video

MonoBlockchain Preview | YouTube