Created
January 9, 2018 12:40
-
-
Save jsphdnl/92de6883929fc7f6be78ba24a8f4c439 to your computer and use it in GitHub Desktop.
BlockChain from Scratch Part 01 - python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
It will more fruitful if mention the formula to convert. Thank you.