我正在用web3制作我自己的桌面BSC钱包。目前我正在使用
private_key = "private key"
account = w3.eth.account.privateKeyToAccount(private_key)
但我想用一个助记符短语创建账户,比如";你好,约翰披萨吉他;。我一直在寻找,但我没能做到
此时请求的功能在Web3.py 内不稳定
- 选项1:使用一些库,如以太坊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
也匹配以太坊和BSC。重复最后一个数字,你会得到下一个账户。账户对象可以管理一些操作
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)
我在文档中找不到任何未经审计的功能,但只要查看这个(帐户(对象的属性,我就会发现你有以下属性:
- 地址
- 加密
- 钥匙
- privateKey
- signHash
- signTransaction
- 签名消息
- 签名交易
完整列表(包括私有属性(:
['__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']
您可能不应该使用此帐户对象对事务进行签名,因为它没有文档,并且在所有文档示例中,事务通常使用web3.eth.sign_transaction(txn,key(使用私钥进行签名。你很难找到关于这个对象及其功能的信息,由于上的vscode自动完成,我偶然发现了这个功能
相反,使用它来检索私钥,并使用它,如文档中所示
pk = account.privateKey
这段代码生成了10个地址,它们的私钥可以在您的python代码中复制/通过:
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 + 1} = '{acc.address}'")
print(f"private{i + 1} = '{Web3.toHex(acc.key)}'")