-
Notifications
You must be signed in to change notification settings - Fork 18
/
cellminer.rb
419 lines (332 loc) · 10.2 KB
/
cellminer.rb
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
#
# cellminer - Bitcoin miner for the Cell Broadband Engine Architecture
# Copyright © 2011 Robert Leslie
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License (version 2) as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
require 'optparse'
require 'uri'
require 'thread'
require_relative 'bitcoin.rb'
require_relative 'ext/cellminer.so'
require_relative 'sha256.rb'
class CellMiner
attr_accessor :options
attr_reader :rpc
class AbortMining < StandardError; end
USER_AGENT = "Cell Miner"
NSLICES = 128
QUANTUM = 0x100000000 / NSLICES
QUEUE_MAX = 384
RETRY_INTERVAL = 30
def initialize(argv = [])
@options = Hash.new
options[:num_spe] = Bitcoin::SPUMiner::USABLE_SPES
options[:num_ppe] = 0
options[:interval] = 60
options[:debug] = $DEBUG
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] [server]"
opts.on("-u", "--username USER", String,
"RPC Username") do |username|
options[:username] = username
end
opts.on("-p", "--password PASS", String,
"RPC Password") do |password|
options[:password] = password
end
opts.on("--spe N", Integer,
"Number of SPEs to use (default %d)" %
options[:num_spe]) do |opt|
options[:num_spe] = opt
end
opts.on("--ppe N", Integer,
"Number of PPE threads to use (default %d)" %
options[:num_ppe]) do |opt|
options[:num_ppe] = opt
end
opts.on("-i", "--interval SECS", Integer,
"Work polling interval (default %d)" %
options[:interval]) do |opt|
options[:interval] = opt
end
opts.on("-b", "--balance",
"Show balance and exit") do |opt|
options[:balance] = opt
end
opts.on("--test",
"Use known testing data") do |opt|
options[:test] = opt
end
opts.on("-d", "--debug",
"Show debugging output") do |opt|
options[:debug] = opt
end
end.parse!(argv)
server = argv.shift || ENV['BITCOIN_SERVER'] ||
begin
warn "Warning: using default server localhost"
'localhost'
end
params = {}
uri = URI.parse(server) rescue nil
if uri.kind_of? URI::HTTP
host, port = uri.host, uri.port
params[:path] = uri.path unless uri.path.empty?
else
host, port = server.split(':')
end
params[:host] = host
params[:port] = port.to_i if port
params[:username] = options[:username] if options[:username]
params[:password] = options[:password] if options[:password]
@rpc = Bitcoin.rpc_proxy(params, USER_AGENT)
@mutex = Mutex.new
end
def main
if options[:balance]
puts "Current balance = #{rpc.getbalance} BTC"
exit
end
say "%s starting" % USER_AGENT
work_queue = Queue.new
solved_queue = Queue.new
miner_proc = lambda do |miner_class|
miner = miner_class.new(options[:debug])
loop do
begin
start = Time.now
work = work_queue.shift
debug "#{miner} Mining %08x..%08x" %
[work[:start_nonce], work[:start_nonce] + work[:range] - 1]
if solution = miner.run(work[:data], work[:target], work[:midstate],
work[:start_nonce], work[:range])
debug "#{miner} Found solution"
solved_queue << solution
else
Thread.current[:rate] = work[:range] / (Time.now - start)
end
rescue AbortMining
end
end
end
Thread.abort_on_exception = true
miners = ThreadGroup.new
class << miners
include Enumerable
alias << add
def empty?
list.empty?
end
def each(&block)
list.each(&block)
end
def rate
inject(0.0) {|sum, thread| sum + (thread[:rate] || 0) }
end
def abort
each {|thread| thread.raise AbortMining }
end
end
if options[:num_spe] > 0
say "Creating %d SPU miner(s)" % options[:num_spe]
options[:num_spe].times do
miners << Thread.new(Bitcoin::SPUMiner, &miner_proc)
end
end
if options[:num_ppe] > 0
say "Creating %d PPU miner(s)" % options[:num_ppe]
options[:num_ppe].times do
miners << Thread.new(Bitcoin::PPUMiner, &miner_proc)
end
end
if miners.empty?
$stderr.puts "No miners!"
exit 1
end
getwork_queue = Queue.new
# work processing thread
Thread.new do
last_block = nil
last_target = nil
loop do
work = getwork_queue.shift
prev_block = work[:data][4..35].reverse.unpack('H*').first
target = work[:target].unpack('H*').first
msg = "Got work... %.3f Mhash/s, %d backlogged work items" %
[miners.rate / 1_000_000, work_queue.length]
if target != last_target
last_target = target
msg << "\n target = %s" % target
end
if prev_block != last_block
last_block = prev_block
msg << "\n prev = %s" % prev_block
work_queue.clear
miners.abort
solved_queue.clear
end
say msg
work[:range] = QUANTUM
NSLICES.times do |i|
work[:start_nonce] = i * QUANTUM
work_queue << work.dup
end
# trim excess work
work_queue.shift(true) while work_queue.length > QUEUE_MAX
end
end
# work gathering thread
getwork_thread = Thread.new do
loop do
getwork_queue << getwork do |poll_rpc|
unless @long_polling
@long_polling = true
say "Starting long poll"
# long polling thread
Thread.new do
loop do
work = getwork(poll_rpc)
say "Long poll returned"
getwork_queue << work
end
end
end
end
sleep options[:interval]
end
end
# solution gathering thread
loop do
solution = solved_queue.shift
# send back to server...
response = sendwork(solution)
say "Solved? (%s)\n %s hash = %s" %
[response, response == true ? '*' : ' ', block_hash(solution)]
return if options[:test]
getwork_thread.run if response == false
end
end
private
def say(info)
@mutex.synchronize do
puts "[%s] %s" % [Time.now.strftime("%Y-%m-%d %H:%M:%S"), info]
end
end
def debug(info)
say(info) if options[:debug]
end
def getwork(rpc = rpc, &block)
begin
work = options[:test] ? testwork : rpc.getwork(&block)
rescue => err
say "RPC (getwork) error: %s" % err
sleep RETRY_INTERVAL
retry
end
# unpack hex strings and fix byte ordering
work = work.map do |k, v|
k = k.to_sym
v = [v.to_s].pack('H*')
v = (k == :target) ? v.reverse : v.unpack('V*').pack('N*')
[k, v]
end
Hash[work]
end
def sendwork(solution)
data = solution.unpack('N*').pack('V*').unpack('H*').first
begin
rpc.getwork(data)
rescue => err
say "RPC (sendwork) error: %s" % err
sleep RETRY_INTERVAL
retry
end
end
def block_hash(data)
hash0 = SHA256.new.update(data)
hash1 = [UInt256.new(hash0.hexdigest).byte_string,
0x80000000, 0, 0, 0, 0, 0, 0, 0x100].pack('a32N8')
hash1 = SHA256.new.update(hash1)
hash1.digest.reverse.unpack('H*').first
end
def testwork
say "Using test data"
# Test data for known block (#115558)
hash = UInt256.new("000000000000bd26aaf867f23a7b66b6" \
"2ffe1e402f79a424ef8b3e4e84c68f32")
version = 1
prev_block = UInt256.new("00000000000090b0cae8c5fea2fffac9" \
"f909c097f0402637c59647b91bbd896f")
merkle_root = UInt256.new("15fbf39fd7120dd06950467fbdf9d226" \
"9ed3f63796b0acab93d89e2888e2b10a")
time = 1301376879
bits = 453047097
nonce = 3406758657
datav = [version,
prev_block.reverse_endian.byte_string,
merkle_root.reverse_endian.byte_string,
time, bits, nonce,
0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0280]
check = SHA256.new.update(datav.pack('Va32a32V3N12'))
hash1 = [UInt256.new(check.hexdigest).byte_string,
0x80000000, 0, 0, 0, 0, 0, 0, 0x100].pack('a32N8')
check = SHA256.new.update(hash1)
debug "Supposed hash\n = %s" % hash
debug "Calculated hash\n = %s" %
UInt256.new(check.hexdigest).reverse_endian
# zero nonce
datav[5] = 0
data = datav.pack('Va32a32V3N12')
midstate = UInt256.new(SHA256.new.update(data[0..63]).hexdigest)
target = UInt256.new((bits & 0x00ffffff) * 2**(8 * ((bits >> 24) - 3)))
# reverse-endian crap
data = data.unpack('V*').pack('N*')
target = target.reverse_endian.byte_string
midstate = midstate.byte_string.unpack('V*').pack('N*')
hash1 = hash1.unpack('V*').pack('N*')
{
:data => data.unpack('H*').first,
:target => target.unpack('H*').first,
:midstate => midstate.unpack('H*').first,
:hash1 => hash1.unpack('H*').first
}
end
end
class UInt256
attr_accessor :value
def initialize(value)
case value
when Integer
when String
value = pack_chars [value].pack('H*').unpack('C*')
else
raise TypeError, "can't cast #{value.class} as #{self.class}"
end
@value = value
end
def to_s
"%064x" % value
end
def byte_string
[to_s].pack('H*')
end
def reverse_endian
self.class.new(pack_chars byte_string.unpack('C*').reverse)
end
private
def pack_chars(chars)
chars.inject(0) {|v, ch| (v << 8) + ch }
end
end