mohamedlegh / tutoriel-blockchain-creation-bootstrap Goto Github PK
View Code? Open in Web Editor NEWcreate a blockchain from scratch
create a blockchain from scratch
class Block:
def __init__(self, index, previous_hash, nonce=0, timestamp=0, transactions=[], hashval=None, miner=None):
self.index = index
self.nonce = nonce
self.timestamp = timestamp
self.transactions = []
for elem in transactions:
self.transactions.append(Transaction(elem["sender"], elem["receiver"], elem["amount"], elem["timestamp"],
elem["tx_number"]))
self.previous_hash = previous_hash
self.hashval = hashval
self.miner = miner
class Transaction:
def __init__(self, sender, receiver, amount, timestamp=0, tx_number=None):
self.sender = sender
self.receiver = receiver
self.amount = amount
self.timestamp = timestamp
self.tx_number = tx_number
@node.route('/consensus', methods=['POST'])
def consensus():
global blockchain
if blockchain != None:
mychain = blockchain.blocks_list
mylength = len(mychain)
max_length = mylength
else:
max_length = 0
longest_chain = None
max_chain = None
peer = None
for node in peers:
response = requests.get('http://{}/chain'.format(node))
length_peer = response.json()['length']
chain_peer = response.json()['chain']
reward = 50
blockchain_peer = Blockchain(difficulty, chain_peer, reward)
if length_peer > max_length and blockchain_peer.verify():
max_length = length_peer
longest_chain = chain_peer
peer = node
max_chain = blockchain_peer
if longest_chain:
blockchain = max_chain
return "Find longer chain in peer: " + str(peer) + ", with length equal : " + str(max_length), 200
elif blockchain == None:
blockchain = Blockchain(difficulty)
blockchain.create_genesis_block()
return "No blockchain, creating a new chain", 200
return "My chain is the longest chain", 200
class Block:
def __init__(self, index, previous_hash, nonce=0, timestamp=0, transactions=[], hashval=None, miner=None):
self.index = index
self.nonce = nonce
self.timestamp = timestamp
self.transactions = []
for elem in transactions:
self.transactions.append(Transaction(elem["sender"], elem["receiver"], elem["amount"], elem["timestamp"],
elem["tx_number"]))
self.previous_hash = previous_hash
self.hashval = hashval
self.miner = miner
def hash(self, nonce):
sha = hashlib.sha256()
data = ""
data = str(self.index) + str(self.timestamp) + \
str(nonce) + str(self.previous_hash)
for elem in self.transactions:
data += str(elem.sender) + str(elem.receiver) + str(elem.amount)
sha.update(data.encode())
return sha.hexdigest()
def add_transaction(self, transaction):
tx = transaction
tx.tx_number = len(self.transactions)
self.transactions.append(tx)
def mine(self, difficulty): # proof of work algorithm, like in bitcoin
self.timestamp = time.time()
nonce = 0
prefix = "0" * difficulty
hash_value = self.hash(nonce)
while(hash_value.startswith(prefix) == False):
nonce += 1
hash_value = self.hash(nonce)
print(hash_value)
self.hashval = hash_value
self.nonce = nonce
self.miner = "your_name"
return nonce
def verify(self,nonce):
# check hash
computed_hash = self.hash(nonce)
if computed_hash != self.hashval:
return False
return True
def to_dict(self):
block_dict = {}
block_dict["index"] = self.index
block_dict["nonce"] = self.nonce
block_dict["timestamp"] = self.timestamp
block_dict["miner"] = self.miner
block_dict["transactions"] = []
for elem in self.transactions:
block_dict["transactions"].append(elem.to_dict())
block_dict["previous_hash"] = self.previous_hash
block_dict["hashval"] = self.hashval
return block_dict
def __repr__(self):
string = "Block number: " + str(self.index) + "\n" +\
"Nonce: " + str(self.nonce) + "\n" +\
"Timestamp: " + str(self.timestamp) + "\n" +\
"Miner: " + str(self.miner) + "\n" + \
"Transactions: " + str(self.transactions) + "\n" + \
"Previous hash: " + str(self.previous_hash) + "\n" + \
"Hash: " + str(self.hashval) + "\n"
return string
class Transaction:
def __init__(self, sender, receiver, amount, timestamp=0, tx_number=None):
self.sender = sender
self.receiver = receiver
self.amount = amount
self.timestamp = timestamp
self.tx_number = tx_number
def __repr__(self):
string = "Transaction number: " + str(self.tx_number) + "\n" + \
"Sender: " + str(self.sender) + "\n" + \
"Receiver: " + str(self.receiver) + "\n" + \
"Amount: " + str(self.amount) + "\n" + \
"Timestamp: " + str(self.timestamp) + "\n"
return string
def to_dict(self):
tx_dict = {}
tx_dict["tx_number"] = self.tx_number
tx_dict["sender"] = self.sender
tx_dict["receiver"] = self.receiver
tx_dict["amount"] = self.amount
tx_dict["timestamp"] = self.timestamp
return tx_dict
class Blockchain:
def __init__(self, difficulty, blocks_list=[], block_reward=50):
self.blocks_list = []
for elem in blocks_list:
block = Block(elem["index"],
elem["previous_hash"],
elem["nonce"],
elem["timestamp"],
elem["transactions"],
elem["hashval"],
elem["miner"])
self.blocks_list.append(block)
self.tx_pool = []
self.difficulty = difficulty
self.block_reward = block_reward
def create_genesis_block(self):
# Manually construct the first block
block = Block(0, "")
new_tx = Transaction("network",
"me",
self.block_reward,
time.time())
block.add_transaction(new_tx)
nonce = block.mine(self.difficulty)
self.blocks_list.append(block)
def mine_block(self):
last_block = self.blocks_list[-1]
index = last_block.index + 1
previous_hash = last_block.hashval
block = Block(index, previous_hash)
for elem in self.tx_pool :
block.add_transaction(elem)
self.tx_pool.clear()
new_tx = Transaction("network",
"me",
self.block_reward,
time.time())
block.add_transaction(new_tx)
nonce = block.mine(self.difficulty)
self.blocks_list.append(block)
def add_block(self, block):
last_block = self.blocks_list[-1]
if(block.timestamp < last_block.timestamp):
print("Timestamp received"+str(block.timestamp))
print("Timestamp last block"+str(last_block.timestamp))
raise ValueError(
"Error timestamp is before timestamp of last block")
if(block.index != last_block.index+1):
print("index received"+str(block.index))
print("index expected"+str(last_block.index+1))
raise ValueError("Error in indexing")
if(block.previous_hash != last_block.hashval):
print("Previous hash received"+str(block.previous_hash))
print("Previous hash expected"+str(last_block.hashval))
raise ValueError("block not aligned in the chain")
if(block.verify(block.nonce) != True):
raise ValueError("block not valid")
self.blocks_list.append(block)
def add_transaction(self, sender, receiver,amount):
transaction = Transaction(sender,
receiver,
amount,
time.time())
self.tx_pool.append(transaction)
def verify(self):
for elem in self.blocks_list:
if(elem.verify(elem.nonce) == False):
return False
return True
def to_dict(self):
chain_dict = []
for elem in self.blocks_list:
chain_dict.append(elem.to_dict())
return chain_dict
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.