#!/usr/bin/env python
# coding: utf-8

1.1 无工作量证明的区块链版本

# In[ ]:


import hashlib
class Block:
        def __init__(self, data, prev_hash):
            self.previous_hash = prev_hash
            self.data = data
        
        # 计算区块的哈希值
        @property
        def hash(self):
            message = hashlib.sha256()
            message.update(str(self.data).encode('utf-8'))
            return message.hexdigest()
            


# In[ ]:


def create_genesis_block():
    '''
    生成创世区块,为第一个区块,无父区块哈希
    '''
    return Block(data='Genesis Block', prev_hash='')


# In[ ]:


class BlockChain:
    '''
        区块链结构体
    '''
    def __init__(self):
        self.blocks = [create_genesis_block()]
    
    def add_block(self, data):
        '''
        添加区块
        '''
        pre_block = self.blocks[len(self.blocks) - 1]
        new_block = Block(data, pre_block.hash)
        self.blocks.append(new_block)
        return new_block
    


# In[ ]:


# 创建区块链


bc = BlockChain()
# print(bc.blocks)
b1 = bc.add_block('Jack send 0.3 btc to Alice')
b2 = bc.add_block('Alice send 0.1 btc to Tom') 


# In[ ]:


for b in bc.blocks:
    print('Prev Hash: {}'.format(b.previous_hash))
    print('Data: {}'.format(b.data))
    print('Hash: {}'.format(b.hash))
    print('\n')


# In[ ]:


b1.data = 'Jack send 1.3 btc to Alice' # 篡改数据


# In[ ]:


for i, b in enumerate(bc.blocks):
    print('Prev Hash: {}'.format(b.previous_hash))
    print('Data: {}'.format(b.data))
    print('Hash: {}'.format(b.hash))
    if b.previous_hash and b.previous_hash != bc.blocks[i-1].hash:
        print('Invaid Block!!')
    else:
        print('Valid Block')
    print('\n')

1.2 工作量证明的区块链版本

·说白了,区块链就是一种数据结构,这种数据结构具有防篡改性
·工作量证明就是限制区块链的数量,产生的哈希值需要满足一定条件!
# In[33]:


import hashlib

class ProofOfWork():
    '''
    工作量证明
    '''
    def __init__(self, block):
        self.block = block
        
    def mine(self):
        i = 1 # 一定不能设置全局变量,因为种子是i和存储的数据,每次肯定会变!!!
        prefix = '0000'
        
        while True:
            nouce = str(i)
            message = hashlib.sha256() # 只是创建一个类
            message.update(str(self.block.data).encode('utf-8'))
            message.update(nouce.encode('utf-8'))
            digest = message.hexdigest()
#             print(digest)
            if digest.startswith(prefix):
                print(self.block.data, digest, i, end = '\n--------------------------------------------\n')
                return nouce, digest
            i += 1
            
            if not i%50000:
                print(self.block.data, digest, i)
            

            


# In[29]:


import hashlib
class Block:
        def __init__(self, data, prev_hash):
            self.previous_hash = prev_hash
            self.data = data
            self.nouce = ''
        
        # 计算区块的哈希值
        @property
        def hash(self):
            message = hashlib.sha256()
            message.update(str(self.data).encode('utf-8'))
            message.update(str(self.nouce).encode('utf-8'))
            digest = message.hexdigest()
            return message.hexdigest()
            


# In[30]:


def create_genesis_block():
    '''
    生成创世区块,为第一个区块,无父区块哈希
    
    '''
    block = Block(data = 'Genesis Block', prev_hash='')
    pow = ProofOfWork(block)
    nouce, digest = pow.mine()
    block.nouce = nouce
    return block


# In[31]:


class BlockChain:
    '''
        区块链结构体
    '''
    def __init__(self):
        self.blocks = [create_genesis_block()]
    
    def add_block(self, data):
        '''
        添加区块
        '''
        prev_block = self.blocks[len(self.blocks) - 1]
        block = Block(data, prev_block.hash)
        pow = ProofOfWork(block)
        nouce, digest = pow.mine()
        block.nouce = nouce
        self.blocks.append(block)
    


# In[32]:


# 创建区块链


bc = BlockChain()
# print(bc.blocks)
b1 = bc.add_block('Jack send 0.3 btc to Alice')
b2 = bc.add_block('Alice send 0.1 btc to Tom') 
b3 = bc.add_block('Cat send 0.3 btc to Tom')
b4 = bc.add_block('Bob send 0.8 btc to Tom')


# In[11]:


for b in bc.blocks:
    print('Prev Hash: {}'.format(b.previous_hash))
    print('Data: {}'.format(b.data))
    print('Hash: {}'.format(b.hash))
    print('\n')



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐