首页 > 区块链 > 用Python函数来解释区块链7个功能
low链  

用Python函数来解释区块链7个功能

摘要:区块链功能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()

用Python函数来解释区块链7个功能

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

区块链的核心是哈希函数。如果没有加密,区块链将很容易操作,交易将被欺骗性地插入。

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 '是谁拥有想要的记录。例如,我有10个硬币,我给Medium1个,然后状态将是下面的字典的值。

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

重要的是要注意透支不能存在。如果只有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

现在,我们可以生成块。读取前一个块的信息,并将其用于将其链接到新块。这也是区块链理念的核心。看似有效的交易可以尝试欺诈地插入区块链,但解密所有先前的区块在计算上(几乎)是不可能的,这保留了区块链的完整性。

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 expected_hash:

raise

return

一旦我们把所有的东西组合在一起,就有时间来创建我们的块。我们现在将更新区块链。

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

在我们完成之前,链必须被验证:

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

最后,需要一个交易功能,它将上述所有内容挂在一起:

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

所以,现在我们有7个功能。我们如何与它互动?那么,首先我们需要开始我们的连锁与创世纪块。这是我们新硬币的开始。为了这篇文章的目的,将从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}

现在,看看我给Medium硬币时会发生什么:

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

状态得到更新以显示谁有什么:

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

区块链看起来像这样:

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

免责声明
世链财经作为开放的信息发布平台,所有资讯仅代表作者个人观点,与世链财经无关。如文章、图片、音频或视频出现侵权、违规及其他不当言论,请提供相关材料,发送到:2785592653@qq.com。
风险提示:本站所提供的资讯不代表任何投资暗示。投资有风险,入市须谨慎。
世链粉丝群:提供最新热点新闻,空投糖果、红包等福利,微信:juu3644。