-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathblock.py
More file actions
53 lines (46 loc) · 1.57 KB
/
block.py
File metadata and controls
53 lines (46 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import hashlib as hashlib
import datetime as date
# Block object
class Block:
# Constructor
def __init__(self, index, transactions, nonce, previousHash, hash=None, timestamp=None):
self.index = index
self.transactions = transactions
self.nonce = nonce
self.previousHash = previousHash
if hash:
self.hash = hash
else:
self.hash = self.hashBlock()
self.timestamp = timestamp
def _asdict(self):
return self.__dict__
# Generate the hash for the new block
def hashBlock(self):
hash = hashlib.sha256((
str(self.transactions) +
str(self.nonce) +
str(self.previousHash)).encode('utf-8'))
return hash.hexdigest()
# Prints out information about the block
def display(self):
print("Block #: " + str(self.index))
print("transactions: " + self.transactions)
print("Nonce: " + str(self.nonce))
print("Hash: " + self.hash)
print("Previous Hash: " + self.previousHash)
print("")
def validate(self, prefix):
if (self.hash != self.hashBlock()):
return False
# if (self.hash[:4] != "0000"):
# return False
if (self.hash[:len(prefix)] != prefix):
return False
return True
# Creates the first block with arbitrary hash
def createGenesisBlock():
return Block(0, "[]", 0, "0")
def nextBlock(lastBlock, transactions, nonce):
index = lastBlock.index + 1
return Block(index, transactions, nonce, lastBlock.hash)