Blockchain works on the principal of hash keys. Hashing functions are essential to avoid alteration and fraudulent manipulation.
def hash_function(k):
"""Hashes our transaction."""
if type(k) is not str:
k = json.dumps(k, sort_keys=True)
return hashlib.sha256(k).hexdigest()
Blockchain depends on the principle of a hash key. That is, it depends on the hashing function as its backbone. If it is not encrypted using a hashing function, anyone can manipulate the structure fraudulently.
def update_state(transaction, state):
state = state.copy()
for key in transaction:
if key in state.keys():
state[key] += transaction[key]
else:
state[key] = transaction[key]
return state
The ‘state’ defines the person who has the record of storing asset. In other words, it represents what lies with whom. If the value is deducted from a person’s assets from 10 to 9, state will acquire a value like this:
{‘transaction’: {‘Tom’: 9, ‘Medium’: 1}}
Also, a critical part to keep in mind is that it is not possible to send/give someone more than one already has. To implement this property, we use the function given below:
def valid_transaction(transaction, state):
"""A valid transaction must sum to 0."""
if sum(transaction.values()) is not 0:
return False
for key in transaction.keys():
if key in state.keys():
account_balance = state[key]
else:
account_balance = 0
if account_balance + transaction[key] < 0:
return False
return True
[/code]
<br /><br />
After taking care of our basic logic functions to prevent fraudulent manipulations, we can focus on the structure. The Blockchain depends on blocks. Like the name, it is like chain of blocks. Subsequent blocks require the information of previous blocks to work. Here also, to prevent fraudulent insertions or deletions, all the previous blocks have strong encryption. One cannot decrypt a particular block without affecting the chain. Decrypting a chain in this way is impossible computationally.
<br /><br />
def make_block(transactions, chain):
"""Make a block to go into the chain."""
parent_hash = chain[-1]['hash']
block_number = chain[-1]['contents']['block_number'] + 1
block_contents = {
'block_number': block_number,
'parent_hash': parent_hash,
'transaction_count': block_number + 1,
'transaction': transactions
}
return {'hash': hash_function(block_contents), 'contents': block_contents}
We can also check the integrity of the previous blocks using this function:
def check_block_hash(block):
expected_hash = hash_function(block['contents'])
if block['hash'] is not expected_hash:
raise
return
Now it is time to assemble our blocks and update the Blockchain:
def check_block_validity(block, parent, state):
parent_number = parent['contents']['block_number']
parent_hash = parent['hash']
block_number = block['contents']['block_number']
for transaction in block['contents']['transaction']:
if valid_transaction(transaction, state):
state = update_state(transaction, state)
else:
raise
check_block_hash(block) # Check hash integrity
if block_number is not parent_number + 1:
raise
if block['contents']['parent_hash'] is not parent_hash:
raise
return state
We have to use this function to verify the integrity of the chain as well:
def check_chain(chain):
"""Check the chain is valid."""
if type(chain) is str:
try:
chain = json.loads(chain)
assert (type(chain) == list)
except ValueError:
# String passed in was not valid JSON
return False
elif type(chain) is not list:
return False
state = {}
for transaction in chain[0]['contents']['transaction']:
state = update_state(transaction, state)
check_block_hash(chain[0])
parent = chain[0]
for block in chain[1:]:
state = check_block_validity(block, parent, state)
parent = block
return state
Now we need to define a function to compile all of the above together:
def add_transaction_to_chain(transaction, state, chain):
if valid_transaction(transaction, state):
state = update_state(transaction, state)
else:
raise Exception('Invalid transaction.')
my_block = make_block(state, chain)
chain.append(my_block)
for transaction in chain:
check_chain(transaction)
return state, chain
Now that we have our 7 functions, we need to define our starting block in the chain. That is, we have to define our deposit framework to have some kind of value as a beginning.
genesis_block = {
'hash': hash_function({
'block_number': 0,
'parent_hash': None,
'transaction_count': 1,
'transaction': [{'Tom': 10}]
}),
'contents': {
'block_number': 0,
'parent_hash': None,
'transaction_count': 1,
'transaction': [{'Tom': 10}]
},
}
block_chain = [genesis_block]
chain_state = {'Tom': 10}
When we give or move some value to our medium from before:
chain_state, block_chain = add_transaction_to_chain(transaction={'Tom': -1, 'Medium': 1}, state=chain_state, chain=block_chain)
Then our state looks like this:
{'Medium': 1, 'Tom': 9}
Our Blockchain looks like:
[{'contents': {'block_number': 0,
'parent_hash': None,
'transaction': [{'Tom': 10}],
'transaction_count': 1},
'hash': '064d0b480b3b92761f31831d30ae9f01954efaa62371b4b44f11465ec22abe93'},
{'contents': {'block_number': 1,
'parent_hash': '064d0b480b3b92761f31831d30ae9f01954efaa62371b4b44f11465ec22abe93',
'transaction': {'Medium': 1, 'Tom': 9},
'transaction_count': 2},
'hash': 'b4ae25f0cc0ee0b0caa66b9a3473e9a108652d53b1dc22a40962fef5c8c0f08c'}]
So, we have defined our 7 functions and assigned a transaction to the first block of our Blockchain. You can experiment with the code and change things around to see how the Blockchain changes.
Try to experiment with what happens if you go against the logic and structure of the Blockchain. To start learning deep learning for further use, reach out to our
Deep Learning Indian centers. Use artificial intelligence in Blockchain structures and learn Artificial Intelligence in
Artificial Intelligence Indian centers.