Skip to content

Commit 5db8470

Browse files
committed
Exported hashing functions to a separate util file
hash_util.py
1 parent 01994a8 commit 5db8470

File tree

2 files changed

+27
-15
lines changed

2 files changed

+27
-15
lines changed

blockchain.py

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from functools import reduce
2-
import hashlib
3-
import json
42
from collections import OrderedDict
53

4+
from hash_util import hash_block, hash_str_256
5+
6+
67
# Configure Reward received for a successful mining of a block
78
MINING_REWARD = 10
89

@@ -29,18 +30,6 @@
2930

3031

3132

32-
def hash_block(block):
33-
"""Returns the SHA256 hash of the block as a string
34-
35-
Arguments:
36-
:block: The block to hash
37-
"""
38-
# Convert string to UTF8 with encode()
39-
# Return string representation of SHA256 with hexdigest()
40-
# The "sort_keys=True" ensures that order of data remains same during multiple hashing of same block
41-
return hashlib.sha256(json.dumps(block, sort_keys=True).encode()).hexdigest()
42-
43-
4433
def valid_proof(transaction, last_hash, proof):
4534
"""Returns True, if the proof (nonce) is valid a proof-of-work,
4635
i.e., if it satisfies the proof-of-work condition of generating
@@ -52,7 +41,7 @@ def valid_proof(transaction, last_hash, proof):
5241
:proof: The Nounce number that is to be checked
5342
"""
5443
guess = (str(transaction) + str(last_hash) + str(proof)).encode() # Combine and UTF8 encode
55-
guess_hash = hashlib.sha256(guess).hexdigest()
44+
guess_hash = hash_str_256(guess)
5645
print("GUESS HASH: ", guess_hash)
5746
return guess_hash[:POW_LEADING_ZEROS] == ('0' * POW_LEADING_ZEROS)
5847

hash_util.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import hashlib
2+
import json
3+
4+
5+
def hash_str_256(str):
6+
"""Returns SHA256 hash of a string as string
7+
8+
Arguments:
9+
:str: The string to hash
10+
"""
11+
return hashlib.sha256(str).hexdigest()
12+
13+
14+
def hash_block(block):
15+
"""Returns the SHA256 hash of the block as a string
16+
17+
Arguments:
18+
:block: The block to hash
19+
"""
20+
# Convert string to UTF8 with encode()
21+
# Return string representation of SHA256 with hexdigest()
22+
# The "sort_keys=True" ensures that order of data remains same during multiple hashing of same block
23+
return hash_str_256(json.dumps(block, sort_keys=True).encode())

0 commit comments

Comments
 (0)