Alikhani0916 commited on
Commit
412c489
Β·
verified Β·
1 Parent(s): b2c2a43

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -0
app.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import socket
2
+ import json
3
+ import struct
4
+ import binascii
5
+ import hashlib
6
+ import time
7
+ import sys
8
+
9
+ HOST = 'sha256.unmineable.com'
10
+ PORT = 3333
11
+ USERNAME = 'TRX:THBhffMkmQzKPhmWdJznyGv6X4MjhoHWwq.sssj'
12
+ PASSWORD = 'x'
13
+
14
+ def create_tcp_connection(host, port):
15
+ try:
16
+ print(f"🌐 Connecting to {host}:{port} via TCP...")
17
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
18
+ sock.settimeout(30)
19
+ sock.connect((host, port))
20
+ print(f"βœ… Connected successfully to {host}:{port}!")
21
+ return sock
22
+ except Exception as e:
23
+ print(f"❌ ERROR: Connection failed - {e}")
24
+ sys.exit(1)
25
+
26
+ def receive_message(sock):
27
+ response = ""
28
+ try:
29
+ while True:
30
+ part = sock.recv(4096).decode('utf-8')
31
+ if not part:
32
+ print("❌ ERROR: Connection closed by server.")
33
+ sys.exit(1)
34
+ response += part
35
+ if "\n" in response:
36
+ break
37
+ except socket.timeout:
38
+ print("❌ ERROR: Socket timeout.")
39
+ sys.exit(1)
40
+ messages = response.strip().split("\n")
41
+ parsed_messages = []
42
+ for msg in messages:
43
+ try:
44
+ parsed_messages.append(json.loads(msg))
45
+ except json.JSONDecodeError:
46
+ print(f"❌ ERROR: Failed to parse JSON: {msg}")
47
+ return parsed_messages
48
+
49
+ def subscribe_sha256(sock):
50
+ print("πŸ”— Subscribing...")
51
+ subscribe_msg = {
52
+ "id": 1,
53
+ "method": "mining.subscribe",
54
+ "params": ["python-miner/1.0"]
55
+ }
56
+ sock.sendall((json.dumps(subscribe_msg) + '\n').encode())
57
+ responses = receive_message(sock)
58
+ for res in responses:
59
+ if "result" in res:
60
+ print("βœ… Subscribed!")
61
+ extranonce1 = res['result'][1]
62
+ extranonce2_size = res['result'][2]
63
+ return res, extranonce1, extranonce2_size
64
+ print("❌ Subscription failed.")
65
+ sys.exit(1)
66
+
67
+ def authorize_sha256(sock, username, password):
68
+ print("πŸ”‘ Authorizing...")
69
+ auth_msg = {
70
+ "id": 2,
71
+ "method": "mining.authorize",
72
+ "params": [username, password]
73
+ }
74
+ sock.sendall((json.dumps(auth_msg) + '\n').encode())
75
+ responses = receive_message(sock)
76
+ for res in responses:
77
+ if res.get("result") is True:
78
+ print("βœ… Authorized!")
79
+ return res
80
+ print("❌ Authorization failed.")
81
+ sys.exit(1)
82
+
83
+ def calculate_merkle_root(coinbase_hash, merkle_branch):
84
+ current_hash = coinbase_hash
85
+ for h in merkle_branch:
86
+ branch_hash = binascii.unhexlify(h)[::-1]
87
+ combined = current_hash.digest() + branch_hash # Use digest() to get bytes from hash object
88
+ current_hash = hashlib.sha256(hashlib.sha256(combined).digest()) # Reassign current_hash to hash object
89
+ return binascii.hexlify(current_hash.digest()[::-1]).decode() # Use digest() and reverse for final output
90
+
91
+ def mine_sha256(sock, username, extranonce1, extranonce2_size):
92
+ extranonce2_counter = 0
93
+ hashes_per_second = 0 # Initialize hashrate variable
94
+ hash_count = 0 # Counter for hashes in the current interval
95
+ last_report_time = time.time() # Time of last hashrate report
96
+ report_interval = 10 # Report hashrate every 10 seconds
97
+
98
+ try:
99
+ while True:
100
+ messages = receive_message(sock)
101
+ for data in messages:
102
+ if data.get("method") == "mining.notify":
103
+ params = data["params"]
104
+ job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _ = params
105
+ # Generate extranonce2
106
+ extranonce2 = f"{extranonce2_counter:0{extranonce2_size * 2}x}"
107
+ extranonce2_counter += 1
108
+ # Build coinbase transaction
109
+ coinbase_tx = binascii.unhexlify(coinb1) + binascii.unhexlify(extranonce1) + binascii.unhexlify(extranonce2) + binascii.unhexlify(coinb2)
110
+ coinbase_hash = hashlib.sha256(hashlib.sha256(coinbase_tx).digest())
111
+ # Compute Merkle root
112
+ merkle_root_hex = calculate_merkle_root(coinbase_hash, merkle_branch)
113
+ merkle_root = binascii.unhexlify(merkle_root_hex)[::-1]
114
+ # Construct block header
115
+ version_bytes = struct.pack("<I", int(version, 16))
116
+ prevhash_bytes = binascii.unhexlify(prevhash)[::-1]
117
+ nbits_bytes = binascii.unhexlify(nbits)[::-1]
118
+ ntime_bytes = struct.pack("<I", int(ntime, 16))
119
+ nonce = 0
120
+ target = bits_to_target(nbits)
121
+ print(f"πŸ”¨ Mining job {job_id}, Target: {target}")
122
+ # Start mining
123
+ start_time = time.time()
124
+ while time.time() - start_time < 10:
125
+ nonce_bytes = struct.pack("<I", nonce)
126
+ block_header = (
127
+ version_bytes +
128
+ prevhash_bytes +
129
+ merkle_root +
130
+ ntime_bytes +
131
+ nbits_bytes +
132
+ nonce_bytes
133
+ )
134
+ # Double SHA-256
135
+ hash_result = hashlib.sha256(hashlib.sha256(block_header).digest()).hexdigest()
136
+ hash_int = int(hash_result, 16)
137
+ hash_count += 1 # Increment hash count for hashrate calculation
138
+ if hash_int < target:
139
+ print(f"πŸŽ‰ Valid share found! Nonce: {nonce}")
140
+ submit_msg = {
141
+ "id": 4,
142
+ "method": "mining.submit",
143
+ "params": [
144
+ username,
145
+ job_id,
146
+ extranonce2,
147
+ ntime,
148
+ f"{nonce:08x}"
149
+ ]
150
+ }
151
+ sock.sendall((json.dumps(submit_msg) + '\n').encode())
152
+ print("πŸ“€ Submitted share.")
153
+ break
154
+ nonce += 1
155
+
156
+ current_time = time.time()
157
+ if current_time - last_report_time >= report_interval:
158
+ elapsed_time = current_time - last_report_time
159
+ hashes_per_second = hash_count / elapsed_time
160
+ print(f"πŸ“Š Hashrate: {hashes_per_second:.2f} H/s") # Display Hashrate
161
+ hash_count = 0 # Reset hash counter
162
+ last_report_time = current_time # Update last report time
163
+
164
+
165
+ except KeyboardInterrupt:
166
+ print("⏹️ Mining stopped.")
167
+ finally:
168
+ sock.close()
169
+ def bits_to_target(nbits_hex):
170
+ nbits = int(nbits_hex, 16)
171
+ exponent = nbits >> 24
172
+ mantissa = nbits & 0xffffff
173
+ return mantissa << (8 * (exponent - 3))
174
+
175
+ def main_sha256():
176
+ sock = create_tcp_connection(HOST, PORT)
177
+ sub_res, extranonce1, extranonce2_size = subscribe_sha256(sock)
178
+ authorize_sha256(sock, USERNAME, PASSWORD)
179
+ mine_sha256(sock, USERNAME, extranonce1, extranonce2_size)
180
+
181
+ if __name__ == "__main__":
182
+ main_sha256()