69 lines
2.0 KiB
Python
69 lines
2.0 KiB
Python
from eth_account import Account
|
||
from eth_utils import keccak, to_checksum_address
|
||
from eth_keys import keys
|
||
import os
|
||
|
||
from models.nexus import Nexus
|
||
|
||
|
||
def generate_private_key(mnemonic: str = None) -> dict:
|
||
"""生成符合BIP39/BIP44标准的以太坊私钥(支持助记词和随机生成)"""
|
||
Account.enable_unaudited_hdwallet_features()
|
||
|
||
try:
|
||
if mnemonic:
|
||
# 从助记词派生
|
||
account = Account.from_mnemonic(
|
||
mnemonic,
|
||
account_path="m/44'/60'/0'/0/0"
|
||
)
|
||
private_key = account.key.hex()
|
||
source = 'mnemonic'
|
||
else:
|
||
# 随机生成(符合安全标准)
|
||
private_key = os.urandom(32).hex()
|
||
source = 'random'
|
||
|
||
# 验证私钥有效性
|
||
key_obj = keys.PrivateKey(bytes.fromhex(private_key))
|
||
|
||
# 生成完整地址信息
|
||
public_key = key_obj.public_key
|
||
address = to_checksum_address(public_key.to_address())
|
||
|
||
# 返回包含完整信息的字典
|
||
return {
|
||
'private_key': private_key,
|
||
'public_key': public_key.to_hex(),
|
||
'address': address,
|
||
'source': source,
|
||
'entropy_strength': len(private_key) * 4 # 实际熵位数
|
||
}
|
||
|
||
except Exception as e:
|
||
print(f"生成错误: {str(e)}")
|
||
return None
|
||
|
||
|
||
# 测试用例
|
||
if __name__ == "__main__":
|
||
# 测试助记词模式
|
||
test_mnemonic = "inch habit speak price hamster door street picture recall barrel dust forest"
|
||
|
||
print(generate_private_key(test_mnemonic))
|
||
|
||
# for i in range(10000):
|
||
# # 没有传入地址就是创建新的
|
||
# address = generate_private_key()
|
||
#
|
||
# Nexus.get_or_create(
|
||
# private_key="0x" + address["private_key"],
|
||
# address=address["address"]
|
||
# )
|
||
#
|
||
# # print(address)
|
||
# # print(address["private_key"])
|
||
#
|
||
# # 0x174de758d40e2725ca370ab2053beb14157c5ac09c0b0e11ba1cd4fdcd002cfe
|
||
# # 174de758d40e2725ca370ab2053beb14157c5ac09c0b0e11ba1cd4fdcd002cfe
|