【问题标题】:Base58Check encoding for Bitcoin addresses too long比特币地址的 Base58Check 编码太长
【发布时间】:2014-06-27 05:18:51
【问题描述】:

我正在尝试使用 Python 创建一个比特币地址。我得到了正确的散列部分,但我在使用 Base58Check 编码时遇到了一些问题。我用这个包:

https://pypi.python.org/pypi/base58

这是一个例子:

import base58

unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string)
print(encoded_string)

输出是:

bSLesHPiFV9jKNeNbUiMyZGJm45zVSB8bSdogLWCmvs88wxHjEQituLz5daEGCrHE7R7

根据the technical background for creating Bitcoin addresses,上面的 RIPEMD-160 哈希应该是“16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM”。也就是说,我的输出是错误的,显然太长了。有谁知道我做错了什么?

编辑:

我在 hex (.decode("hex")) 中添加了一个解码:

import base58

unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string.decode("hex"))
print(encoded_string)

现在的输出看起来更好了:

1csU3KSAQMEYLPudM8UWJVxFfptcZSDvaYY477

然而,它仍然是错误的。它必须是字节编码吗?你如何在 Python 中做到这一点?

EDIT2:

现在已修复(感谢 Arpegius)。将 str(bytearray.fromhex( hexstring )) 添加到我的代码中(在 Python 2.7 中):

import base58

hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
unencoded_string = str(bytearray.fromhex( hexstring ))
encoded_string= base58.b58encode(unencoded_string)
print(encoded_string)

输出:

16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

【问题讨论】:

  • unencoded_string 是十六进制编码的吗?您需要先对其进行解码。

标签: python bitcoin


【解决方案1】:

base58.b58encode 中需要一个字节(python2 str)而不是十六进制。你需要先解码:

In [1]: import base58
In [2]: hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
In [3]: unencoded_string = bytes.fromhex(hexstring)
In [4]: encoded_string= base58.b58encode(unencoded_string)
In [5]: print(encoded_string)
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

在 python 2.7 中你可以使用str(bytearray.fromhex( hexstring ))

【讨论】:

  • 谢谢,但我收到以下消息:AttributeError: type object 'str' has no attribute 'fromhex'。我复制了你的代码 1:1。编辑:没关系,现在明白了。非常感谢!
猜你喜欢
  • 2019-05-16
  • 2014-01-17
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2017-03-25
相关资源
最近更新 更多