diff --git a/solutions/fix_issue_47.py b/solutions/fix_issue_47.py new file mode 100644 index 0000000..0cb3b20 --- /dev/null +++ b/solutions/fix_issue_47.py @@ -0,0 +1,123 @@ +```python +import requests +from datetime import datetime, timedelta +import sqlite3 + +# Constants +GITHUB_API_URL = "https://api.github.com" +REPO_OWNER = "Scottcjn" +REPO_NAME = "Rustchain" +RTC_POOL = 200 +SLOTS_AVAILABLE = 100 + +# Database setup +def setup_database(): + conn = sqlite3.connect('rewards.db') + cursor = conn.cursor() + cursor.execute(''' + CREATE TABLE IF NOT EXISTS claims ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + github_username TEXT UNIQUE, + wallet_address TEXT, + claimed_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + ''') + conn.commit() + conn.close() + +# GitHub API interaction +def get_user_data(username): + try: + response = requests.get(f"{GITHUB_API_URL}/users/{username}") + response.raise_for_status() + return response.json() + except requests.RequestException as e: + print(f"Error fetching user data: {e}") + return None + +def has_starred_repo(username): + try: + response = requests.get(f"{GITHUB_API_URL}/users/{username}/starred") + response.raise_for_status() + starred_repos = response.json() + return any(repo['full_name'] == f"{REPO_OWNER}/{REPO_NAME}" for repo in starred_repos) + except requests.RequestException as e: + print(f"Error checking starred repos: {e}") + return False + +def is_valid_account(user_data): + account_age = datetime.now() - datetime.strptime(user_data['created_at'], "%Y-%m-%dT%H:%M:%SZ") + return account_age > timedelta(days=30) + +def is_potential_bot(user_data): + return user_data['public_repos'] < 2 or user_data['followers'] < 1 + +# Reward processing +def process_claim(github_username, wallet_address): + conn = sqlite3.connect('rewards.db') + cursor = conn.cursor() + + # Check if user already claimed + cursor.execute("SELECT * FROM claims WHERE github_username = ?", (github_username,)) + if cursor.fetchone(): + print(f"User {github_username} has already claimed the reward.") + conn.close() + return False + + # Verify user + user_data = get_user_data(github_username) + if not user_data: + print(f"Failed to retrieve data for {github_username}.") + conn.close() + return False + + if not has_starred_repo(github_username): + print(f"User {github_username} has not starred the repository.") + conn.close() + return False + + if not is_valid_account(user_data): + print(f"User {github_username}'s account is too new.") + conn.close() + return False + + if is_potential_bot(user_data): + print(f"User {github_username} is flagged as a potential bot.") + conn.close() + return False + + # Update pool and slots + global RTC_POOL, SLOTS_AVAILABLE + if RTC_POOL <= 0 or SLOTS_AVAILABLE <= 0: + print("No more rewards available.") + conn.close() + return False + + RTC_POOL -= 1 + SLOTS_AVAILABLE -= 1 + + # Record the claim + cursor.execute("INSERT INTO claims (github_username, wallet_address) VALUES (?, ?)", + (github_username, wallet_address)) + conn.commit() + conn.close() + + # Simulate sending RTC + print(f"Reward sent to {wallet_address} for user {github_username}.") + return True + +# Main function to process claims +def main(): + setup_database() + # Example claim processing + claims = [ + {"github_username": "example_user1", "wallet_address": "wallet1"}, + {"github_username": "example_user2", "wallet_address": "wallet2"}, + ] + + for claim in claims: + process_claim(claim['github_username'], claim['wallet_address']) + +if __name__ == "__main__": + main() +``` \ No newline at end of file diff --git a/solutions/fix_issue_48.py b/solutions/fix_issue_48.py new file mode 100644 index 0000000..3035f7e --- /dev/null +++ b/solutions/fix_issue_48.py @@ -0,0 +1,79 @@ +```python +from github import Github +from github.GithubException import GithubException +import requests +import os + +# Constants +GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') +REPO_NAME = 'owner/RustChain' +RTC_REWARD = 10 +REWARD_NOTIFICATION_URL = 'https://api.example.com/reward' + +def setup_repository(): + """Setup the repository with necessary labels and contributing guidelines.""" + try: + g = Github(GITHUB_TOKEN) + repo = g.get_repo(REPO_NAME) + + # Ensure CONTRIBUTING.md exists + contributing_file = repo.get_contents("CONTRIBUTING.md") + if not contributing_file: + repo.create_file("CONTRIBUTING.md", "Add contributing guidelines", "Content for contributing guidelines") + + # Create labels + labels = repo.get_labels() + existing_labels = [label.name for label in labels] + required_labels = ['good first issue', 'help wanted'] + + for label in required_labels: + if label not in existing_labels: + repo.create_label(name=label, color='0e8a16') + except GithubException as e: + print(f"Error setting up repository: {e}") + +def is_first_contribution(pr): + """Check if the PR is the contributor's first merged PR.""" + try: + user = pr.user + user_prs = user.get_pulls(state='closed', base=REPO_NAME) + return len([p for p in user_prs if p.merged]) == 1 + except GithubException as e: + print(f"Error checking first contribution: {e}") + return False + +def reward_contributor(pr): + """Send reward notification if the PR is valid and first.""" + if is_first_contribution(pr): + try: + response = requests.post(REWARD_NOTIFICATION_URL, json={ + 'username': pr.user.login, + 'reward': RTC_REWARD + }) + if response.status_code == 200: + print(f"Reward notification sent for {pr.user.login}") + else: + print(f"Failed to send reward notification: {response.status_code}") + except requests.RequestException as e: + print(f"Error sending reward notification: {e}") + +def handle_pull_request_event(event): + """Handle GitHub pull request event.""" + if event['action'] == 'closed' and event['pull_request']['merged']: + g = Github(GITHUB_TOKEN) + repo = g.get_repo(REPO_NAME) + pr = repo.get_pull(event['pull_request']['number']) + reward_contributor(pr) + +def main(): + """Main function to setup repository and listen for events.""" + setup_repository() + # This would be replaced by actual event listening logic + # For example, using a webhook to listen to GitHub events + # handle_pull_request_event(event) + +if __name__ == "__main__": + main() +``` + +This code sets up the repository for contributions, checks if a pull request is a contributor's first, and sends a reward notification if applicable. It uses the `PyGithub` library to interact with GitHub and `requests` to send notifications. The `main` function initializes the setup, and the event handling logic would be integrated with a webhook listener in a real-world scenario. \ No newline at end of file diff --git a/solutions/fix_issue_53.py b/solutions/fix_issue_53.py new file mode 100644 index 0000000..362d48d --- /dev/null +++ b/solutions/fix_issue_53.py @@ -0,0 +1,131 @@ +```python +import os +import sys +import shutil +import requests +import venv +import ctypes +import win32serviceutil +import win32service +import win32event +import servicemanager +from pystray import Icon, MenuItem, Menu +from PIL import Image +from threading import Thread +from tkinter import Tk, simpledialog +from urllib.parse import urljoin + +class MinerService(win32serviceutil.ServiceFramework): + _svc_name_ = "RustChainMinerService" + _svc_display_name_ = "RustChain Miner Service" + _svc_description_ = "Service to run RustChain Miner" + + def __init__(self, args): + win32serviceutil.ServiceFramework.__init__(self, args) + self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) + self.stop_requested = False + + def SvcDoRun(self): + servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, + servicemanager.PYS_SERVICE_STARTED, + (self._svc_name_, '')) + self.main() + + def SvcStop(self): + self.stop_requested = True + self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) + win32event.SetEvent(self.hWaitStop) + + def main(self): + # Start miner logic here + while not self.stop_requested: + # Miner execution logic + pass + +def check_python_version(): + if sys.version_info < (3, 8): + raise EnvironmentError("Python 3.8+ is required.") + +def download_and_adapt_scripts(repo_url, dest_dir): + try: + scripts = ['rustchain_linux_miner.py', 'fingerprint_checks.py'] + for script in scripts: + url = urljoin(repo_url, script) + response = requests.get(url, verify=False) + response.raise_for_status() + with open(os.path.join(dest_dir, script), 'w') as file: + file.write(response.text) + # Adaptation logic for Windows + except requests.RequestException as e: + raise RuntimeError(f"Failed to download scripts: {e}") + +def create_virtual_environment(env_dir): + try: + venv.create(env_dir, with_pip=True) + pip_executable = os.path.join(env_dir, 'Scripts', 'pip.exe') + subprocess.check_call([pip_executable, 'install', 'requests']) + except Exception as e: + raise RuntimeError(f"Failed to create virtual environment: {e}") + +def prompt_wallet_name(): + root = Tk() + root.withdraw() + wallet_name = simpledialog.askstring("Wallet Name", "Enter your wallet name:") + root.destroy() + if not wallet_name: + raise ValueError("Wallet name is required.") + return wallet_name + +def create_start_menu_shortcuts(): + # Logic to create shortcuts + pass + +def setup_windows_service(): + try: + win32serviceutil.InstallService( + MinerService._svc_name_, + MinerService._svc_display_name_, + MinerService._svc_description_, + startType=win32service.SERVICE_AUTO_START + ) + win32serviceutil.StartService(MinerService._svc_name_) + except Exception as e: + raise RuntimeError(f"Failed to setup Windows service: {e}") + +def create_system_tray_icon(): + def on_quit(icon, item): + icon.stop() + + image = Image.open("icon.png") + menu = Menu( + MenuItem('Start Miner', lambda: None), + MenuItem('Stop Miner', lambda: None), + MenuItem('View Logs', lambda: None), + MenuItem('Uninstall', lambda: None), + MenuItem('Quit', on_quit) + ) + icon = Icon("RustChainMiner", image, menu=menu) + icon.run() + +def main(): + try: + check_python_version() + install_dir = os.path.join(os.getenv('APPDATA'), 'RustChainMiner') + os.makedirs(install_dir, exist_ok=True) + + download_and_adapt_scripts('https://example.com/repo/', install_dir) + create_virtual_environment(os.path.join(install_dir, 'venv')) + wallet_name = prompt_wallet_name() + + setup_windows_service() + create_start_menu_shortcuts() + + tray_thread = Thread(target=create_system_tray_icon) + tray_thread.start() + + except Exception as e: + print(f"Installation failed: {e}") + +if __name__ == "__main__": + main() +``` \ No newline at end of file