4 from twisted.internet import protocol, reactor
6 from p2pool.bitcoin import data as bitcoin_data, getwork
7 from p2pool.util import expiring_dict, jsonrpc, pack
10 class StratumRPCMiningProvider(object):
11 def __init__(self, wb, other):
16 self.handler_map = expiring_dict.ExpiringDict(300)
18 self.watch_id = self.wb.new_work_event.watch(self._send_work)
20 def rpc_subscribe(self, miner_version=None, session_id=None):
21 reactor.callLater(0, self._send_work)
24 ["mining.notify", "ae6812eb4cd7735a302a8a9dd95cf71f"], # subscription details
26 self.wb.COINBASE_NONCE_LENGTH, # extranonce2_size
29 def rpc_authorize(self, username, password):
30 self.username = username
32 reactor.callLater(0, self._send_work)
35 x, got_response = self.wb.get_work(*self.wb.preprocess_request('' if self.username is None else self.username))
36 jobid = str(random.randrange(2**128))
37 self.other.svc_mining.rpc_set_difficulty(bitcoin_data.target_to_difficulty(x['share_target'])*self.wb.net.DUMB_SCRYPT_DIFF).addErrback(lambda err: None)
38 self.other.svc_mining.rpc_notify(
40 getwork._swap4(pack.IntType(256).pack(x['previous_block'])).encode('hex'), # prevhash
41 x['coinb1'].encode('hex'), # coinb1
42 x['coinb2'].encode('hex'), # coinb2
43 [pack.IntType(256).pack(s).encode('hex') for s in x['merkle_link']['branch']], # merkle_branch
44 getwork._swap4(pack.IntType(32).pack(x['version'])).encode('hex'), # version
45 getwork._swap4(pack.IntType(32).pack(x['bits'].bits)).encode('hex'), # nbits
46 getwork._swap4(pack.IntType(32).pack(x['timestamp'])).encode('hex'), # ntime
48 ).addErrback(lambda err: None)
49 self.handler_map[jobid] = x, got_response
51 def rpc_submit(self, worker_name, job_id, extranonce2, ntime, nonce):
52 if job_id not in self.handler_map:
53 print >>sys.stderr, '''Couldn't link returned work's job id with its handler. This should only happen if this process was recently restarted!'''
55 x, got_response = self.handler_map[job_id]
56 coinb_nonce = extranonce2.decode('hex')
57 assert len(coinb_nonce) == self.wb.COINBASE_NONCE_LENGTH
58 new_packed_gentx = x['coinb1'] + coinb_nonce + x['coinb2']
61 previous_block=x['previous_block'],
62 merkle_root=bitcoin_data.check_merkle_link(bitcoin_data.hash256(new_packed_gentx), x['merkle_link']),
63 timestamp=pack.IntType(32).unpack(getwork._swap4(ntime.decode('hex'))),
65 nonce=pack.IntType(32).unpack(getwork._swap4(nonce.decode('hex'))),
67 return got_response(header, worker_name, coinb_nonce)
70 self.wb.new_work_event.unwatch(self.watch_id)
72 class StratumProtocol(jsonrpc.LineBasedPeer):
73 def connectionMade(self):
74 self.svc_mining = StratumRPCMiningProvider(self.factory.wb, self.other)
76 def connectionLost(self, reason):
77 self.svc_mining.close()
79 class StratumServerFactory(protocol.ServerFactory):
80 protocol = StratumProtocol
82 def __init__(self, wb):