手把手带你做自己的’比特币‘(上)

本篇我用python实现一个本地的区块,要实现完整的区块链还需要做分布式服务器,很多很多东西。先实现分账, 使用区块链进行交易的比特币以及其他加密货币的交易记录会被按时间顺序存储,并且是公开存储。通俗的说,区块链是一个公共数据库,其中新数据存储在称为块的容器中,并被添加到具有过去添加的数据的不可变链(因此是块链)。在比特币和其他加密货币的情况下,这些数据是一组交易记录,当然,数据可以是任何类型的。比如,区块链2.0的以太坊,就可以在链上建应用,而不单单是一种纯粹的加密数字货币。
在本篇中,每个块都有时间戳和可选的索引,在SnakeCoin中,将同时存储两者,并且为了帮助确保整个块链的完整性,每个块将具有自识别散列。像比特币一样,每个块的散列将是块的索引,时间戳,数据以及前一个块的哈希散列的加密散列
import hashlib as hasher
import datetime as date

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.hash_block()

    def hash_block(self):
        sha = hasher.sha256()
        sha.update(str(self.index).encode('utf-8') +
                   str(self.timestamp).encode('utf-8') +
                   str(self.data).encode('utf-8') +
                   str(self.previous_hash).encode('utf-8'))
        return sha.hexdigest()

    def __str__(self):
        output = str(self.index) + "  /  " + \
                 str(self.timestamp) + "  /  " + \
                 str(self.data) + "  /  " + \
                 str(self.previous_hash[:10])
        return output

现在我们有了块结构,但是我们正在创建一个块链,需要向实际的链条添加块。如前所述,每个块都需要上一个块的信息。也就是说,出现了一个问题:块区中的第一个块怎么到达那里?因此,第一个块,或起源块,是一个特殊的块。在许多情况下,它是手动添加的或具有允许添加的唯一逻辑值。

我们将创建一个函数返回一个起源块,使事情变得容易。该块的索引为0,它在“previous hash”参数中具有任意数据值和任意值。

def create_genesis_block():
    #手动构造带有索引零和任意先前散列的块
    return Block(0, date.datetime.now(), "Genesis Block", "0")

现在我们可以创建一个起源块,我们需要一个函数来生成块链中的后续块。该函数将将链中的前一个块作为参数,创建要生成的块的数据,并返回具有其相应数据的新块。当新块得到先前块中的哈希信息时,块链的完整性随着每个新的块而增加。如果我们没有这样做,外界信息会更容易“改变过去”,并用自己的更新变化来替代我们的链条。这个哈希链作为加密证明,有助于确保一旦块被添加到块链中,它不能被替换或删除。
def next_block(last_block):
    this_index = last_block.index + 1
    this_timestamp = date.datetime.now()
    this_data = "Hey! I'm block " + str(this_index)
    previous_hash = last_block.hash
    return Block(this_index, this_timestamp, this_data, previous_hash)

以上是必要的工作。现在我们可以创建我们的blockchain!在我们的例子中,blockchain本身就是一个简单的Python列表。列表的第一个元素是起源块。当然,我们需要添加后续的块。因为CCHCoin是最小的块,所以我们只添加20个新的块。我们可以用for循环来做到这一点。
# 创建区块链和添加创世块
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# 我们需要多少块
# 创世块后面的块数
num_of_blocks_to_add = 20

# 添加块到链上
for i in range(0, num_of_blocks_to_add):
    block_to_add = next_block(previous_block)
    blockchain.append(block_to_add)
    previous_block = block_to_add

    print ("Block #{} has been added to the blockchain!".format(block_to_add.index))
    print (block_to_add)
    print ("Hash: {}\n".format(block_to_add.hash))

运行结果:
手把手带你做自己的’比特币‘(上)_第1张图片

你可能感兴趣的:(区块链)