Skip to content

Instantly share code, notes, and snippets.

@iamvasanth07
Forked from jsphdnl/blockchain_1.py
Created June 27, 2018 13:48
Show Gist options
  • Save iamvasanth07/fbbbc5322dfe940165da41f8de732fcd to your computer and use it in GitHub Desktop.
Save iamvasanth07/fbbbc5322dfe940165da41f8de732fcd to your computer and use it in GitHub Desktop.
BlockChain from Scratch Part 01 - python
import hashlib
import json
class TRBlock(object) :
def __init__(self, index, timestamp, data, prevHash, nonce, target):
'''
Default constructor for creating a block.
Parameters
----------
index : int
The index of the block
timestamp: long
Timestamp in epoch, number of seconds since 1 Jan 1970
data : object
The actual data that needs to be stored on block chain
prevHash : str
The hash of the previous block
nonce : str
The nonce which has been mined
target: int
Number of leading zeros
'''
self.index = index
self.timestamp = timestamp
self.data = data
self.prevHash = prevHash
self.nonce = nonce
self.target = target
def compute_hash(self):
'''
Compute sha1 hash and convert it into hexadecimal string, json.dumps
uses ":" separator without space
Returns
-------
str
sha1 hash of the attributes converted into hexadecimal string
'''
return hashlib.sha1(json.dumps(self.__dict__, separators=(',', ':')) \
.encode("utf-8")).hexdigest()
if __name__ == "__main__":
block = TRBlock(0,1514528022,"Hello World", "000000000000000000000000000", \
"Random nonce",8)
print(block.compute_hash())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment