简体   繁体   English

AttributeError: '_hashlib.HASH' object 没有属性 'startswith'

[英]AttributeError: '_hashlib.HASH' object has no attribute 'startswith'

class Block:
   def __init__(self):
      self.verified_transactions = []
      self.previous_block_hash = ""
      self.Nonce = ""

   def mine(message, difficulty=1):
      assert difficulty >= 1
      prefix = '1' * difficulty
      for i in range(1000):
         digest = hashlib.sha256(str(hash(message)).encode('utf-8') + str(i).encode('utf-8'))
         if digest.startswith(prefix):
            print ("after " + str(i) + " iterations found nonce: "+ digest)
         return digest
error: Traceback (most recent call last):
  File "c:/Users/thoma/Desktop/Client.py", line 113, in <module>
    Block.mine ("test message", 2)
  File "c:/Users/thoma/Desktop/Client.py", line 94, in mine
    if str(digest.startswith(prefix)):
AttributeError: '_hashlib.HASH' object has no attribute 'startswith'

---- complete code----- ---- 完整代码-----

# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
# following imports are required by PKI
import Cryptodome
import Cryptodome.Random
from Cryptodome.Hash import SHA
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5


transactions = []
last_block_hash = ""
TPCoins = []

def sha256(message):
      return hashlib.sha256(message.encode('ascii')).hexdigest()

class Client:
   def __init__(self):
      random = Cryptodome.Random.new().read
      self._private_key = RSA.generate(1024, random)
      self._public_key = self._private_key.publickey()
      self._signer = PKCS1_v1_5.new(self._private_key)

   @property
   def identity(self):
      return binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')

class Transaction:
   def __init__(self, sender, recipient, value):
      self.sender = sender
      self.recipient = recipient
      self.value = value
      self.time = datetime.datetime.now() 

   def to_dict(self):
      if self.sender == "Genesis":
         identity = "Genesis"
      else:
         identity = self.sender.identity

      return collections.OrderedDict({
         'sender': identity,
         'recipient': self.recipient,
         'value': self.value,
         'time' : self.time})

   def sign_transaction(self):
      private_key = self.sender._private_key
      signer = PKCS1_v1_5.new(private_key)
      h = SHA.new(str(self.to_dict()).encode('utf8'))
      return binascii.hexlify(signer.sign(h)).decode('ascii')

   def display_transaction(transaction):
      #for transaction in transactions:
      dict = transaction.to_dict()
      print ("sender: " + dict['sender'])
      print ('-----')
      print ("recipient: " + dict['recipient'])
      print ('-----')
      print ("value: " + str(dict['value']))
      print ('-----')
      print ("time: " + str(dict['time']))
      print ('-----')

   def dump_blockchain (self):
      print ("Number of blocks in the chain: " + str(len (self)))
      for x in range (len(TPCoins)):
         block_temp = TPCoins[x]
         print ("block # " + str(x))
         for transaction in block_temp.verified_transactions:
            Transaction.display_transaction (transaction)
            print ('--------------')
         print ('=====================================')

class Block:
   def __init__(self):
      self.verified_transactions = []
      self.previous_block_hash = ""
      self.Nonce = ""

   def mine(message, difficulty=1):
      assert difficulty >= 1
      prefix = '1' * difficulty
      for i in range(1000):
         digest = hashlib.sha256(str(hash(message)).encode('utf-8') + str(i).encode('utf-8'))
         if digest.startswith(prefix):
            print ("after " + str(i) + " iterations found nonce: "+ digest)
         return digest


#genesis block & users initialisation
Thomas = Client()
IoT_Sensor = Client()
Node = Client()
IoT_Device = Client()
t0 = Transaction("Genesis",Thomas.identity,200.0)
block0 = Block()
block0.previous_block_hash = None
Nonce = None
block0.verified_transactions.append (t0)
digest = hash (block0)
last_block_hash = digest
TPCoins.append (block0)
Transaction.dump_blockchain(TPCoins)
Block.mine ("test message", 2)

Any thoughts?有什么想法吗? I am working off a tutorial @ python blockchain tutorial我正在写一个教程@ python 区块链教程

I believe the issue is the variable digest is not a str but rather a hashlib.sha256 object and thus.startswith() is not recognised.我认为问题在于变量摘要不是 str 而是 hashlib.sha256 object 并且因此.startswith() 未被识别。 I have tried casting to str() without any luck.我尝试过强制转换为 str() ,但没有任何运气。

Thanks for any help everyone.感谢大家的帮助。

Solution thanks to furas:)感谢 furas 的解决方案:)

def mine(message, difficulty=1):
      assert difficulty >= 1
      prefix = '1' * difficulty
      for i in range(1000):
         digest = sha256(str(hash(message)) + str(i))
         if digest.startswith(prefix):
            print ("after " + str(i) + " iterations found nonce: "+ digest)
            return digest

output: output:

after 303 iterations found nonce: 11337d455c3d425b33cbeeb23fc87d6a3e7c05bf0d27f648e6c9df2f87eea2fb

See tutorial again.再看教程。

It uses own function sha256() instead of standard hashlib.sha256() and this sha256() has .hexdigest() at the end:它使用自己的 function sha256()而不是标准的hashlib.sha256()并且这个sha256()最后有.hexdigest()

def sha256(message):
    return hashlib.sha256(message.encode('ascii')).hexdigest()

And later it uses this sha256() before digest.startswith()后来它在digest.startswith() sha256() )

  digest = sha256(...)
  if digest.startswith(prefix):
      # ... code ...

And your forgot .hexdigest() in your code.并且您在代码中忘记了.hexdigest()

  digest = hashlib.sha256(...).hexdigest()
  if digest.startswith(prefix):
      # ... code ...

By the way: I think return digest in tutorial is in wrong place - it will return digest in first loop but it should do this inside if digest.startswith(prefix):顺便说一句:我认为教程中的return digest在错误的位置 - 它会在第一个循环中返回digest ,但if digest.startswith(prefix):

     digest = hashlib.sha256(str(hash(message)).encode('utf-8') + str(i).encode('utf-8')).hexdigest()

     if digest.startswith(prefix):
        print("after", i, "iterations found nonce:", digest)
        return digest

If after 1000 iterations it will not find digest with prefix then it will return None如果在 1000 次迭代后找不到带有前缀的摘要,那么它将返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法腌制“_hashlib.HASH”对象 - TypeError: cannot pickle '_hashlib.HASH' object TypeError:object .__ new __(_ hashlib.HASH)不安全,请使用_hashlib.HASH .__ new __() - TypeError: object.__new__(_hashlib.HASH) is not safe, use _hashlib.HASH.__new__() AttributeError:&#39;NoneType&#39;对象没有属性&#39;startswith&#39; - AttributeError: 'NoneType' object has no attribute 'startswith' RobotFramework:AttributeError:“列表”对象没有属性“ startswith” - RobotFramework : AttributeError: 'list' object has no attribute 'startswith' Python AttributeError:“ tuple”对象在hashlib.encode中没有属性“ encode” - Python AttributeError: 'tuple' object has no attribute 'encode' in hashlib.encode AttributeError:使用Python httplib时,“ tuple”对象没有属性“ startswith” - AttributeError: 'tuple' object has no attribute 'startswith' when using Python httplib 烧瓶错误:AttributeError:&#39;NoneType&#39;对象没有属性&#39;startswith&#39; - Flask error: AttributeError: 'NoneType' object has no attribute 'startswith' AttributeError: &#39;tuple&#39; 对象在开始迁移时没有属性 &#39;startswith&#39; - AttributeError: 'tuple' object has no attribute 'startswith' when start migrate AttributeError: &#39;NoneType&#39; 对象在启动 Django 应用程序时没有属性 &#39;startswith&#39; - AttributeError: 'NoneType' object has no attribute 'startswith' while launching the Django App 在服务器上运行 collectstatic :AttributeError: &#39;PosixPath&#39; 对象没有属性 &#39;startswith&#39; - Running collectstatic on server : AttributeError: 'PosixPath' object has no attribute 'startswith'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM