<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="zh-Hans-CN">
	<id>http://www.anwsome.com//index.php?action=history&amp;feed=atom&amp;title=%E6%9E%84%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8C%BA%E5%9D%97%E9%93%BE</id>
	<title>构建自己的区块链 - 版本历史</title>
	<link rel="self" type="application/atom+xml" href="http://www.anwsome.com//index.php?action=history&amp;feed=atom&amp;title=%E6%9E%84%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8C%BA%E5%9D%97%E9%93%BE"/>
	<link rel="alternate" type="text/html" href="http://www.anwsome.com//index.php?title=%E6%9E%84%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8C%BA%E5%9D%97%E9%93%BE&amp;action=history"/>
	<updated>2026-04-15T01:54:57Z</updated>
	<subtitle>本wiki上该页面的版本历史</subtitle>
	<generator>MediaWiki 1.45.1</generator>
	<entry>
		<id>http://www.anwsome.com//index.php?title=%E6%9E%84%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8C%BA%E5%9D%97%E9%93%BE&amp;diff=28&amp;oldid=prev</id>
		<title>Xlong：​创建页面，内容为“== 如何构建自己的区块链：Python 教程 == 本教程将引导您从零开始构建区块链的基础知识。通过一个具体示例的详细讲解，您将更深入地了解区块链的优势和局限性。如需更全面的概述，我推荐您阅读 BitsOnBlocks 上的[https://bitsonblocks.net/2015/09/09/gentle-introduction-blockchain-technology/ 这篇优秀文章]。  === 1. 交易、验证和系统状态更新 === 区块链本质上是一个分…”</title>
		<link rel="alternate" type="text/html" href="http://www.anwsome.com//index.php?title=%E6%9E%84%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E5%8C%BA%E5%9D%97%E9%93%BE&amp;diff=28&amp;oldid=prev"/>
		<updated>2025-12-24T04:02:15Z</updated>

		<summary type="html">&lt;p&gt;创建页面，内容为“== 如何构建自己的区块链：Python 教程 == 本教程将引导您从零开始构建区块链的基础知识。通过一个具体示例的详细讲解，您将更深入地了解区块链的优势和局限性。如需更全面的概述，我推荐您阅读 BitsOnBlocks 上的[https://bitsonblocks.net/2015/09/09/gentle-introduction-blockchain-technology/ 这篇优秀文章]。  === 1. 交易、验证和系统状态更新 === 区块链本质上是一个分…”&lt;/p&gt;
&lt;p&gt;&lt;b&gt;新页面&lt;/b&gt;&lt;/p&gt;&lt;div&gt;== 如何构建自己的区块链：Python 教程 ==&lt;br /&gt;
本教程将引导您从零开始构建区块链的基础知识。通过一个具体示例的详细讲解，您将更深入地了解区块链的优势和局限性。如需更全面的概述，我推荐您阅读 BitsOnBlocks 上的[https://bitsonblocks.net/2015/09/09/gentle-introduction-blockchain-technology/ 这篇优秀文章]。&lt;br /&gt;
&lt;br /&gt;
=== 1. 交易、验证和系统状态更新 ===&lt;br /&gt;
区块链本质上是一个分布式数据库，它有一套规则来验证数据库中新增的数据。我们将首先追踪两个虚拟人物——爱丽丝和鲍勃——的账户，他们将彼此进行虚拟货币交易。&lt;br /&gt;
&lt;br /&gt;
我们需要创建一个用于存储传入交易的交易池，验证这些交易，并将它们打包成一个区块。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
我们将使用哈希函数为每笔交易创建一个“指纹”——这个哈希函数将每个区块彼此关联起来。为了方便使用，我们将定义一个辅助函数来封装我们使用的 Python 哈希函数。&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
import hashlib, json, sys&lt;br /&gt;
&lt;br /&gt;
def hashMe(msg=&amp;quot;&amp;quot;):&lt;br /&gt;
    # For convenience, this is a helper function that wraps our hashing algorithm&lt;br /&gt;
    if type(msg)!=str:&lt;br /&gt;
        msg = json.dumps(msg,sort_keys=True)  # If we don&amp;#039;t sort keys, we can&amp;#039;t guarantee repeatability!&lt;br /&gt;
        &lt;br /&gt;
    if sys.version_info.major == 2:&lt;br /&gt;
        return unicode(hashlib.sha256(msg).hexdigest(),&amp;#039;utf-8&amp;#039;)&lt;br /&gt;
    else:&lt;br /&gt;
        return hashlib.sha256(str(msg).encode(&amp;#039;utf-8&amp;#039;)).hexdigest()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;接下来，我们要创建一个函数来生成 Alice 和 Bob 之间的交易。我们将用负数表示取款，用正数表示存款。我们将确保交易始终发生在我们系统的两个用户之间，并且存款金额与取款金额大小相等——也就是说，我们既不创造货币，也不销毁货币。&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
import random&lt;br /&gt;
random.seed(0)&lt;br /&gt;
&lt;br /&gt;
def makeTransaction(maxValue=3):&lt;br /&gt;
    # This will create valid transactions in the range of (1,maxValue)&lt;br /&gt;
    sign      = int(random.getrandbits(1))*2 - 1   # This will randomly choose -1 or 1&lt;br /&gt;
    amount    = random.randint(1,maxValue)&lt;br /&gt;
    alicePays = sign * amount&lt;br /&gt;
    bobPays   = -1 * alicePays&lt;br /&gt;
    # By construction, this will always return transactions that respect the conservation of tokens.&lt;br /&gt;
    # However, note that we have not done anything to check whether these overdraft an account&lt;br /&gt;
    return {u&amp;#039;Alice&amp;#039;:alicePays,u&amp;#039;Bob&amp;#039;:bobPays}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;现在让我们创建大量交易，然后将它们分成区块。&lt;br /&gt;
&lt;br /&gt;
txnBuffer = [makeTransaction() for i in range(30)]&lt;br /&gt;
&lt;br /&gt;
下一步：创建我们自己的区块！我们将从交易缓冲区中取出前 k 笔交易，并将它们打包成一个区块。在此之前，我们需要定义一个方法来检查我们提取到区块中的交易的有效性。对于比特币，验证函数会检查输入值是否为有效的未花费交易输出（UTXO），交易输出是否不大于输入值，以及用于签名的密钥是否有效。在以太坊中，验证函数会检查智能合约是否被忠实执行并遵守 gas 限制。&lt;br /&gt;
&lt;br /&gt;
不过别担心，我们不必构建如此复杂的系统。我们将定义一套非常简单的规则，这些规则适用于基本的代币系统：&lt;br /&gt;
&lt;br /&gt;
* 存款和取款的总和必须为 0（代币既不被创造也不被销毁）&lt;br /&gt;
* 用户账户必须有足够的资金来支付任何提款。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
如果违反了其中任何一个条件，我们将拒绝交易。&lt;br /&gt;
&lt;br /&gt;
同时提供了一些交易示例，其中一些是欺诈性的——但我们现在可以检查它们的有效性！&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
def updateState(txn, state):&lt;br /&gt;
    # Inputs: txn, state: dictionaries keyed with account names, holding numeric values for transfer amount (txn) or account balance (state)&lt;br /&gt;
    # Returns: Updated state, with additional users added to state if necessary&lt;br /&gt;
    # NOTE: This does not not validate the transaction- just updates the state!&lt;br /&gt;
    &lt;br /&gt;
    # If the transaction is valid, then update the state&lt;br /&gt;
    state = state.copy() # As dictionaries are mutable, let&amp;#039;s avoid any confusion by creating a working copy of the data.&lt;br /&gt;
    for key in txn:&lt;br /&gt;
        if key in state.keys():&lt;br /&gt;
            state[key] += txn[key]&lt;br /&gt;
        else:&lt;br /&gt;
            state[key] = txn[key]&lt;br /&gt;
    return state&lt;br /&gt;
    &lt;br /&gt;
def isValidTxn(txn,state):&lt;br /&gt;
    # Assume that the transaction is a dictionary keyed by account names&lt;br /&gt;
&lt;br /&gt;
    # Check that the sum of the deposits and withdrawals is 0&lt;br /&gt;
    if sum(txn.values()) is not 0:&lt;br /&gt;
        return False&lt;br /&gt;
    &lt;br /&gt;
    # Check that the transaction does not cause an overdraft&lt;br /&gt;
    for key in txn.keys():&lt;br /&gt;
        if key in state.keys(): &lt;br /&gt;
            acctBalance = state[key]&lt;br /&gt;
        else:&lt;br /&gt;
            acctBalance = 0&lt;br /&gt;
        if (acctBalance + txn[key]) &amp;lt; 0:&lt;br /&gt;
            return False&lt;br /&gt;
    &lt;br /&gt;
    return True&lt;br /&gt;
    &lt;br /&gt;
state = {u&amp;#039;Alice&amp;#039;:5,u&amp;#039;Bob&amp;#039;:5}&lt;br /&gt;
&lt;br /&gt;
print(isValidTxn({u&amp;#039;Alice&amp;#039;: -3, u&amp;#039;Bob&amp;#039;: 3},state))  # Basic transaction- this works great! True&lt;br /&gt;
print(isValidTxn({u&amp;#039;Alice&amp;#039;: -4, u&amp;#039;Bob&amp;#039;: 3},state))  # But we can&amp;#039;t create or destroy tokens! False&lt;br /&gt;
print(isValidTxn({u&amp;#039;Alice&amp;#039;: -6, u&amp;#039;Bob&amp;#039;: 6},state))  # We also can&amp;#039;t overdraft our account. False&lt;br /&gt;
print(isValidTxn({u&amp;#039;Alice&amp;#039;: -4, u&amp;#039;Bob&amp;#039;: 2,&amp;#039;Lisa&amp;#039;:2},state)) # Creating new users is valid. True&lt;br /&gt;
print(isValidTxn({u&amp;#039;Alice&amp;#039;: -4, u&amp;#039;Bob&amp;#039;: 3,&amp;#039;Lisa&amp;#039;:2},state)) # But the same rules still apply! False&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;每个区块包含一批交易、指向前一个区块哈希值的引用（如果区块编号大于 1）以及其内容和区块头的哈希值。&lt;br /&gt;
&lt;br /&gt;
=== 2. 构建区块链：从交易到区块 ===&lt;br /&gt;
我们准备开始构建区块链！目前区块链上什么都没有，但我们可以通过定义“创世区块”（系统中的第一个区块）来启动它。由于创世区块不与任何先前的区块关联，它的处理方式略有不同，我们可以任意设置系统状态。在本例中，我们将为两位用户（Alice 和 Bob）创建账户，并分别给予他们 50 个代币。&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
state = {u&amp;#039;Alice&amp;#039;:50, u&amp;#039;Bob&amp;#039;:50}  # Define the initial state&lt;br /&gt;
genesisBlockTxns = [state]&lt;br /&gt;
genesisBlockContents = {u&amp;#039;blockNumber&amp;#039;:0,u&amp;#039;parentHash&amp;#039;:None,u&amp;#039;txnCount&amp;#039;:1,u&amp;#039;txns&amp;#039;:genesisBlockTxns}&lt;br /&gt;
genesisHash = hashMe( genesisBlockContents )&lt;br /&gt;
genesisBlock = {u&amp;#039;hash&amp;#039;:genesisHash,u&amp;#039;contents&amp;#039;:genesisBlockContents}&lt;br /&gt;
genesisBlockStr = json.dumps(genesisBlock, sort_keys=True)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;这将成为所有其他要素联系在一起的第一个要素。&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span lang=&amp;quot;zh-Hans-CN&amp;quot; dir=&amp;quot;ltr&amp;quot;&amp;gt;chain = [genesisBlock]&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
对于每个区块，我们希望收集一组交易信息，创建区块头，对其进行哈希处理，然后将其添加到链中。&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
def makeBlock(txns,chain):&lt;br /&gt;
    parentBlock = chain[-1]&lt;br /&gt;
    parentHash  = parentBlock[u&amp;#039;hash&amp;#039;]&lt;br /&gt;
    blockNumber = parentBlock[u&amp;#039;contents&amp;#039;][u&amp;#039;blockNumber&amp;#039;] + 1&lt;br /&gt;
    txnCount    = len(txns)&lt;br /&gt;
    blockContents = {u&amp;#039;blockNumber&amp;#039;:blockNumber,u&amp;#039;parentHash&amp;#039;:parentHash,&lt;br /&gt;
                     u&amp;#039;txnCount&amp;#039;:len(txns),&amp;#039;txns&amp;#039;:txns}&lt;br /&gt;
    blockHash = hashMe( blockContents )&lt;br /&gt;
    block = {u&amp;#039;hash&amp;#039;:blockHash,u&amp;#039;contents&amp;#039;:blockContents}&lt;br /&gt;
    &lt;br /&gt;
    return block&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;让我们用这个方法将交易缓冲区处理成一组数据块：&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
blockSizeLimit = 5  # Arbitrary number of transactions per block- &lt;br /&gt;
               #  this is chosen by the block miner, and can vary between blocks!&lt;br /&gt;
&lt;br /&gt;
while len(txnBuffer) &amp;gt; 0:&lt;br /&gt;
    bufferStartSize = len(txnBuffer)&lt;br /&gt;
    &lt;br /&gt;
    ## Gather a set of valid transactions for inclusion&lt;br /&gt;
    txnList = []&lt;br /&gt;
    while (len(txnBuffer) &amp;gt; 0) &amp;amp; (len(txnList) &amp;lt; blockSizeLimit):&lt;br /&gt;
        newTxn = txnBuffer.pop()&lt;br /&gt;
        validTxn = isValidTxn(newTxn,state) # This will return False if txn is invalid&lt;br /&gt;
        &lt;br /&gt;
        if validTxn:           # If we got a valid state, not &amp;#039;False&amp;#039;&lt;br /&gt;
            txnList.append(newTxn)&lt;br /&gt;
            state = updateState(newTxn,state)&lt;br /&gt;
        else:&lt;br /&gt;
            print(&amp;quot;ignored transaction&amp;quot;)&lt;br /&gt;
            sys.stdout.flush()&lt;br /&gt;
            continue  # This was an invalid transaction; ignore it and move on&lt;br /&gt;
        &lt;br /&gt;
    ## Make a block&lt;br /&gt;
    myBlock = makeBlock(txnList,chain)&lt;br /&gt;
    chain.append(myBlock)  &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;链信息输出如下：&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
chain[0]&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
    &amp;#039;contents&amp;#039;: {&amp;#039;blockNumber&amp;#039;: 0,&lt;br /&gt;
    &amp;#039;parentHash&amp;#039;: None,&lt;br /&gt;
    &amp;#039;txnCount&amp;#039;: 1,&lt;br /&gt;
    &amp;#039;txns&amp;#039;: [{&amp;#039;Alice&amp;#039;: 50, &amp;#039;Bob&amp;#039;: 50}]},&lt;br /&gt;
    &amp;#039;hash&amp;#039;: &amp;#039;7c88a4312054f89a2b73b04989cd9b9e1ae437e1048f89fbb4e18a08479de507&amp;#039;&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
 chain[1]&lt;br /&gt;
 &lt;br /&gt;
 {&lt;br /&gt;
    &amp;#039;contents&amp;#039;: &lt;br /&gt;
        {&lt;br /&gt;
            &amp;#039;blockNumber&amp;#039;: 1,&lt;br /&gt;
            &amp;#039;parentHash&amp;#039;: &amp;#039;7c88a4312054f89a2b73b04989cd9b9e1ae437e1048f89fbb4e18a08479de507&amp;#039;,&lt;br /&gt;
            &amp;#039;txnCount&amp;#039;: 5,&lt;br /&gt;
            &amp;#039;txns&amp;#039;: [{&amp;#039;Alice&amp;#039;: 3, &amp;#039;Bob&amp;#039;: -3},&lt;br /&gt;
            {&amp;#039;Alice&amp;#039;: -1, &amp;#039;Bob&amp;#039;: 1},&lt;br /&gt;
            {&amp;#039;Alice&amp;#039;: 3, &amp;#039;Bob&amp;#039;: -3},&lt;br /&gt;
            {&amp;#039;Alice&amp;#039;: -2, &amp;#039;Bob&amp;#039;: 2},&lt;br /&gt;
            {&amp;#039;Alice&amp;#039;: 3, &amp;#039;Bob&amp;#039;: -3}]&lt;br /&gt;
        },&lt;br /&gt;
    &amp;#039;hash&amp;#039;: &amp;#039;7a91fc8206c5351293fd11200b33b7192e87fad6545504068a51aba868bc6f72&amp;#039;&lt;br /&gt;
     &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;正如预期的那样，创世区块包含一笔无效交易，该交易会初始化账户余额（凭空创建代币）。子区块引用了父区块的哈希值，其中包含一组影响系统状态的新交易。现在我们可以看到系统状态已更新，包含了这些交易。&lt;br /&gt;
&lt;br /&gt;
=== 3 检查链有效性 ===&lt;br /&gt;
既然我们已经知道如何创建新区块并将它们连接成链，那么让我们定义一些函数来检查新区块是否有效，以及整个链是否有效。&lt;br /&gt;
在区块链网络中，这一点在两个方面变得尤为重要：&lt;br /&gt;
&lt;br /&gt;
* 在初始设置节点时，我们会下载完整的区块链历史记录。下载完成后，我们需要遍历整个区块链来计算系统状态。为了防止有人在初始链中插入无效交易，我们需要在初始下载时检查整条链的有效性。&lt;br /&gt;
* 一旦我们的节点与网络同步（拥有最新的区块链副本和系统状态的表示），它就需要检查广播到网络的新区块的有效性。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
我们需要三个功能来实现这一点：&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;checkBlockHash&amp;#039;&amp;#039;&amp;#039;: 一个简单的辅助函数，用于确保区块内容与哈希值匹配。&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;checkBlockValidity&amp;#039;&amp;#039;&amp;#039;: 检查给定父节点和当前系统状态的区块的有效性。如果区块有效，我们希望它返回更新后的状态；否则，抛出错误。&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;checkChain&amp;#039;&amp;#039;&amp;#039;: 检查整个区块链的有效性，并计算从创世区块开始的系统状态。如果区块链有效，则返回系统状态；否则，抛出错误。&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
def checkBlockHash(block):&lt;br /&gt;
    # Raise an exception if the hash does not match the block contents&lt;br /&gt;
    expectedHash = hashMe( block[&amp;#039;contents&amp;#039;] )&lt;br /&gt;
    if block[&amp;#039;hash&amp;#039;]!=expectedHash:&lt;br /&gt;
        raise Exception(&amp;#039;Hash does not match contents of block %s&amp;#039;%&lt;br /&gt;
                        block[&amp;#039;contents&amp;#039;][&amp;#039;blockNumber&amp;#039;])&lt;br /&gt;
    return&lt;br /&gt;
    &lt;br /&gt;
def checkBlockValidity(block,parent,state):    &lt;br /&gt;
    # We want to check the following conditions:&lt;br /&gt;
    # - Each of the transactions are valid updates to the system state&lt;br /&gt;
    # - Block hash is valid for the block contents&lt;br /&gt;
    # - Block number increments the parent block number by 1&lt;br /&gt;
    # - Accurately references the parent block&amp;#039;s hash&lt;br /&gt;
    parentNumber = parent[&amp;#039;contents&amp;#039;][&amp;#039;blockNumber&amp;#039;]&lt;br /&gt;
    parentHash   = parent[&amp;#039;hash&amp;#039;]&lt;br /&gt;
    blockNumber  = block[&amp;#039;contents&amp;#039;][&amp;#039;blockNumber&amp;#039;]&lt;br /&gt;
    &lt;br /&gt;
    # Check transaction validity; throw an error if an invalid transaction was found.&lt;br /&gt;
    for txn in block[&amp;#039;contents&amp;#039;][&amp;#039;txns&amp;#039;]:&lt;br /&gt;
        if isValidTxn(txn,state):&lt;br /&gt;
            state = updateState(txn,state)&lt;br /&gt;
        else:&lt;br /&gt;
            raise Exception(&amp;#039;Invalid transaction in block %s: %s&amp;#039;%(blockNumber,txn))&lt;br /&gt;
&lt;br /&gt;
    checkBlockHash(block) # Check hash integrity; raises error if inaccurate&lt;br /&gt;
&lt;br /&gt;
    if blockNumber!=(parentNumber+1):&lt;br /&gt;
        raise Exception(&amp;#039;Hash does not match contents of block %s&amp;#039;%blockNumber)&lt;br /&gt;
&lt;br /&gt;
    if block[&amp;#039;contents&amp;#039;][&amp;#039;parentHash&amp;#039;] != parentHash:&lt;br /&gt;
        raise Exception(&amp;#039;Parent hash not accurate at block %s&amp;#039;%blockNumber)&lt;br /&gt;
    &lt;br /&gt;
    return state&lt;br /&gt;
    &lt;br /&gt;
def checkChain(chain):&lt;br /&gt;
    # Work through the chain from the genesis block (which gets special treatment), &lt;br /&gt;
    #  checking that all transactions are internally valid,&lt;br /&gt;
    #    that the transactions do not cause an overdraft,&lt;br /&gt;
    #    and that the blocks are linked by their hashes.&lt;br /&gt;
    # This returns the state as a dictionary of accounts and balances,&lt;br /&gt;
    #   or returns False if an error was detected&lt;br /&gt;
&lt;br /&gt;
    &lt;br /&gt;
    ## Data input processing: Make sure that our chain is a list of dicts&lt;br /&gt;
    if type(chain)==str:&lt;br /&gt;
        try:&lt;br /&gt;
            chain = json.loads(chain)&lt;br /&gt;
            assert( type(chain)==list)&lt;br /&gt;
        except:  # This is a catch-all, admittedly crude&lt;br /&gt;
            return False&lt;br /&gt;
    elif type(chain)!=list:&lt;br /&gt;
        return False&lt;br /&gt;
    &lt;br /&gt;
    state = {}&lt;br /&gt;
    ## Prime the pump by checking the genesis block&lt;br /&gt;
    # We want to check the following conditions:&lt;br /&gt;
    # - Each of the transactions are valid updates to the system state&lt;br /&gt;
    # - Block hash is valid for the block contents&lt;br /&gt;
&lt;br /&gt;
    for txn in chain[0][&amp;#039;contents&amp;#039;][&amp;#039;txns&amp;#039;]:&lt;br /&gt;
        state = updateState(txn,state)&lt;br /&gt;
    checkBlockHash(chain[0])&lt;br /&gt;
    parent = chain[0]&lt;br /&gt;
    &lt;br /&gt;
    ## Checking subsequent blocks: These additionally need to check&lt;br /&gt;
    #    - the reference to the parent block&amp;#039;s hash&lt;br /&gt;
    #    - the validity of the block number&lt;br /&gt;
    for block in chain[1:]:&lt;br /&gt;
        state = checkBlockValidity(block,parent,state)&lt;br /&gt;
        parent = block&lt;br /&gt;
        &lt;br /&gt;
    return state&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== 4 整合：最终的区块链架构 ===&lt;br /&gt;
在实际的区块链网络中，新节点会下载区块链副本并进行验证（就像我们刚才做的那样），然后在点对点网络上宣告自身的存在，并开始监听交易。它们将交易打包成一个区块，然后将自己提议的区块传递给其他节点。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
我们已经了解了如何验证区块链副本，以及如何将交易打包成一个区块。如果我们从其他地方收到一个区块，验证它并将其添加到我们自己的区块链中也很容易。&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
假设以下代码在节点 A 上运行，该节点负责挖矿：&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
import copy&lt;br /&gt;
nodeBchain = copy.copy(chain)&lt;br /&gt;
nodeBtxns  = [makeTransaction() for i in range(5)]&lt;br /&gt;
newBlock   = makeBlock(nodeBtxns,nodeBchain)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;现在假设 &amp;lt;code&amp;gt;newBlock&amp;lt;/code&amp;gt; 被发送到我们的节点，我们想要检查它是否为有效区块，如果是则更新我们的状态：&amp;lt;syntaxhighlight lang=&amp;quot;python3&amp;quot; line=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Blockchain on Node A is currently %s blocks long&amp;quot;%len(chain))&lt;br /&gt;
&lt;br /&gt;
try:&lt;br /&gt;
    print(&amp;quot;New Block Received; checking validity...&amp;quot;)&lt;br /&gt;
    state = checkBlockValidity(newBlock,chain[-1],state) # Update the state- this will throw an error if the block is invalid!&lt;br /&gt;
    chain.append(newBlock)&lt;br /&gt;
except:&lt;br /&gt;
    print(&amp;quot;Invalid block; ignoring and waiting for the next block...&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;Blockchain on Node A is now %s blocks long&amp;quot;%len(chain))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;Blockchain on Node A is currently 7 blocks long&lt;br /&gt;
&lt;br /&gt;
New Block Received; checking validity...&lt;br /&gt;
&lt;br /&gt;
Blockchain on Node A is now 8 blocks long&lt;br /&gt;
&lt;br /&gt;
=== 5 结论与拓展 ===&lt;br /&gt;
我们已经构建了区块链的所有基本架构，从状态转换规则集到区块创建方法，再到用于验证交易、区块和整条链有效性的机制。我们可以从下载的区块链副本中获取系统状态，验证从网络接收的新区块，并创建我们自己的区块。&lt;br /&gt;
&lt;br /&gt;
我们创建的系统状态实际上是一个分布式账本或数据库——这是许多区块链的核心。我们可以扩展它，使其包含特殊交易类型或完整的智能合约。&lt;br /&gt;
&lt;br /&gt;
我们尚未探讨网络架构、工作量证明或状态证明验证步骤，以及为区块链提供抗攻击安全性的共识机制。我们也尚未讨论公钥密码学、隐私和验证步骤。未来我们将对此进行更深入的探讨！&lt;/div&gt;</summary>
		<author><name>Xlong</name></author>
	</entry>
</feed>