我正在尝试制作一个可以找到丢失的加密钱包的应用程序,我想问你们我可以使用哪些方法来使这个应用程序更高效、更快我希望你们理解我的问题是什么
这是我的Python代码堆栈
import requests
import binascii
from bip_utils import Bip39SeedGenerator, Bip44Coins, Bip44, Bip39WordsNum, Bip39MnemonicGenerator, Bip39Languages
from concurrent.futures import ThreadPoolExecutor
import os
import time
from bs4 import BeautifulSoup
import sys
from colorama import Fore, Back, Style, just_fix_windows_console
just_fix_windows_console()
os.system('cls')
menutitle = 'CryptoTweak V2 | t.me/crptweak'
menutitle = menutitle.replace("|", "^|")
os.system(f'title {menutitle}')
commentar = 0
foundx = 0
total_balance = 0
coinname = None
refreshcount = 0
solanaheaders = {
"accept": "application/json",
"Authorization": "Bearer 7658a30d-dd6f-4aa5-9102-4039dc4773a7"
}
coin_gecko_headers = {
"accept": "application/json"
}
licenseinp = input(Fore.GREEN + "Enter License Key: ")
licenseresponse = requests.get(f"") # corrected the URL
licensecheck = licenseresponse.json()
features = None
if "nolicense" in licensecheck:
os.system('cls')
print(Fore.RED + "Invalid license.\nExiting in 5 seconds.")
time.sleep(5)
os._exit(0)
else:
if "expiredornot" in licensecheck and licensecheck["expiredornot"]:
os.system('cls')
print(Fore.RED + "License not working.")
time.sleep(5)
os._exit(0)
else:
os.system('cls')
print(Fore.GREEN + "License is valid.")
time.sleep(5)
os.system("cls")
plans = []
if "BTC" in licensecheck["plans"]:
plans.append("BTC")
if "ETH" in licensecheck["plans"]:
plans.append("ETH")
if "BNB" in licensecheck["plans"]:
plans.append("BNB")
if "MULTI" in licensecheck["plans"]:
plans.append("MULTI")
plan_str = ", ".join(plans) if plans else "NONE"
menu=f"""\n\n
▄▄· ▄▄▄ ▄· ▄▌ ▄▄▄·▄▄▄▄▄ ▄▄▄▄▄▄▄▌ ▐ ▄▌▄▄▄ . ▄▄▄· ▄ •▄ ✠══════════════ ☩ ☨ ☩ ══════════════✠
▐█ ▌▪▀▄ █·▐█▪██▌▐█ ▄█•██ ▪ •██ ██· █▌▐█▀▄.▀·▐█ ▀█ █▌▄▌▪ t.me/crptweak CryptoTweak V2
██ ▄▄▐▀▀▄ ▐█▌▐█▪ ██▀· ▐█.▪ ▄█▀▄ ▐█.▪██▪▐█▐▐▌▐▀▀▪▄▄█▀▀█ ▐▀▀▄·
▐███▌▐█ █▌ ▐█▀·.▐█▪· ▐█▌·▐█▌.▐▌ ▐█▌ ▐█▌██▐█▌▐█▄▄▌▐█ ▐▌▐█.█▌ ═══════════════════════
▐███▌▐█•█▌ ▐█▀ •▐█ • ▐█▌·▐█▌ ▐▌ ▐█▌·▐█▌██▐█▌▐█▄▄▌▐█ ▪▐▌▐█ █▌ 1. Start Wallet Miner 2.Quit
·▀▀▀ .▀ ▀ ▀ • .▀ ▀▀▀ ▀█▄▀▪ ▀▀▀ ▀▀▀▀ ▀▪ ▀▀▀ ▀ ▀ ·▀ ▀ ✠══════════════ ☩ ☨ ☩ ══════════════✠
\n\n
"""
print(menu.replace('█', Fore.YELLOW+"█"+Fore.RESET).replace('▄', Fore.YELLOW+"▄"+Fore.RESET).replace('▌', Fore.YELLOW+"-"+Fore.RESET).replace('☩', Fore.LIGHTYELLOW_EX+"☩"+Fore.RESET).replace('☨', Fore.YELLOW+"☨"+Fore.RESET).replace('✠', Fore.YELLOW+"✠"+Fore.RESET).replace('·', Fore.LIGHTYELLOW_EX+"·"+Fore.RESET).replace('.', Fore.LIGHTYELLOW_EX+"."+Fore.RESET).replace('▪', Fore.LIGHTYELLOW_EX+"▪"+Fore.RESET).replace('•', Fore.YELLOW+"•"+Fore.RESET).replace('▀', Fore.LIGHTYELLOW_EX+"▀"+Fore.RESET).replace('▐', Fore.LIGHTYELLOW_EX+"▐"+Fore.RESET))
soru = input(Fore.YELLOW + 'Choose: ' + Fore.LIGHTYELLOW_EX)
if soru == '1':
os.system('cls')
refreshcount = 0
while True:
refreshcount += 1
if refreshcount % 100 == 0:
os.system('cls')
print(Fore.GREEN + 'Refreshing The App In 10 Seconds To Prevent Freezing.' + Fore.RESET)
time.sleep(10)
refreshcount = 0
# Generate from mnemonic
mnemonic = Bip39MnemonicGenerator(Bip39Languages.ENGLISH).FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)
mnemonic2 = Bip39MnemonicGenerator(Bip39Languages.ENGLISH).FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
seed_bytes2 = Bip39SeedGenerator(mnemonic2).Generate()
btcaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN).DeriveDefaultPath().PublicKey().ToAddress()
ethaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.ETHEREUM).DeriveDefaultPath().PublicKey().ToAddress()
ltcaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.LITECOIN).DeriveDefaultPath().PublicKey().ToAddress()
dogeaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.DOGECOIN).DeriveDefaultPath().PublicKey().ToAddress()
dashaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.DASH).DeriveDefaultPath().PublicKey().ToAddress()
bscaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.BINANCE_SMART_CHAIN).DeriveDefaultPath().PublicKey().ToAddress()
maticaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.POLYGON).DeriveDefaultPath().PublicKey().ToAddress()
solanaaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.SOLANA).DeriveDefaultPath().PublicKey().ToAddress()
rippleaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.RIPPLE).DeriveDefaultPath().PublicKey().ToAddress()
tronaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.TRON).DeriveDefaultPath().PublicKey().ToAddress()
zecaddr = Bip44.FromSeed(seed_bytes, Bip44Coins.ZCASH).DeriveDefaultPath().PublicKey().ToAddress()
btcaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.BITCOIN).DeriveDefaultPath().PublicKey().ToAddress()
ethaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.ETHEREUM).DeriveDefaultPath().PublicKey().ToAddress()
ltcaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.LITECOIN).DeriveDefaultPath().PublicKey().ToAddress()
dogeaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.DOGECOIN).DeriveDefaultPath().PublicKey().ToAddress()
dashaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.DASH).DeriveDefaultPath().PublicKey().ToAddress()
bscaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.BINANCE_SMART_CHAIN).DeriveDefaultPath().PublicKey().ToAddress()
maticaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.POLYGON).DeriveDefaultPath().PublicKey().ToAddress()
solanaaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.SOLANA).DeriveDefaultPath().PublicKey().ToAddress()
rippleaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.RIPPLE).DeriveDefaultPath().PublicKey().ToAddress()
tronaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.TRON).DeriveDefaultPath().PublicKey().ToAddress()
zecaddr2 = Bip44.FromSeed(seed_bytes2, Bip44Coins.ZCASH).DeriveDefaultPath().PublicKey().ToAddress()
print(Fore.RED + f"PHRASE: {mnemonic}" + Fore.RESET)
print(Fore.RED + f"PHRASE: {mnemonic2}" + Fore.RESET)
# Define a function to fetch the balance for a given address and coin
def fetch_balance(coin, address):
if coin == 'BTC' or coin == 'BTC2':
response = requests.get(f"")
soup = BeautifulSoup(response.text, 'html.parser')
balance_elements = soup.find_all('span', {'class': 'dash-label'})
if balance_elements:
# Extract the balance value
balance_element = balance_elements[2]
balance = balance_element.find_next_sibling(string=True).strip().replace(',', '').replace(' BTC', '')
balance = float(balance)
else:
balance = "0.0"
elif coin == 'ETH' or coin == 'ETH2':
response = requests.get(f"")
balance = response.json()['result']
balance = float(balance) / 10**18
elif coin == 'LTC' or coin == 'LTC2':
response = requests.get(f"")
if response.status_code == 200:
balance = response.json()['balance']
balance = float(balance) / 10**8
else:
response = requests.get(f"")
soup = BeautifulSoup(response.content, 'html.parser')
balance_element = soup.find("dd", {"class": "mt-1 text-sm text-base-content/100 md:col-span-2 sm:mt-0"})
if balance_element is not None:
# Remove any unwanted characters and commas from the balance
balance = float(balance_element.text.strip().replace(',', '').replace(' LTC', ''))
else:
print("0.0")
elif coin == 'DOGE' or coin == 'DOGE2':
response = requests.get(f"")
if response.status_code == 200:
balance = response.json()['balance']
balance = float(balance) / 10**8
else:
response = requests.get(f"")
soup = BeautifulSoup(response.content, 'html.parser')
balance_element = soup.find("dd", {"class": "mt-1 text-sm text-base-content/100 md:col-span-2 sm:mt-0"})
if balance_element is not None:
# Remove any unwanted characters and commas from the balance
balance = float(balance_element.text.strip().replace(',', '').replace(' DOGE', ''))
else:
print("0.0")
elif coin == 'DASH' or coin == 'DASH2':
response = requests.get(f"")
balance = response.json()['balance']
balance = float(balance)
elif coin == 'BNB' or coin == 'BNB2':
response = requests.get(f"")
balance = response.json()['result']
balance = float(balance) / 10**18
elif coin == 'MATIC' or coin == 'MATIC2':
response = requests.get(f"")
balance = response.json()['result']
balance = float(balance) / 10**18
elif coin == 'SOL' or coin == 'SOL2':
response = requests.get(f"", headers=solanaheaders)
balance = response.json()["value"]["base"]["balance"]
balance = float(balance) / 10**9
elif coin == 'TRX' or coin == 'TRX2':
response = requests.get(f"")
balance = response.json()['balance']
balance = float(balance) / 10**6
elif coin == 'ZEC' or coin == 'ZEC2':
response = requests.get(f"")
soup = BeautifulSoup(response.text, 'html.parser')
balance_element = soup.find('span', {'class': 'wb-ba'})
if balance_element:
# Extract the balance value
balance = balance_element.text.strip().replace(',', '')
balance = float(balance.split('+')[1])
else:
balance = "0.0"
else:
raise ValueError(f"Unsupported coin: {coin}")
return coin, balance
# Use a ThreadPoolExecutor with 10 worker threads to fetch the balances concurrently
with ThreadPoolExecutor(max_workers=20) as executor:
features = {}
if "BTC" in licensecheck["plans"]:
features.update({executor.submit(fetch_balance, coin, address): (coin, address) for coin, address in [('BTC', btcaddr), ('BTC2', btcaddr2)]})
if "ETH" in licensecheck["plans"]:
features.update({executor.submit(fetch_balance, coin, address): (coin, address) for coin, address in [('ETH', ethaddr), ('ETH2', ethaddr2)]})
if "BNB" in licensecheck["plans"]:
features.update({executor.submit(fetch_balance, coin, address): (coin, address) for coin, address in [('BNB', bscaddr), ('BNB2', bscaddr2)]})
if "MULTI" in licensecheck["plans"]:
features.update({executor.submit(fetch_balance, coin, address): (coin, address) for coin, address in [('LTC', ltcaddr), ('DOGE', dogeaddr), ('DASH', dashaddr), ('MATIC', maticaddr), ('SOL', solanaaddr), ('TRX', tronaddr), ('ZEC', zecaddr), ('LTC2', ltcaddr2), ('DOGE2', dogeaddr2), ('DASH2', dashaddr2), ('MATIC2', maticaddr2), ('SOL2', solanaaddr2), ('TRX2', tronaddr2), ('ZEC2', zecaddr2)]})
for future in features:
coin, address = features[future]
try:
result = future.result()
if result[0].upper() == 'BTC' or 'BTC2':
coin_gecko_url = ""
coinname = 'bitcoin'
elif result[0].upper() == 'ETH' or 'ETH2':
coin_gecko_url = ""
coinname = 'ethereum'
elif result[0].upper() == 'LTC' or 'LTC2':
coin_gecko_url = ""
coinname = 'litecoin'
elif result[0].upper() == 'DOGE' or 'DOGE2':
coin_gecko_url = ""
coinname = 'dogecoin'
elif result[0].upper() == 'DASH' or 'DASH2':
coin_gecko_url = ""
coinname = 'dash'
elif result[0].upper() == 'BNB' or 'BNB2':
coin_gecko_url = ""
coinname = 'binancecoin'
elif result[0].upper() == 'MATIC' or 'MATIC2':
coin_gecko_url = ""
coinname = 'matic-network'
elif result[0].upper() == 'SOL' or 'SOL2':
coin_gecko_url = ""
coinname = 'solana'
elif result[0].upper() == 'TRX' or 'TRX2':
coin_gecko_url = ""
coinname = 'tron'
elif result[0].upper() == 'ZEC' or 'ZEC2':
coin_gecko_url = ""
coinname = 'zcash'
if float(result[1]) > 0:
coin_gecko_response = requests.get(coin_gecko_url, headers=coin_gecko_headers)
if coin_gecko_response.status_code == 200:
coin_gecko_data = coin_gecko_response.json()
exchange_rate = coin_gecko_data[coinname]["usd"]
usd_balance = format(float(result[1]) * exchange_rate, ',.2f')
foundx += 1
print(Fore.GREEN + f"{result[1]} {result[0]} | ${usd_balance}")
open('found.txt', 'a').write(f"{result[1]} {result[0]} | ${usd_balance} | {mnemonic} | {mnemonic2}\n")
total_balance += result[1] * exchange_rate
title = f"t.me/crptweak | Checked: {commentar} | Found: {foundx} | ${float(total_balance)} | C: {refreshcount}"
title = title.replace("|", "^|")
os.system(f"title {title}")
else:
foundx += 1
print(Fore.GREEN + f"{result[1]} {result[0]} | Failed To Fetch Data :(")
open('found.txt', 'a').write(f"{result[1]} {result[0]} | Failed To Fetch Data :( | {mnemonic} | {mnemonic2}\n")
title = f"t.me/crptweak | Checked: {commentar} | Found: {foundx} | ${float(total_balance)} | C: {refreshcount}"
title = title.replace("|", "^|")
os.system(f"title {title}")
else:
commentar += 1
title = f"t.me/crptweak | Checked: {commentar} | Found: {foundx} | ${float(total_balance)} | C: {refreshcount}"
title = title.replace("|", "^|")
os.system(f"title {title}")
except Exception as e:
print(f"Error fetching balance for {coin} address {address}: {e}")
elif soru == '2':
os._exit(0)
else:
os._exit(0)
我希望让这段代码运行得更快,我想了解我可以使用哪些方法来使这个程序运行得更快、更高效:)
因此,一般的经验法则是确保仅在需要时运行必要的代码,并测试您的逻辑以确保仅在正确的时间运行正确的代码(这样您就不会做不必要的事情)减慢程序速度的逻辑)
def get_public_key_address(seed_bytes_used, coin_type): # made into own function just for simplicity if there are future changes it works for all coins
return Bip44.FromSeed(seed_bytes_used, coin_type).DeriveDefaultPath().PublicKey().ToAddress()
if soru == '1':
os.system('cls')
refreshcount = 0
coin_names: Dict[str, str] = { # a key reference table for coin name conversion # used in also getting the url
'BTC': 'bitcoin',
'BTC2': 'bitcoin',
'ETH': 'ethereum',
'ETH2': 'ethereum',
'LTC': 'litecoin',
'LTC2': 'litecoin',
'DOGE': 'dogecoin',
'DOGE2': 'dogecoin',
'DASH': 'dash',
'DASH2': 'dash',
'BNB': 'binancecoin',
'BNB2': 'binancecoin',
'MATIC': 'matic-network',
'MATIC2': 'matic-network',
'SOL': 'solana',
'SOL2': 'solana',
'TRX': 'tron',
'TRX2': 'tron',
'ZEC': 'zcash',
'ZEC2': 'zcash',
}
coin_gecko_urls: Dict[str, str] = { # TODO insert urls
'bitcoin': '',
'ethereum': '',
'litecoin': '',
'dogecoin': '',
'dash': '',
'binancecoin': '',
'matic-network': '',
'solana': '',
'tron': '',
'zcash': '',
}
while True:
refreshcount += 1
if refreshcount % 100 == 0:
os.system('cls')
print(Fore.GREEN + 'Refreshing The App In 10 Seconds To Prevent Freezing.' + Fore.RESET)
time.sleep(10)
refreshcount = 0
# Generate from mnemonic
mnemonic = Bip39MnemonicGenerator(Bip39Languages.ENGLISH).FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)
mnemonic2 = Bip39MnemonicGenerator(Bip39Languages.ENGLISH).FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
seed_bytes2 = Bip39SeedGenerator(mnemonic2).Generate()
print(Fore.RED + f"PHRASE: {mnemonic}" + Fore.RESET)
print(Fore.RED + f"PHRASE: {mnemonic2}" + Fore.RESET)
# Use a ThreadPoolExecutor with 10 worker threads to fetch the balances concurrently
with ThreadPoolExecutor(max_workers=20) as executor:
features = {}
coins_to_search - []
if "BTC" in licensecheck["plans"]: # added own coins into this scoped area -- so you aren't trying to generate additional info when its not required
btcaddr = get_public_key_address(seed_bytes, Bip44Coins.BITCOIN)
btcaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.BITCOIN)
coins_to_search.extend([('BTC', btcaddr), ('BTC2', btcaddr2)])
if "ETH" in licensecheck["plans"]:
ethaddr = get_public_key_address(seed_bytes, Bip44Coins.ETHEREUM)
ethaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.ETHEREUM)
coins_to_search.extend([('ETH', ethaddr), ('ETH2', ethaddr2)])
if "BNB" in licensecheck["plans"]:
bscaddr = get_public_key_address(seed_bytes, Bip44Coins.BINANCE_SMART_CHAIN)
bscaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.BINANCE_SMART_CHAIN)
coins_to_search.extend([('BNB', bscaddr), ('BNB2', bscaddr2)])
if "MULTI" in licensecheck["plans"]:
ltcaddr = get_public_key_address(seed_bytes, Bip44Coins.LITECOIN)
ltcaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.LITECOIN)
dogeaddr = get_public_key_address(seed_bytes, Bip44Coins.DOGECOIN)
dogeaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.DOGECOIN)
dashaddr = get_public_key_address(seed_bytes, Bip44Coins.DASH)
dashaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.DASH)
maticaddr = get_public_key_address(seed_bytes, Bip44Coins.POLYGON)
maticaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.POLYGON)
solanaaddr = get_public_key_address(seed_bytes, Bip44Coins.SOLANA)
solanaaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.SOLANA)
rippleaddr = get_public_key_address(seed_bytes, Bip44Coins.RIPPLE)
rippleaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.RIPPLE)
tronaddr = get_public_key_address(seed_bytes, Bip44Coins.TRON)
tronaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.TRON)
zecaddr = get_public_key_address(seed_bytes, Bip44Coins.ZCASH)
zecaddr2 = get_public_key_address(seed_bytes2, Bip44Coins.ZCASH)
coins_to_search.extend([('LTC', ltcaddr), ('DOGE', dogeaddr), ('DASH', dashaddr), ('MATIC', maticaddr), ('SOL', solanaaddr), ('TRX', tronaddr), ('ZEC', zecaddr), ('LTC2', ltcaddr2), ('DOGE2', dogeaddr2), ('DASH2', dashaddr2), ('MATIC2', maticaddr2), ('SOL2', solanaaddr2), ('TRX2', tronaddr2), ('ZEC2', zecaddr2)])
features.update({executor.submit(fetch_balance, coin, address): (coin, address) for coin, address in coins_to_search}) # moved here to make it all one process
for future in features:
coin, address = features[future]
try:
result = future.result()
if float(result[1]) <= 0: # guard clause before doing anything to check that it is valid
commentar += 1
title = f"title t.me/crptweak ^| Checked: {commentar} ^| Found: {foundx} ^| ${float(total_balance)} ^| C: {refreshcount}" # removed title.replace because if just changing a str it should just be in the str normally
os.system(title)
continue # through the loop
result_name = future.result()[0].upper() # made a single result that you are trying to compare to instead of trying to process the result for each comparison
coinname = coin_names[result_name]
coin_gecko_url = coin_gecko_urls[coinname] # to simplify the look ups # previously your or statement was always defaulting to true because a str is always a str
coin_gecko_response = requests.get(coin_gecko_url, headers=coin_gecko_headers)
if coin_gecko_response.status_code != 200: # guard clause to check that its a valid response
foundx += 1
print(Fore.GREEN + f"{result[1]} {result[0]} | Failed To Fetch Data :(")
with open('found.txt', 'a') as file: # adding context manager for simplicity that file is properly closed after using
file.write(f"{result[1]} {result[0]} | Failed To Fetch Data :( | {mnemonic} | {mnemonic2}\n")
title = f"title t.me/crptweak ^| Checked: {commentar} ^| Found: {foundx} ^| ${float(total_balance)} ^| C: {refreshcount}" # removed title.replace because if just changing a str it should just be in the str normally
os.system(title)
continue # through the loop
exchange_rate = coin_gecko_response.json()[coinname]["usd"]
usd_balance = format(float(result[1]) * exchange_rate, ',.2f')
foundx += 1
print(Fore.GREEN + f"{result[1]} {result[0]} | ${usd_balance}")
with open('found.txt', 'a') as file: # adding context manager for simplicity that file is properly closed after using
file.write(f"{result[1]} {result[0]} | ${usd_balance} | {mnemonic} | {mnemonic2}\n")
total_balance += result[1] * exchange_rate # should this be adding the usd_balance?
title = f"title t.me/crptweak ^| Checked: {commentar} ^| Found: {foundx} ^| ${float(total_balance)} ^| C: {refreshcount}"
os.system(title)
except Exception as e: # where will this error most likely occur -- it is better to have a singular scoped exception (so that only one things fails and it is easier to debug)
print(f"Error fetching balance for {coin} address {address}: {e}")
至于真正进一步优化程序——您应该分析您的代码,以便更好地了解代码在哪里减慢了进程。