-
Notifications
You must be signed in to change notification settings - Fork 43
/
ntgbtminer.py
482 lines (351 loc) · 13.6 KB
/
ntgbtminer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# ntgbtminer - vsergeev - https://github.com/vsergeev/ntgbtminer
#
# No Thrils GetBlockTemplate Bitcoin Miner
#
# This is mostly a demonstration of the GBT protocol.
# It mines at a measly 550 KH/s on my computer, but
# with a whole lot of spirit ;)
#
import urllib.request
import urllib.error
import urllib.parse
import base64
import json
import hashlib
import struct
import random
import time
import os
import sys
# JSON-HTTP RPC Configuration
# This will be particular to your local ~/.bitcoin/bitcoin.conf
RPC_URL = os.environ.get("RPC_URL", "http://127.0.0.1:8332")
RPC_USER = os.environ.get("RPC_USER", "bitcoinrpc")
RPC_PASS = os.environ.get("RPC_PASS", "")
################################################################################
# Bitcoin Daemon JSON-HTTP RPC
################################################################################
def rpc(method, params=None):
"""
Make an RPC call to the Bitcoin Daemon JSON-HTTP server.
Arguments:
method (string): RPC method
params: RPC arguments
Returns:
object: RPC response result.
"""
rpc_id = random.getrandbits(32)
data = json.dumps({"id": rpc_id, "method": method, "params": params}).encode()
auth = base64.encodebytes((RPC_USER + ":" + RPC_PASS).encode()).decode().strip()
request = urllib.request.Request(RPC_URL, data, {"Authorization": "Basic {:s}".format(auth)})
with urllib.request.urlopen(request) as f:
response = json.loads(f.read())
if response['id'] != rpc_id:
raise ValueError("Invalid response id: got {}, expected {:u}".format(response['id'], rpc_id))
elif response['error'] is not None:
raise ValueError("RPC error: {:s}".format(json.dumps(response['error'])))
return response['result']
################################################################################
# Bitcoin Daemon RPC Call Wrappers
################################################################################
def rpc_getblocktemplate():
try:
return rpc("getblocktemplate", [{"rules": ["segwit"]}])
except ValueError:
return {}
def rpc_submitblock(block_submission):
return rpc("submitblock", [block_submission])
################################################################################
# Representation Conversion Utility Functions
################################################################################
def int2lehex(value, width):
"""
Convert an unsigned integer to a little endian ASCII hex string.
Args:
value (int): value
width (int): byte width
Returns:
string: ASCII hex string
"""
return value.to_bytes(width, byteorder='little').hex()
def int2varinthex(value):
"""
Convert an unsigned integer to little endian varint ASCII hex string.
Args:
value (int): value
Returns:
string: ASCII hex string
"""
if value < 0xfd:
return int2lehex(value, 1)
elif value <= 0xffff:
return "fd" + int2lehex(value, 2)
elif value <= 0xffffffff:
return "fe" + int2lehex(value, 4)
else:
return "ff" + int2lehex(value, 8)
def bitcoinaddress2hash160(addr):
"""
Convert a Base58 Bitcoin address to its Hash-160 ASCII hex string.
Args:
addr (string): Base58 Bitcoin address
Returns:
string: Hash-160 ASCII hex string
"""
table = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
hash160 = 0
addr = addr[::-1]
for i, c in enumerate(addr):
hash160 += (58 ** i) * table.find(c)
# Convert number to 50-byte ASCII Hex string
hash160 = "{:050x}".format(hash160)
# Discard 1-byte network byte at beginning and 4-byte checksum at the end
return hash160[2:50 - 8]
################################################################################
# Transaction Coinbase and Hashing Functions
################################################################################
def tx_encode_coinbase_height(height):
"""
Encode the coinbase height, as per BIP 34:
https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki
Arguments:
height (int): height of the mined block
Returns:
string: encoded height as an ASCII hex string
"""
width = (height.bit_length() + 7) // 8
return bytes([width]).hex() + int2lehex(height, width)
def tx_make_coinbase(coinbase_script, address, value, height):
"""
Create a coinbase transaction.
Arguments:
coinbase_script (string): arbitrary script as an ASCII hex string
address (string): Base58 Bitcoin address
value (int): coinbase value
height (int): mined block height
Returns:
string: coinbase transaction as an ASCII hex string
"""
# See https://en.bitcoin.it/wiki/Transaction
coinbase_script = tx_encode_coinbase_height(height) + coinbase_script
# Create a pubkey script
# OP_DUP OP_HASH160 <len to push> <pubkey> OP_EQUALVERIFY OP_CHECKSIG
pubkey_script = "76" + "a9" + "14" + bitcoinaddress2hash160(address) + "88" + "ac"
tx = ""
# version
tx += "01000000"
# in-counter
tx += "01"
# input[0] prev hash
tx += "0" * 64
# input[0] prev seqnum
tx += "ffffffff"
# input[0] script len
tx += int2varinthex(len(coinbase_script) // 2)
# input[0] script
tx += coinbase_script
# input[0] seqnum
tx += "ffffffff"
# out-counter
tx += "01"
# output[0] value
tx += int2lehex(value, 8)
# output[0] script len
tx += int2varinthex(len(pubkey_script) // 2)
# output[0] script
tx += pubkey_script
# lock-time
tx += "00000000"
return tx
def tx_compute_hash(tx):
"""
Compute the SHA256 double hash of a transaction.
Arguments:
tx (string): transaction data as an ASCII hex string
Return:
string: transaction hash as an ASCII hex string
"""
return hashlib.sha256(hashlib.sha256(bytes.fromhex(tx)).digest()).digest()[::-1].hex()
def tx_compute_merkle_root(tx_hashes):
"""
Compute the Merkle Root of a list of transaction hashes.
Arguments:
tx_hashes (list): list of transaction hashes as ASCII hex strings
Returns:
string: merkle root as a big endian ASCII hex string
"""
# Convert list of ASCII hex transaction hashes into bytes
tx_hashes = [bytes.fromhex(tx_hash)[::-1] for tx_hash in tx_hashes]
# Iteratively compute the merkle root hash
while len(tx_hashes) > 1:
# Duplicate last hash if the list is odd
if len(tx_hashes) % 2 != 0:
tx_hashes.append(tx_hashes[-1])
tx_hashes_new = []
for i in range(len(tx_hashes) // 2):
# Concatenate the next two
concat = tx_hashes.pop(0) + tx_hashes.pop(0)
# Hash them
concat_hash = hashlib.sha256(hashlib.sha256(concat).digest()).digest()
# Add them to our working list
tx_hashes_new.append(concat_hash)
tx_hashes = tx_hashes_new
# Format the root in big endian ascii hex
return tx_hashes[0][::-1].hex()
################################################################################
# Block Preparation Functions
################################################################################
def block_make_header(block):
"""
Make the block header.
Arguments:
block (dict): block template
Returns:
bytes: block header
"""
header = b""
# Version
header += struct.pack("<L", block['version'])
# Previous Block Hash
header += bytes.fromhex(block['previousblockhash'])[::-1]
# Merkle Root Hash
header += bytes.fromhex(block['merkleroot'])[::-1]
# Time
header += struct.pack("<L", block['curtime'])
# Target Bits
header += bytes.fromhex(block['bits'])[::-1]
# Nonce
header += struct.pack("<L", block['nonce'])
return header
def block_compute_raw_hash(header):
"""
Compute the raw SHA256 double hash of a block header.
Arguments:
header (bytes): block header
Returns:
bytes: block hash
"""
return hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1]
def block_bits2target(bits):
"""
Convert compressed target (block bits) encoding to target value.
Arguments:
bits (string): compressed target as an ASCII hex string
Returns:
bytes: big endian target
"""
# Bits: 1b0404cb
# 1b left shift of (0x1b - 3) bytes
# 0404cb value
bits = bytes.fromhex(bits)
shift = bits[0] - 3
value = bits[1:]
# Shift value to the left by shift
target = value + b"\x00" * shift
# Add leading zeros
target = b"\x00" * (32 - len(target)) + target
return target
def block_make_submit(block):
"""
Format a solved block into the ASCII hex submit format.
Arguments:
block (dict): block template with 'nonce' and 'hash' populated
Returns:
string: block submission as an ASCII hex string
"""
submission = ""
# Block header
submission += block_make_header(block).hex()
# Number of transactions as a varint
submission += int2varinthex(len(block['transactions']))
# Concatenated transactions data
for tx in block['transactions']:
submission += tx['data']
return submission
################################################################################
# Block Miner
################################################################################
def block_mine(block_template, coinbase_message, extranonce_start, address, timeout=None, debugnonce_start=False):
"""
Mine a block.
Arguments:
block_template (dict): block template
coinbase_message (bytes): binary string for coinbase script
extranonce_start (int): extranonce offset for coinbase script
address (string): Base58 Bitcoin address for block reward
Timeout:
timeout (float): timeout in seconds
debugnonce_start (int): nonce start for testing purposes
Returns:
(block submission, hash rate) on success,
(None, hash rate) on timeout or nonce exhaustion.
"""
# Add an empty coinbase transaction to the block template transactions
coinbase_tx = {}
block_template['transactions'].insert(0, coinbase_tx)
# Add a nonce initialized to zero to the block template
block_template['nonce'] = 0
# Compute the target hash
target_hash = block_bits2target(block_template['bits'])
# Mark our mine start time
time_start = time.time()
# Initialize our running average of hashes per second
hash_rate, hash_rate_count = 0.0, 0
# Loop through the extranonce
extranonce = extranonce_start
while extranonce <= 0xffffffff:
# Update the coinbase transaction with the new extra nonce
coinbase_script = coinbase_message + int2lehex(extranonce, 4)
coinbase_tx['data'] = tx_make_coinbase(coinbase_script, address, block_template['coinbasevalue'], block_template['height'])
coinbase_tx['hash'] = tx_compute_hash(coinbase_tx['data'])
# Recompute the merkle root
block_template['merkleroot'] = tx_compute_merkle_root([tx['hash'] for tx in block_template['transactions']])
# Reform the block header
block_header = block_make_header(block_template)
time_stamp = time.time()
# Loop through the nonce
nonce = 0 if not debugnonce_start else debugnonce_start
while nonce <= 0xffffffff:
# Update the block header with the new 32-bit nonce
block_header = block_header[0:76] + nonce.to_bytes(4, byteorder='little')
# Recompute the block hash
block_hash = block_compute_raw_hash(block_header)
# Check if it the block meets the target hash
if block_hash < target_hash:
block_template['nonce'] = nonce
block_template['hash'] = block_hash.hex()
return (block_template, hash_rate)
# Measure hash rate and check timeout
if nonce > 0 and nonce % 1048576 == 0:
hash_rate = hash_rate + ((1048576 / (time.time() - time_stamp)) - hash_rate) / (hash_rate_count + 1)
hash_rate_count += 1
time_stamp = time.time()
# If our mine time expired, return none
if timeout and (time_stamp - time_start) > timeout:
return (None, hash_rate)
nonce += 1
extranonce += 1
# If we ran out of extra nonces, return none
return (None, hash_rate)
################################################################################
# Standalone Bitcoin Miner, Single-threaded
################################################################################
def standalone_miner(coinbase_message, address):
while True:
block_template = rpc_getblocktemplate()
print("Mining block template, height {:d}...".format(block_template['height']))
mined_block, hash_rate = block_mine(block_template, coinbase_message, 0, address, timeout=60)
print(" {:.4f} KH/s\n".format(hash_rate / 1000.0))
if mined_block:
print("Solved a block! Block hash: {}".format(mined_block['hash']))
submission = block_make_submit(mined_block)
print("Submitting:", submission, "\n")
response = rpc_submitblock(submission)
if response is not None:
print("Submission Error: {}".format(response))
break
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: {:s} <coinbase message> <block reward address>".format(sys.argv[0]))
sys.exit(1)
standalone_miner(sys.argv[1].encode().hex(), sys.argv[2])