python挖矿算力测试程序详解

yipeiwu_com6年前Python基础

谈到比特币,我们都知道挖矿,有些人并不太明白挖矿的含义。这里的挖矿其实就是哈希的碰撞,举个简单例子:

import hashlib
x = 11
y = 1
#这里可以调节挖矿难度,也就是哈希的长度
while hashlib.sha256(f'{x*y}'.encode("utf-8")).hexdigest()[5:7]!="00":
  print(x*y)
  y +=1
print("找到了:",(x*y))

结果如下:

当然比特币的挖矿要比这个复杂太多,但是原理差不多,有个大概的认知。

关于节点的同步,是取整个节点中最长的区块链进行同步,如图所示:

有了以上内容铺垫,代码实现和理解就容易了,代码如下:

#挖矿原理与网络共识
import datetime
import hashlib
import json
import requests

class Blockchain2:

  def __init__(self):
    self.chain = [] #区块链列表
    self.nodes = set() #节点集合
    self.current_tranactions = [] #交易列表
    self.new_block(proof=100,preHash=1) #创建第一个区块

  #新建一个区块,需要计算,才能追加
  def new_block(self,proof,preHash = None):
    block={
      "index":len(self.chain)+1,#区块索引
      "timestamp":datetime.datetiem.now(),#区块时间戳
      "transactions":self.current_tranactions,#区块交易记录集合
      "proof":proof,#算力凭证
      "preHash":preHash or self.hash(self.chain[-1]), #上一块的哈希
    }
    self.current_tranactions = [] #开辟新的区块,初始化区块交易记录
    self.chain.append(block)

  @staticmethod
  def hash(block):
    #处理为json字符串格式的哈希
    block_str = json.dumps(block,sort_keys=True).encode("utf-8")
    return hashlib.sha256(block_str).hexdigest()

  #新增交易记录
  def new_transaction(self,sender,receiver,amount):
    transaction ={
      "sender":sender,
      "receiver":receiver,
      "amount":amount,
    }

    self.current_tranactions.append(transaction)

    return self.last_block["index"]+1

  @property
  def last_block(self):
    return self.chain[-1]

  #挖矿,依赖上一个模块,获取工作量证明,即POW共识机制
  def proof_of_work(self,last_block):
    last_proof = last_block["proof"]
    last_hash = self.hash(last_block)
    proof = 0

    while self.valid_proof(last_proof,proof,last_hash) is False:
      proof +=1

    return proof

  #校验工作量
  @staticmethod
  def valid_proof(last_proof,proof,last_hash):
    guess = f'{last_proof}{proof}{last_hash}'.encode("utf-8")
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:6] =="000000" #可以调整计算难度

  #区块一致性,同步算法,
  def resolve_conflicts(self):
    neighbours = self.nodes
    new_chain = None
    max_length = len(self.chain)
    #遍历所有节点,找出最长的链
    for node in neighbours:
      #获取节点区块链信息
      response = requests.get(f'http://{node}/chain')
      if response.status_code ==200:
        length = response.json()["length"]
        chain = response.json()["chain"]

        if length>max_length and self.valid_chain(chain):
          max_length = length
          new_chain = chain

    if new_chain:
      self.chain = new_chain
      return True
    else:
      return False

  #校验区块链的合法性
  def valid_chain(self,chain):
    last_block = chain[0]
    current_index = 1
    #校验每一个区块的prehash,proof合法性
    while current_index <len(chain):
      block = chain[current_index]
      #校验哈希的合法性
      if block["preHash"] != self.hash(last_block):
        return False
      #校验算力的合法性
      if not self.valid_proof(last_block["proof"],block["proof"],block["preHash"]):
        return False
      last_block = block
      current_index +=1
    return True

算力校验和pow共识基本实现了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用PyCharm进行远程开发和调试

python使用PyCharm进行远程开发和调试

背景描述 有时候Python应用的代码在本地开发环境运行十分正常,但是放到线上以后却出现了莫名其妙的异常,经过再三排查以后还是找不到问题原因,于是就在想,要是可以在服务器环境中进行单步跟...

跟老齐学Python之Python文档

跟老齐学Python之Python文档

文档很重要。独孤九剑的剑诀、易筋经的心法、写着辟邪剑谱的袈裟,这些都是文档。连那些大牛人都要这些文档,更何况我们呢?所以,文档是很重要的。 文档,说白了就是用word(这个最多了)等(注...

Python读取Excel表格,并同时画折线图和柱状图的方法

Python读取Excel表格,并同时画折线图和柱状图的方法

今日给大家分享一个Python读取Excel表格,同时采用表格中的数值画图柱状图和折线图,这里只需要几行代码便可以实。 首先我们需要安装一个Excel操作的库xlrd,这个很简单,在安装...

用Python编写一个简单的Lisp解释器的教程

用Python编写一个简单的Lisp解释器的教程

本文有两个目的: 一是讲述实现计算机语言解释器的通用方法,另外一点,着重展示如何使用Python来实现Lisp方言Scheme的一个子集。我将我的解释器称之为Lispy (lis.py)...

PyQt4实时显示文本内容GUI的示例

PyQt4实时显示文本内容GUI的示例

首先创建一个txt.py文件用来保存显示整理好的爬虫内容: #! /usr/bin/env python # -*- coding: utf-8 -*- txt_name = [...