繁体   English   中英

如何使用助记词创建 Web3py 帐户

[英]How to create a Web3py account using mnemonic phrase

我正在用 web3 制作自己的桌面 BSC 钱包。 目前我正在使用

private_key = "private key"
account = w3.eth.account.privateKeyToAccount(private_key)

但我想使用助记短语创建帐户,如“hello john pizza guitar”。 我一直在寻找,但我无法实现它。

目前请求的功能在 Web3.py 中不稳定

  • 选项 1:使用像Ethereum Mnemonic Utils这样的库来处理你的种子。
  • 选项 2:在 web3py 中启用未经审核的功能
web3 = Web3()
web3.eth.account.enable_unaudited_hdwallet_features()
account = web3.eth.account.from_mnemonic(my_mnemonic, account_path="m/44'/60'/0'/0/0")

注意:默认的account_path也匹配 Ethereum 和 BSC。 迭代最后一个数字你会得到下一个账户。 账号object可以管理一些操作

account.address # The address for the chosen path
account.key # Private key for that address

如果你不关心使用未经审计的功能,你可以使用这个:

    w3.eth.account.enable_unaudited_hdwallet_features()
    account = w3.eth.account.from_mnemonic("hello john pizza guitar")
    print(account.address)

我在文档中找不到任何关于未经审核功能的提及,但只需查看此(帐户)object 的属性,我就会发现您具有以下属性:

  • 地址
  • 加密
  • 钥匙
  • 私钥
  • 符号散列
  • 签署交易
  • 签名消息
  • sign_transaction

完整列表(包括私有属性):

['__abstractmethods__', '__bytes__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_address', '_key_obj', '_private_key', '_publicapi', 'address', 'encrypt', 'key', 'privateKey', 'signHash', 'signTransaction', 'sign_message', 'sign_transaction']

您可能不应该使用此帐户 object 来签署交易,因为它没有记录,并且在文档的所有示例中,交易通常使用 web3.eth.sign_transaction(txn, key) 使用私钥签署。 您将很难找到有关此 object 及其功能的信息,由于 vscode 自动完成功能,我偶然发现了此 function

相反,使用它来检索私钥并按照文档中所示使用它

pk = account.privateKey

此代码生成 10 个地址及其私钥:

from web3 import Web3
w3 = Web3()

# test mnemonic from ganache (don't use it!)
mnemonic = "witness explain monitor check grid depend music purchase ready title bar federal"

w3.eth.account.enable_unaudited_hdwallet_features()
for i in range(10):
    acc = w3.eth.account.from_mnemonic(mnemonic, account_path=f"m/44'/60'/0'/0/{i}")
    print(f"\naddress{i} = ", acc.address)
    print(f"private{i} = ", Web3.toHex(acc.key))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM