Want to build your own Blockchain

in bitcoin •  2 years ago 

Today I have brought you a template to building your own blockchain. Copy code below for basic blockchain layout, of course you will have to make it your own with personalized specifications and security. Paste this into Python and have fun. I will be laying out a template to algorythms in later posts. In the end I will give you the the a complete beginners template to creating your own Crypto currency. All you need after that is an idea and a backing for your coin. Good Luck and have fun.

import hashlib
import time

class Block:
def init(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()

def calculate_hash(self):
    sha = hashlib.sha256()
    sha.update(
        str(self.index).encode('utf-8') +
        str(self.timestamp).encode('utf-8') +
        str(self.data).encode('utf-8') +
        str(self.previous_hash).encode('utf-8') +
        str(self.nonce).encode('utf-8')
    )
    return sha.hexdigest()

def mine_block(self, difficulty):
    target = '0' * difficulty
    while self.hash[:difficulty] != target:
        self.nonce += 1
        self.hash = self.calculate_hash()

class Blockchain:
def init(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 4

def create_genesis_block(self):
    return Block(0, time.time(), 'Genesis Block', '0')

def get_latest_block(self):
    return self.chain[-1]

def add_block(self, new_block):
    new_block.previous_hash = self.get_latest_block().hash
    new_block.mine_block(self.difficulty)
    self.chain.append(new_block)

def is_chain_valid(self):
    for i in range(1, len(self.chain)):
        current_block = self.chain[i]
        previous_block = self.chain[i - 1]

        if current_block.hash != current_block.calculate_hash():
            return False

        if current_block.previous_hash != previous_block.hash:
            return False

    return True

Usage example

blockchain = Blockchain()
blockchain.add_block(Block(1, time.time(), 'Data 1', ''))
blockchain.add_block(Block(2, time.time(), 'Data 2', ''))

#bitcoin
#crypto
#cryptocurrency
#technology
#steemit

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!