用7个Python函数解析区块链

1.哈希函数 Hash Function

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()

区块链的核心是哈希函数。在没有加密的情况下,区块链将很容易操作,并且交易将能够被欺骗地插入。

2.状态更新

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

“状态”是谁拥有需求的记录。例如,Tom有10个硬币,并给了Medium1个,那么这个状态就是下面字典的值:

{‘transaction’: {‘Tom’: 9, ‘Medium’: 1}}

3.有效事务

值得注意的是,透支不能存在。如果只有10枚硬币,那么就不能给别人11枚硬币。下面的函数验证了我们试图创建的交易确实有效。此外,交易必须保持平衡。我不能给出5个硬币,而让对方收到4个硬币,因为那将允许硬币的销毁和创造。

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

4.创建区块

现在,我们可以创建区块了。读取前一个区块中的信息,并将其链接到新区块上。这也是区块链思想的核心。看起来有效的交易可以尝试欺骗地插入到区块链中,但是对所有前面的块进行解密在计算上(几乎)是不可能的,这如此便保留了区块链的完整性。

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}

以下函数是一个帮助检查先前区块哈希函数的小帮手:

def check_block_hash(block):
expected_hash = hash_function(block['contents'])
if block['hash'] is not expected_hash:
raise
return

5.升级区块链

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

6.验证区块链

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

7.事务处理函数

最后,我们需要用事务处理函数将以上全部内容串起:

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

举例

以上是我们的七个函数,那么该如何与之互动呢?首先我们需要用Genesis Block启动我们的区块链。这是我们的初始资金。

比方说,Tom,从10个硬币开始:

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}

接下来,Tom给了Medium一些硬币:

chain_state, block_chain = add_transaction_to_chain(transaction={'Tom': -1, 'Medium': 1}, state=chain_state, chain=block_chain)

状态就会更新成:

{'Medium': 1, 'Tom': 9}

python学习交流群:125240963

而区块链看起来就会像这样:

[{'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'}]

原文地址:https://www.kdnuggets.com/2018/04/blockchain-explained-7-python-functions.html

作者:Tom Cusack
更多Python视频、源码、资料加群725638078免费获取
来源:KDnuggets
参与:Cynthia
翻译:本文为天善智能编译,未经容许,禁止转载

posted @ 2022-10-07 20:56  I'm_江河湖海  阅读(123)  评论(0编辑  收藏  举报