Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import json
- import time
- import threading
- import hashlib
- import struct
- from requests.auth import HTTPBasicAuth
- import requests
- # Configuration du nœud Bitcoin2
- RPC_USER = "RPC user"
- RPC_PASSWORD = "RPC pass"
- RPC_HOST = "127.0.0.1"
- RPC_PORT = 8332 # Port RPC de Bitcoin2
- RPC_URL = f"http://{RPC_HOST}:{RPC_PORT}"
- # Configuration du serveur Stratum
- STRATUM_HOST = "0.0.0.0" # Écoute sur toutes les interfaces
- STRATUM_PORT = 3333 # Port standard pour Stratum
- DIFFICULTY = 1000 # Difficulté initiale pour le Bitaxe (sera ajustée automatiquement)
- # Configuration Vardiff (difficulté variable)
- TARGET_SHARE_TIME = 15 # Cible: 1 share toutes les 15 secondes
- VARDIFF_MIN = 100 # Difficulté minimum
- VARDIFF_MAX = 100000 # Difficulté maximum
- VARDIFF_RETARGET_TIME = 90 # Recalculer la difficulté toutes les 90 secondes
- VARDIFF_VARIANCE = 0.3 # Variance acceptée (30%)
- class Bitcoin2RPC:
- """Classe pour communiquer avec le nœud Bitcoin2"""
- def __init__(self, user, password, url):
- self.auth = HTTPBasicAuth(user, password)
- self.url = url
- self.id_counter = 0
- def call(self, method, params=None):
- """Effectue un appel RPC"""
- if params is None:
- params = []
- self.id_counter += 1
- payload = {
- "jsonrpc": "2.0",
- "id": self.id_counter,
- "method": method,
- "params": params
- }
- try:
- response = requests.post(
- self.url,
- data=json.dumps(payload),
- headers={"content-type": "application/json"},
- auth=self.auth,
- timeout=30
- )
- if response.status_code == 200:
- result = response.json()
- if "error" in result and result["error"]:
- print(f"❌ Erreur RPC {method}: {result['error']}")
- return None
- return result.get("result")
- else:
- print(f"❌ Erreur HTTP {response.status_code}")
- return None
- except Exception as e:
- print(f"❌ Erreur connexion RPC: {e}")
- return None
- def get_block_template(self):
- """Récupère le template de bloc pour mining"""
- # Essayer d'abord avec les règles segwit
- template = self.call("getblocktemplate", [{"rules": ["segwit"]}])
- if template is None:
- # Fallback sans règles
- template = self.call("getblocktemplate", [{}])
- if template is None:
- # Dernier fallback sans paramètres
- template = self.call("getblocktemplate")
- return template
- def submit_block(self, block_hex):
- """Soumet un bloc miné"""
- return self.call("submitblock", [block_hex])
- def get_info(self):
- """Récupère les infos du nœud"""
- # Essayer différentes méthodes selon la version
- info = self.call("getblockchaininfo")
- if info is None:
- info = self.call("getinfo")
- if info is None:
- # Fallback: essayer getnetworkinfo
- network_info = self.call("getnetworkinfo")
- blockchain_info = self.call("getblockchaininfo")
- if network_info and blockchain_info:
- info = {**network_info, **blockchain_info}
- return info
- def get_mining_info(self):
- """Récupère les infos de mining"""
- return self.call("getmininginfo")
- def get_block_count(self):
- """Récupère le nombre de blocs"""
- return self.call("getblockcount")
- def get_network_info(self):
- """Récupère les infos réseau"""
- return self.call("getnetworkinfo")
- class StratumServer:
- """Serveur Stratum pour Bitaxe Gamma"""
- def __init__(self, host, port, rpc):
- self.host = host
- self.port = port
- self.rpc = rpc
- self.clients = {}
- self.job_id = 0
- self.current_template = None
- self.running = False
- self.server_socket = None
- def start(self):
- """Démarre le serveur Stratum"""
- self.running = True
- self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- try:
- self.server_socket.bind((self.host, self.port))
- self.server_socket.listen(5)
- print(f"✅ Serveur Stratum démarré sur {self.host}:{self.port}")
- print(f"📡 Configurez votre Bitaxe Gamma avec:")
- print(f" URL: stratum+tcp://{self._get_local_ip()}:{self.port}")
- print(f" User: bc2miner")
- print(f" Password: x\n")
- # Thread pour mettre à jour les jobs
- update_thread = threading.Thread(target=self._update_jobs, daemon=True)
- update_thread.start()
- # Accepter les connexions
- while self.running:
- try:
- print("⏳ En attente de connexion...")
- client_socket, address = self.server_socket.accept()
- print(f"🔌 Nouvelle connexion détectée: {address}")
- client_socket.settimeout(30) # Timeout de 30 secondes
- client_thread = threading.Thread(
- target=self._handle_client,
- args=(client_socket, address),
- daemon=True
- )
- client_thread.start()
- print(f"✅ Thread démarré pour {address}")
- except Exception as e:
- if self.running:
- print(f"❌ Erreur acceptation connexion: {e}")
- import traceback
- traceback.print_exc()
- except Exception as e:
- print(f"❌ Erreur serveur: {e}")
- finally:
- if self.server_socket:
- self.server_socket.close()
- def _get_local_ip(self):
- """Récupère l'IP locale"""
- try:
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s.connect(("8.8.8.8", 80))
- ip = s.getsockname()[0]
- s.close()
- return ip
- except:
- return "127.0.0.1"
- def _handle_client(self, client_socket, address):
- """Gère une connexion client (Bitaxe)"""
- client_id = f"{address[0]}:{address[1]}"
- print(f"🎯 Handler démarré pour {client_id}")
- self.clients[client_id] = {
- "socket": client_socket,
- "address": address,
- "subscribed": False,
- "authorized": False,
- "worker": None,
- "difficulty": DIFFICULTY,
- "shares": 0,
- "last_share": None,
- "share_times": [], # Pour vardiff
- "last_retarget": time.time() # Dernier ajustement de difficulté
- }
- buffer = ""
- try:
- print(f"👂 En écoute sur {client_id}...")
- while self.running:
- try:
- data = client_socket.recv(4096)
- if not data:
- print(f"📭 Connexion fermée par {client_id}")
- break
- print(f"📦 Données reçues de {client_id}: {len(data)} bytes")
- buffer += data.decode('utf-8')
- # Traiter les messages complets (séparés par \n)
- while '\n' in buffer:
- line, buffer = buffer.split('\n', 1)
- line = line.strip()
- if line:
- try:
- request = json.loads(line)
- print(f"📩 Reçu de {client_id}: {request.get('method', 'unknown')}")
- response = self._process_request(client_id, request)
- if response:
- response_str = json.dumps(response) + '\n'
- client_socket.sendall(response_str.encode('utf-8'))
- print(f"📤 Envoyé à {client_id}: {response.get('result', response.get('method', 'response'))}")
- except json.JSONDecodeError as e:
- print(f"⚠️ Message JSON invalide de {client_id}: {line[:100]}")
- except Exception as e:
- print(f"⚠️ Erreur traitement message de {client_id}: {e}")
- import traceback
- traceback.print_exc()
- except socket.timeout:
- print(f"⏱️ Timeout sur {client_id}")
- continue
- except Exception as e:
- print(f"❌ Erreur recv de {client_id}: {e}")
- import traceback
- traceback.print_exc()
- break
- except Exception as e:
- print(f"❌ Erreur client {client_id}: {e}")
- import traceback
- traceback.print_exc()
- finally:
- print(f"🔌 Déconnexion: {client_id}")
- if client_id in self.clients:
- del self.clients[client_id]
- try:
- client_socket.close()
- except:
- pass
- def _process_request(self, client_id, request):
- """Traite une requête Stratum"""
- method = request.get("method")
- params = request.get("params", [])
- req_id = request.get("id")
- if method == "mining.configure":
- # Le Bitaxe demande la configuration (version_rolling, etc.)
- return {
- "id": req_id,
- "result": {
- "version-rolling": True,
- "version-rolling.mask": "1fffe000"
- },
- "error": None
- }
- elif method == "mining.subscribe":
- self.clients[client_id]["subscribed"] = True
- return {
- "id": req_id,
- "result": [
- [["mining.notify", "subscription_id"]],
- "extranonce1",
- 4 # extranonce2_size
- ],
- "error": None
- }
- elif method == "mining.authorize":
- worker = params[0] if params else "unknown"
- self.clients[client_id]["authorized"] = True
- self.clients[client_id]["worker"] = worker
- print(f"✅ Worker autorisé: {worker} ({client_id})")
- # Envoyer la difficulté
- self._send_difficulty(client_id)
- # Envoyer le premier job
- if self.current_template:
- self._send_job(client_id)
- return {
- "id": req_id,
- "result": True,
- "error": None
- }
- elif method == "mining.submit":
- return self._handle_share(client_id, params, req_id)
- elif method == "mining.suggest_difficulty":
- # Le mineur suggère une difficulté
- suggested_diff = params[0] if params else 1000
- print(f"💡 Difficulté suggérée par {client_id}: {suggested_diff}")
- self.clients[client_id]["difficulty"] = suggested_diff
- self._send_difficulty(client_id)
- return {
- "id": req_id,
- "result": True,
- "error": None
- }
- elif method == "mining.extranonce.subscribe":
- return {
- "id": req_id,
- "result": True,
- "error": None
- }
- return None
- def _send_difficulty(self, client_id):
- """Envoie la difficulté au client"""
- if client_id not in self.clients:
- return
- difficulty = self.clients[client_id]["difficulty"]
- message = {
- "id": None,
- "method": "mining.set_difficulty",
- "params": [difficulty]
- }
- try:
- self.clients[client_id]["socket"].sendall(
- (json.dumps(message) + '\n').encode('utf-8')
- )
- except:
- pass
- def _send_job(self, client_id=None):
- """Envoie un nouveau job de mining"""
- if not self.current_template:
- print("⚠️ Pas de template disponible pour envoyer un job")
- return
- self.job_id += 1
- job_params = self._create_job()
- if not job_params:
- print("⚠️ Échec de création du job")
- return
- message = {
- "id": None,
- "method": "mining.notify",
- "params": job_params
- }
- clients_to_notify = [client_id] if client_id else list(self.clients.keys())
- for cid in clients_to_notify:
- if cid in self.clients and self.clients[cid]["authorized"]:
- try:
- message_str = json.dumps(message) + '\n'
- self.clients[cid]["socket"].sendall(message_str.encode('utf-8'))
- print(f"📤 Job {self.job_id} envoyé à {cid}")
- print(f" 📦 Taille: {len(message_str)} bytes")
- except Exception as e:
- print(f"❌ Erreur envoi job à {cid}: {e}")
- def _create_job(self):
- """Crée un job Stratum depuis le template"""
- if not self.current_template:
- return None
- template = self.current_template
- # Extraire les données du template
- prevhash = template.get('previousblockhash', '0' * 64)
- # IMPORTANT: Stratum utilise little-endian pour prevhash
- prevhash_le = ''.join([prevhash[i:i+2] for i in range(0, len(prevhash), 2)][::-1])
- height = template.get('height', 0)
- version = template.get('version', 1)
- nbits = template.get('bits', '1d00ffff')
- ntime = template.get('curtime', int(time.time()))
- # Calculer la difficulté depuis bits
- difficulty = template.get('difficulty', 0)
- if difficulty == 0:
- bits_int = int(nbits, 16)
- exp = bits_int >> 24
- mant = bits_int & 0xffffff
- target = mant * (2 ** (8 * (exp - 3)))
- difficulty = (0xffff * 2**208) / target if target > 0 else 0
- # Construction de la coinbase avec la hauteur encodée correctement
- # La hauteur doit être encodée selon BIP34
- if height <= 16:
- height_script = f"{0x50 + height:02x}"
- elif height < 0x80:
- height_script = f"01{height:02x}"
- elif height < 0x8000:
- height_bytes = height.to_bytes(2, 'little')
- height_script = f"02{height_bytes.hex()}"
- else:
- height_bytes = height.to_bytes(4, 'little')
- # Trouver la longueur nécessaire
- length = 4
- while length > 1 and height_bytes[length-1] == 0:
- length -= 1
- height_script = f"{length:02x}" + height_bytes[:length].hex()
- # Message personnalisé pour identifier votre pool
- custom_message = "Mined with BitAxe on BC2"
- custom_hex = custom_message.encode('ascii').hex()
- # Coinbase script complet: height + message + espace pour extranonce
- coinbase_script_prefix = height_script + f"{len(custom_message):02x}" + custom_hex
- extranonce_size = 8 # 8 bytes d'extranonce (4 + 4)
- # Taille totale du script
- total_script_size = len(coinbase_script_prefix)//2 + extranonce_size
- # Coinbase transaction
- coinb1 = (
- "02000000" + # version 2
- "01" + # 1 input
- "0000000000000000000000000000000000000000000000000000000000000000" + # prev hash (null)
- "ffffffff" + # prev index
- f"{total_script_size:02x}" + # script size total
- coinbase_script_prefix # height + message
- # extranonce sera ajouté ici par le mineur
- )
- # Output de la coinbase
- coinbase_value = template.get('coinbasevalue', 5000000000)
- value_bytes = struct.pack('<Q', coinbase_value).hex()
- # Utiliser une vraie adresse si disponible dans coinbaseaux
- coinbase_aux = template.get('coinbaseaux', {})
- coinb2 = (
- "ffffffff" + # sequence
- "01" + # 1 output
- value_bytes + # amount
- "19" + # script length (25 bytes)
- "76a914" + # OP_DUP OP_HASH160
- "0000000000000000000000000000000000000000" + # pubkey hash
- "88ac" + # OP_EQUALVERIFY OP_CHECKSIG
- "00000000" # locktime
- )
- # Merkle branches - DOIVENT être en little-endian
- merkle_branch = []
- transactions = template.get('transactions', [])
- if transactions:
- for tx in transactions[:20]:
- txid = tx.get('txid', tx.get('hash', ''))
- if txid:
- # Convertir en little-endian
- txid_le = ''.join([txid[i:i+2] for i in range(0, len(txid), 2)][::-1])
- merkle_branch.append(txid_le)
- # Formats Stratum standard
- version_hex = f"{version:08x}" # Big endian hex string
- ntime_hex = f"{ntime:08x}" # Big endian hex string
- print(f"📋 Job {self.job_id}:")
- print(f" Height: {height}")
- print(f" Difficulty: {difficulty:.2f}")
- print(f" Transactions: {len(merkle_branch)}")
- print(f" Version: {version_hex}")
- print(f" Bits: {nbits}")
- print(f" Time: {ntime_hex}")
- print(f" Prevhash (LE): {prevhash_le[:20]}...")
- print(f" Coinbase script: {coinbase_script_prefix}")
- print(f" Coinb1 length: {len(coinb1)//2} bytes")
- print(f" Coinb2 length: {len(coinb2)//2} bytes")
- return [
- str(self.job_id), # job_id
- prevhash_le, # prevhash en LITTLE ENDIAN
- coinb1, # coinb1
- coinb2, # coinb2
- merkle_branch, # merkle_branch en LITTLE ENDIAN
- version_hex, # version
- nbits, # nbits
- ntime_hex, # ntime
- True # clean_jobs
- ]
- def _handle_share(self, client_id, params, req_id):
- """Traite une share soumise"""
- if client_id not in self.clients:
- return {"id": req_id, "result": False, "error": [21, "Unknown worker", None]}
- current_time = time.time()
- client = self.clients[client_id]
- # Enregistrer la share
- client["shares"] += 1
- client["last_share"] = current_time
- client["share_times"].append(current_time)
- # Garder seulement les 20 dernières shares pour le calcul
- if len(client["share_times"]) > 20:
- client["share_times"] = client["share_times"][-20:]
- worker = client["worker"]
- shares = client["shares"]
- # Calculer le temps moyen entre shares
- avg_share_time = None
- if len(client["share_times"]) >= 2:
- time_diffs = []
- for i in range(1, len(client["share_times"])):
- time_diffs.append(client["share_times"][i] - client["share_times"][i-1])
- avg_share_time = sum(time_diffs) / len(time_diffs)
- print(f"✨ Share #{shares} de {worker} (Diff: {client['difficulty']})", end="")
- if avg_share_time:
- print(f" - Temps moyen: {avg_share_time:.1f}s")
- else:
- print()
- # Ajuster la difficulté si nécessaire
- time_since_retarget = current_time - client["last_retarget"]
- if time_since_retarget >= VARDIFF_RETARGET_TIME and avg_share_time:
- self._adjust_difficulty(client_id, avg_share_time)
- return {
- "id": req_id,
- "result": True,
- "error": None
- }
- def _adjust_difficulty(self, client_id, avg_share_time):
- """Ajuste la difficulté pour ce client (vardiff)"""
- if client_id not in self.clients:
- return
- client = self.clients[client_id]
- current_diff = client["difficulty"]
- # Calculer la nouvelle difficulté basée sur le temps moyen
- # Formule: new_diff = current_diff * (avg_time / target_time)
- ratio = avg_share_time / TARGET_SHARE_TIME
- # Appliquer seulement si la variance est significative
- if abs(1 - ratio) < VARDIFF_VARIANCE:
- return # Pas besoin d'ajuster
- new_diff = current_diff * ratio
- # Limiter entre min et max
- new_diff = max(VARDIFF_MIN, min(VARDIFF_MAX, new_diff))
- # Arrondir à un nombre propre
- new_diff = round(new_diff / 100) * 100
- if new_diff != current_diff:
- print(f"🎯 Ajustement difficulté pour {client['worker']}:")
- print(f" {current_diff} → {new_diff} (temps moyen: {avg_share_time:.1f}s, cible: {TARGET_SHARE_TIME}s)")
- client["difficulty"] = new_diff
- client["last_retarget"] = time.time()
- # Envoyer la nouvelle difficulté
- self._send_difficulty(client_id)
- def _update_jobs(self):
- """Met à jour les jobs périodiquement"""
- while self.running:
- try:
- template = self.rpc.get_block_template()
- if template and template != self.current_template:
- self.current_template = template
- height = template.get('height', '?')
- difficulty = template.get('difficulty', 0)
- print(f"🔄 Nouveau template de bloc (hauteur: {height})")
- print(f" 📊 Template keys: {list(template.keys())}")
- print(f" 🎯 Previous hash: {template.get('previousblockhash', 'N/A')[:20]}...")
- print(f" 💎 Difficulty: {difficulty}")
- print(f" 🔢 Bits: {template.get('bits', 'N/A')}")
- print(f" ⏰ Time: {template.get('curtime', 'N/A')}")
- self._send_job() # Broadcast à tous les clients
- except Exception as e:
- print(f"⚠️ Erreur mise à jour template: {e}")
- import traceback
- traceback.print_exc()
- time.sleep(10) # Vérifier toutes les 10 secondes
- def stop(self):
- """Arrête le serveur"""
- print("\n🛑 Arrêt du serveur...")
- self.running = False
- if self.server_socket:
- self.server_socket.close()
- for client_id in list(self.clients.keys()):
- try:
- self.clients[client_id]["socket"].close()
- except:
- pass
- self.clients.clear()
- def main():
- print("=" * 60)
- print(" Serveur Stratum Bitcoin2 pour Bitaxe Gamma")
- print("=" * 60)
- print()
- # Créer la connexion RPC
- rpc = Bitcoin2RPC(RPC_USER, RPC_PASSWORD, RPC_URL)
- # Tester la connexion
- print("🔍 Test de connexion au nœud Bitcoin2...")
- # Tester différentes méthodes RPC
- info = None
- block_count = rpc.get_block_count()
- if block_count is not None:
- print("✅ Connexion au nœud réussie!")
- print(f" Blocs: {block_count}")
- # Essayer d'obtenir plus d'infos
- network_info = rpc.get_network_info()
- if network_info:
- print(f" Version: {network_info.get('version', 'N/A')}")
- print(f" Connexions: {network_info.get('connections', 'N/A')}")
- mining_info = rpc.get_mining_info()
- if mining_info:
- print(f" Difficulté: {mining_info.get('difficulty', 'N/A')}")
- print(f" Network hashrate: {mining_info.get('networkhashps', 'N/A')} H/s")
- else:
- print("\n❌ Impossible de se connecter au nœud Bitcoin2!")
- print("\n📝 Vérifiez que:")
- print(" 1. Bitcoin2-qt (bitcoinII-qt) est en cours d'exécution")
- print(" 2. Le fichier bitcoinII.conf contient:")
- print(" server=1")
- print(f" rpcuser={RPC_USER}")
- print(f" rpcpassword={RPC_PASSWORD}")
- print(" rpcallowip=127.0.0.1")
- print(f" rpcport={RPC_PORT}")
- print("\n 3. Le fichier bitcoinII.conf est dans le bon dossier:")
- print(" Windows: %APPDATA%\\BitcoinII\\")
- print(" Linux: ~/.bitcoinII/")
- print("\n⚠️ Redémarrez bitcoinII-qt après avoir modifié bitcoinII.conf")
- return
- print()
- # Démarrer le serveur Stratum
- server = StratumServer(STRATUM_HOST, STRATUM_PORT, rpc)
- try:
- server.start()
- except KeyboardInterrupt:
- print("\n\n⌨️ Interruption clavier détectée")
- finally:
- server.stop()
- print("✅ Serveur arrêté proprement")
- if __name__ == "__main__":
- main()
Advertisement