看啥推荐读物
专栏名称: 贺小三
纨绔子弟、贺百万、贺英俊、贺七七、贺叔叔、贺百科、贺会玩、贺好帅、贺天才、贺虚伪、贺薄情、乔帅格的远房表哥、妮妮的欧洲养老院同伴、资深王教人、小尼克。创业失败,娶妻生子。学术无果,回家种地。
今天看啥  ›  专栏  ›  贺小三

简单区块链的实现 in Python 3 (一)

贺小三  · 简书  ·  · 2018-02-06 02:25
Block

Blockchain

稍微懂一点 C 语言中的指针 (Pointer)就很容易明白区块链的基本结构。

Pointer
#!/usr/bin/env python3
# # -*- coding: utf-8 -*-

import hashlib

class Block:

    def __init__(self, index, timestamp, data, previousHash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previousHash = previousHash
        self.hash = self.calculateHash();

    def calculateHash(self):
        sha256 = hashlib.sha256()
        sha256.update((str(self.index) + self.previousHash + self.timestamp + self.data).encode('utf-8'))
        res = sha256.hexdigest()
        return res

    def __str__(self):
        return "index:" + str(self.index) + " timestamp:" + str(self.timestamp) + " data:" + str(self.data) + " previousHash:" + str(self.previousHash) + " hash:" + str(self.hash) 

class Blockchain:

    def __init__(self):
        self.chain = [self.createGenesisBlock()];

    def createGenesisBlock(self):
        return Block(0, "01/01/2017", "Genesis block", "0");

    def getLatestBlock(self):
        return self.chain[len(self.chain) - 1]

    def addBlock(self, newBlock):
        newBlock.previousHash = self.getLatestBlock().hash
        newBlock.hash = newBlock.calculateHash()
        self.chain.append(newBlock)

    def display(self):
        for i in range(len(self.chain)):
            print (self.chain[i])
            print ("")

coin = Blockchain()
coin.addBlock(Block(1, "20/07/2017", "data-1", ""));
coin.display()
output

How does a blockchain work - Simply Explained (YouTube)




原文地址:访问原文地址
快照地址: 访问文章快照