【问题标题】:Convert Bitcoin private key from file text从文件文本转换比特币私钥
【发布时间】:2021-08-25 12:29:51
【问题描述】:

朋友们下午好,我刚开始学习python,我发现这段代码适合我的需要,但是在输出的过程中,一切都是同步的,请帮我解决这个问题。 "

import ecdsa
import hashlib
import base58


with open("my_private_key.txt", "r") as f:    #Input file path
  for line in f:

              #Convert hex private key to bytes
     private_key = bytes.fromhex(line)      

              #Derivation of the private key
     signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
     verifying_key = signing_key.get_verifying_key()

     public_key = bytes.fromhex("04") + verifying_key.to_string()

             #Hashes of public key
     sha256_1 = hashlib.sha256(public_key)
     ripemd160 = hashlib.new("ripemd160")
     ripemd160.update(sha256_1.digest())

             #Adding prefix to identify Network
     hashed_public_key = bytes.fromhex("00") + ripemd160.digest()

             #Checksum calculation
     checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
     checksum = checksum_full[:4]

             #Adding checksum to hashpubkey         
     bin_addr = hashed_public_key + checksum

             #Encoding to address
     address = str(base58.b58encode(bin_addr))
     final_address = address[2:-1]

     print(final_address)

     with open("my_addresses.txt", "a") as i:
        i.write(final_address)

"

【问题讨论】:

  • 您好,欢迎@kamburishka,为了让人们正确回答您的问题,我认为如果您能详细说明会有所帮助。当您说“所有内容都在一行中同步”时,您是说很难读取/解释输出,因为它呈现在一大块中?

标签: python bitcoin private-key


【解决方案1】:

print 在写入所有参数后写入尾随换行符。 write 没有;您必须自己提供。

with open("my_addresses.txt", "a") as i:
    i.write(final_address + "\n")

或者,您可以使用print

with open("my_addresses.txt", "a") as i:
    print(final_address, file=i)

忽略它的许多关键字参数,print 的定义类似于

def print(*args, end='\n', sep=' ', file=sys.stdout):
    file.write(sep.join(args))
    file.write(end)
    

另外,请注意您不需要重复打开输出文件。您可以在输入的同时打开它,并在循环期间保持打开状态。

with open("my_private_key.txt", "r") as f, \
     open("my_addresses.txt", "a") as i:
    for line in f:
        ...
        print(final_address, file=i)

【讨论】:

  • 非常感谢大家的帮助
  • 亲爱的朋友@chepner,你不能告诉我如何在这个脚本中添加多线程,它工作得很慢
猜你喜欢
  • 2014-01-17
  • 2021-12-25
  • 2023-03-13
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2019-05-16
相关资源
最近更新 更多