The content of this article is about analyzing the blockchain in detail through Python functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I think for a lot of people out there, blockchain is such a phenomenon that it’s hard not to get your head spinning. I started watching videos and reading articles, but for me personally, I didn't really understand what it was and what its potential applications were until I wrote my own simple blockchain.
My view of blockchain is that it is a public encrypted database. If you were Amazon and you wanted to use the technology to track inventory levels, would it make sense to use blockchain? Probably not, because your customers don't want to spend the resources to verify your blockchain because they just look at the website and say Only 1 left!
.
I'll let you consider it for future applications. So without further ado, let’s take a look at our 7 functions!
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()
The core of the blockchain is the hash function. Without encryption, the blockchain would be easy to operate and transactions would be able to be written 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
state
is to record who owns the token transactions. For example, I have 10 tokens and I give 1 to Medium, then the state state
will be the value of the dictionary below.
{‘transaction’: {‘Tom’: 9, ‘Medium’: 1}}
It is worth noting that overdraft is not possible. I can't give someone 11 tokens if there are only 10 tokens available. The following function verifies that the transaction we are trying to make is indeed valid. Additionally, the transaction must be balanced overall. I can't give 5 tokens and have the recipient receive 4 tokens because that would destroy and generate the tokens.
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
Now, we can make our block. The information from the previous block is read and used to link it to the new block. This is also the core of the blockchain concept. It is possible to deceptively insert seemingly valid transactions into the blockchain, but it is computationally (almost) impossible to decrypt all previous blocks, which preserves the integrity of the blockchain.
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}
Here is a little helper function to check the hash of the previous block:
def check_block_hash(block): expected_hash = hash_function(block['contents']) if block['hash'] is not expected_hash: raise return
Once we have everything together, we have time to create our block. We will now 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
Before we can finish, the blockchain must be verified:
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
Finally, a transaction function is needed which will suspend all of the above:
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
So, now We have 7 functions. How do we interact with it? Well, first we need to start our blockchain with Genesis Block
. This is the start of our new token (or inventory, etc.). For the purpose of this article I will say that I am Tom and will start with 10 tokens.
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}
Now, look what happens when I give some tokens to Medium:
chain_state, block_chain = add_transaction_to_chain(transaction={'Tom': -1, 'Medium': 1}, state=chain_state, chain=block_chain)
state
Update showing who owns how many tokens:
{'Medium': 1, 'Tom': 9}
The blockchain looks like this:
[{'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'}]
We create the first new transaction and insert it at the top of the stack. Now, I hope I've piqued your curiosity and interest in copying the code down and playing with it.
The above is the detailed content of Analyze the blockchain in detail through Python functions. For more information, please follow other related articles on the PHP Chinese website!