生成区块链标头失败,出现错误

2024-09-29 06:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试处理块链头,但代码停止时出现以下错误-

Traceback (most recent call last): File "C:\Users\SHAHRIAR\AppData\Local\Programs\Python\Python37-32\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) TypeError: a bytes-like object is required, not 'str'

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "f:/PYTHON/blockchain/index.py", line 19, in struct.pack('<L', blockChainObject['bits']) + TypeError: decoding with 'utf-8' codec failed (TypeError: a bytes-like object is required, not 'str')

这是我的全部代码-

import hashlib
import codecs
import struct

blockChainObject = {
    'version':536871426,
    'previousHash':'aa11661d07d7e13b94403bc00a9786b07fe711140743f0f9d7e35a478d80e840',
    'merkleRoot':'a41494afe694e450a7163103fd08ea3d4b5fcb30556165f6e567893989c39222',
    'bits': 0x19030d6c,
    'time':1610982871,
    'nonce':3341292488
}

blockChainHeader = (
    struct.pack('<L', blockChainObject['version']) + 
    codecs.decode(blockChainObject['previousHash'])[::-1] + 
    codecs.decode(blockChainObject['merkleRoot'])[::-1] + 
    struct.pack('<L', blockChainObject['time']) + 
    struct.pack('<L', blockChainObject['bits']) + 
    struct.pack('<L', blockChainObject['nonce'])
)

blockChainHashObject = hashlib.sha256(blockChainHeader).digest()
blockChainHashDigest = hashlib.sha256(blockChainHashObject).hexdigest()

print(blockChainHashDigest)

我正在Win7(64位)上运行Python 3.7.2

我在征求专家的意见,我做错了什么


Tags: 代码importmostcallstructpackutfbits
1条回答
网友
1楼 · 发布于 2024-09-29 06:35:44

您必须转换argument of 解码functions to字节. Also struct.pack返回bytescodecs.decode返回string,因此还必须将decode的结果转换为字节

import hashlib
import codecs
import struct
import sys

blockChainObject = {
    'version':536871426,
    'previousHash': b'aa11661d07d7e13b94403bc00a9786b07fe711140743f0f9d7e35a478d80e840',
    'merkleRoot': b'a41494afe694e450a7163103fd08ea3d4b5fcb30556165f6e567893989c39222',
    'bits': 0x19030d6c,
    'time':1610982871,
    'nonce':3341292488
}


blockChainHeader = (
    struct.pack('<L', blockChainObject['version']) +
    bytes(codecs.decode(blockChainObject['previousHash'])[::-1], 'utf-8') +
    bytes(codecs.decode(blockChainObject['merkleRoot'])[::-1], 'utf-8') +
    struct.pack('<L', blockChainObject['time']) +
    struct.pack('<L', blockChainObject['bits']) +
    struct.pack('<L', blockChainObject['nonce'])
)

blockChainHashObject = hashlib.sha256(blockChainHeader).digest()
blockChainHashDigest = hashlib.sha256(blockChainHashObject).hexdigest()

print(blockChainHashDigest)

结果: 2d2a436603cca71be4c27b51e5e1aa7911cc6cf4ff5ad67a13c17ab7127d7f85

相关问题 更多 >