手把手教你搭建区块链(上)| 技术帖

Coinsuper带你解析如何自己动手搭建区块链。

“学习区块链的最快方法就是自己亲手搭建一个”

如果您已经掌握了一些基础的python知识,那么跟着本文搭建区块链对您来说将不是一件难事儿。

手把手教你搭建区块链(上)| 技术帖

在开始之前,有一些概念需要您先明确:

1. 区块链是一个不变的顺序记录链,称为块。它们可以包含事务,文件或任何您想要记录的数据。您只需记住,它们使用哈希值链接在一起。

2. 哈希函数就是一个简单的函数,它接受输入值,并根据该输入创建确定输入值的输出值。对于任何x输入值,只要运行哈希函数,您将始终收到相同的y输出值。这样,每个输入都有一个确定的输出。哈希函数通常是不可逆的(单向),这意味着仅知道输出就无法弄清楚输入-除非尝试所有可能的输入(也称为暴力破解)。 

手把手教你搭建区块链(上)| 技术帖

这是哈希函数md5,可从任何输入数据创建一个32个字符的十六进制输出

掌握了区块,哈希等基本概念之后,您还需要为搭建区块链做一些环境准备工作:请您确保您的电脑已安装 Python 3.6以上(以及pip)、Flask和Requests库。

pip install Flask==0.12.2 requests==2.18.4 

 Step 1 搭建区块链

打开你最喜欢的文本编辑器或IDE,推荐使用PyCharm;创建一个新文件,名为blockchain.py

创建一个Blockchain类,创建两个初始的空列表作为构造函数,一个用于存储我们的区块链,另一个用于存储交易。

class Blockchain(object):

    def __init__(self):

        self.chain = []

        self.current_transactions = []

    def new_block(self):

        # Creates a new Block and adds it to the chain

        pass

    def new_transaction(self):

        # Adds a new transaction to the list of transactions

        pass

    @staticmethod

    def hash(block):

        # Hashes a Block

        pass

    @property

    def last_block(self):

        # Returns the last Block in the chain

        pass

这个区块链类负责管理链。,它存储事务,并具有一些用于将新块添加到链中的辅助方法。 

”Block到底长什么样?“

每个Block都有一个索引index,一个时间戳timestamp(以Unix时间表示),一个事务列表,一个proof证明(稍后会有更多介绍)以及前一个块的哈希值。如下面代码所示:

block = {

    ‘index’: 1,

    ‘timestamp’: 1506057125.900785,

    ‘transactions’: [

        {

            ‘sender’: “8527147fe1f5426f9dd545de4b27ee00”,

            ‘recipient’: “a77f5cdfa2934df3954a5c7c7da5df1f”,

            ‘amount’: 5,

        }

    ],

    ‘proof’: 324984774000,

    ‘previous_hash’: “2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824”

}

此时链的概念应该很明显了:每个新块本身都包含前一个块的哈希。这很关键,因为这使区块链具有不变性,即:如果攻击者破坏了链中较早的区块,则所有后续区块都将包含不正确的哈希。

”将交易添加到区块“

创建一个new_transaction()方法,将交易添加到区块:

class Blockchain(object):

    …

    def new_transaction(self, sender, recipient, amount):

        “””

        Creates a new transaction to go into the next mined Block

        :param sender: <str> Address of the Sender

        :param recipient: <str> Address of the Recipient

        :param amount: <int> Amount

        :return: <int> The index of the Block that will hold this transaction

        “””

        self.current_transactions.append({

            ‘sender’: sender,

            ‘recipient’: recipient,

            ‘amount’: amount,

        })​

        return self.last_block[‘index’] + 1

new_transaction()将事务添加到列表之后,它将返回要添加该事务的块的索引:即下一个要挖掘的块。这对于提交事务的用户很有用。

”创建一个新区块“

实例化我们的区块链时,我们需要使用创世区块(就是前面没有任何区块)。

我们还需要在创世区块中添加“证明”,这是挖矿(或工作量证明Proof of Work)的结果。 关于Pow可以参考我之前写过的文章:金融小课堂 | 加密货币一级市场概述(上)

除了在构造函数中创建创世区块之外,我们还需要实例化new_block(),new_transaction()和hash()这三个方法:

import hashlib

import json

from time import time

class Blockchain(object):

    def __init__(self):

        self.current_transactions = []

        self.chain = []

        # Create the genesis block

        self.new_block(previous_hash=1, proof=100)

    def new_block(self, proof, previous_hash=None):

        “””

        Create a new Block in the Blockchain

        :param proof: <int> The proof given by the Proof of Work algorithm

        :param previous_hash: (Optional) <str> Hash of previous Block

        :return: <dict> New Block

        “””

​        block = {

            ‘index’: len(self.chain) + 1,

            ‘timestamp’: time(),

            ‘transactions’: self.current_transactions,

            ‘proof’: proof,

            ‘previous_hash’: previous_hash or self.hash(self.chain[-1]),

        }

        # Reset the current list of transactions

        self.current_transactions = []

​        self.chain.append(block)

        return block

​    def new_transaction(self, sender, recipient, amount):

        “””

        Creates a new transaction to go into the next mined Block

        :param sender: <str> Address of the Sender

        :param recipient: <str> Address of the Recipient

        :param amount: <int> Amount

        :return: <int> The index of the Block that will hold this transaction

        “””

        self.current_transactions.append({

            ‘sender’: sender,

            ‘recipient’: recipient,

            ‘amount’: amount,

        })​

        return self.last_block[‘index’] + 1

​    @property

    def last_block(self):

        return self.chain[-1]

    @staticmethod

    def hash(block):

        “””

        Creates a SHA-256 hash of a Block

        :param block: <dict> Block

        :return: <str>

        “””

​        # We must make sure that the Dictionary is Ordered, or we’ll have inconsistent hashes

        block_string = json.dumps(block, sort_keys=True).encode()

        return hashlib.sha256(block_string).hexdigest()

这样一个简单的区块链就大功告成了。 

如果您会好奇更深层的问题,比如如何创建,伪造或开采新的区块

转载声明:本文 由CoinON抓取收录,观点仅代表作者本人,不代表CoinON资讯立场,CoinON不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。若以此作为投资依据,请自行承担全部责任。

声明:图文来源于网络,如有侵权请联系删除

风险提示:投资有风险,入市需谨慎。本资讯不作为投资理财建议。

(0)
打赏 微信扫一扫 微信扫一扫
上一篇 2019年12月25日 下午12:19
下一篇 2019年12月25日 下午12:20

相关推荐

手把手教你搭建区块链(上)| 技术帖

星期三 2019-12-25 12:19:55

“学习区块链的最快方法就是自己亲手搭建一个”

如果您已经掌握了一些基础的python知识,那么跟着本文搭建区块链对您来说将不是一件难事儿。

手把手教你搭建区块链(上)| 技术帖

在开始之前,有一些概念需要您先明确:

1. 区块链是一个不变的顺序记录链,称为块。它们可以包含事务,文件或任何您想要记录的数据。您只需记住,它们使用哈希值链接在一起。

2. 哈希函数就是一个简单的函数,它接受输入值,并根据该输入创建确定输入值的输出值。对于任何x输入值,只要运行哈希函数,您将始终收到相同的y输出值。这样,每个输入都有一个确定的输出。哈希函数通常是不可逆的(单向),这意味着仅知道输出就无法弄清楚输入-除非尝试所有可能的输入(也称为暴力破解)。 

手把手教你搭建区块链(上)| 技术帖

这是哈希函数md5,可从任何输入数据创建一个32个字符的十六进制输出

掌握了区块,哈希等基本概念之后,您还需要为搭建区块链做一些环境准备工作:请您确保您的电脑已安装 Python 3.6以上(以及pip)、Flask和Requests库。

pip install Flask==0.12.2 requests==2.18.4 

 Step 1 搭建区块链

打开你最喜欢的文本编辑器或IDE,推荐使用PyCharm;创建一个新文件,名为blockchain.py

创建一个Blockchain类,创建两个初始的空列表作为构造函数,一个用于存储我们的区块链,另一个用于存储交易。

class Blockchain(object):

    def __init__(self):

        self.chain = []

        self.current_transactions = []

    def new_block(self):

        # Creates a new Block and adds it to the chain

        pass

    def new_transaction(self):

        # Adds a new transaction to the list of transactions

        pass

    @staticmethod

    def hash(block):

        # Hashes a Block

        pass

    @property

    def last_block(self):

        # Returns the last Block in the chain

        pass

这个区块链类负责管理链。,它存储事务,并具有一些用于将新块添加到链中的辅助方法。 

”Block到底长什么样?“

每个Block都有一个索引index,一个时间戳timestamp(以Unix时间表示),一个事务列表,一个proof证明(稍后会有更多介绍)以及前一个块的哈希值。如下面代码所示:

block = {

    ‘index’: 1,

    ‘timestamp’: 1506057125.900785,

    ‘transactions’: [

        {

            ‘sender’: “8527147fe1f5426f9dd545de4b27ee00”,

            ‘recipient’: “a77f5cdfa2934df3954a5c7c7da5df1f”,

            ‘amount’: 5,

        }

    ],

    ‘proof’: 324984774000,

    ‘previous_hash’: “2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824”

}

此时链的概念应该很明显了:每个新块本身都包含前一个块的哈希。这很关键,因为这使区块链具有不变性,即:如果攻击者破坏了链中较早的区块,则所有后续区块都将包含不正确的哈希。

”将交易添加到区块“

创建一个new_transaction()方法,将交易添加到区块:

class Blockchain(object):

    …

    def new_transaction(self, sender, recipient, amount):

        “””

        Creates a new transaction to go into the next mined Block

        :param sender: <str> Address of the Sender

        :param recipient: <str> Address of the Recipient

        :param amount: <int> Amount

        :return: <int> The index of the Block that will hold this transaction

        “””

        self.current_transactions.append({

            ‘sender’: sender,

            ‘recipient’: recipient,

            ‘amount’: amount,

        })​

        return self.last_block[‘index’] + 1

new_transaction()将事务添加到列表之后,它将返回要添加该事务的块的索引:即下一个要挖掘的块。这对于提交事务的用户很有用。

”创建一个新区块“

实例化我们的区块链时,我们需要使用创世区块(就是前面没有任何区块)。

我们还需要在创世区块中添加“证明”,这是挖矿(或工作量证明Proof of Work)的结果。 关于Pow可以参考我之前写过的文章:金融小课堂 | 加密货币一级市场概述(上)

除了在构造函数中创建创世区块之外,我们还需要实例化new_block(),new_transaction()和hash()这三个方法:

import hashlib

import json

from time import time

class Blockchain(object):

    def __init__(self):

        self.current_transactions = []

        self.chain = []

        # Create the genesis block

        self.new_block(previous_hash=1, proof=100)

    def new_block(self, proof, previous_hash=None):

        “””

        Create a new Block in the Blockchain

        :param proof: <int> The proof given by the Proof of Work algorithm

        :param previous_hash: (Optional) <str> Hash of previous Block

        :return: <dict> New Block

        “””

​        block = {

            ‘index’: len(self.chain) + 1,

            ‘timestamp’: time(),

            ‘transactions’: self.current_transactions,

            ‘proof’: proof,

            ‘previous_hash’: previous_hash or self.hash(self.chain[-1]),

        }

        # Reset the current list of transactions

        self.current_transactions = []

​        self.chain.append(block)

        return block

​    def new_transaction(self, sender, recipient, amount):

        “””

        Creates a new transaction to go into the next mined Block

        :param sender: <str> Address of the Sender

        :param recipient: <str> Address of the Recipient

        :param amount: <int> Amount

        :return: <int> The index of the Block that will hold this transaction

        “””

        self.current_transactions.append({

            ‘sender’: sender,

            ‘recipient’: recipient,

            ‘amount’: amount,

        })​

        return self.last_block[‘index’] + 1

​    @property

    def last_block(self):

        return self.chain[-1]

    @staticmethod

    def hash(block):

        “””

        Creates a SHA-256 hash of a Block

        :param block: <dict> Block

        :return: <str>

        “””

​        # We must make sure that the Dictionary is Ordered, or we’ll have inconsistent hashes

        block_string = json.dumps(block, sort_keys=True).encode()

        return hashlib.sha256(block_string).hexdigest()

这样一个简单的区块链就大功告成了。 

如果您会好奇更深层的问题,比如如何创建,伪造或开采新的区块