3 from twisted.internet import protocol, reactor
5 from p2pool.bitcoin import data as bitcoin_data, getwork
6 from p2pool.util import expiring_dict, jsonrpc, pack
9 class StratumRPCMiningProvider(object):
10 def __init__(self, wb, other):
15 self.handler_map = expiring_dict.ExpiringDict(300)
17 self.watch_id = self.wb.new_work_event.watch(self._send_work)
19 def rpc_subscribe(self):
21 ["mining.notify", "ae6812eb4cd7735a302a8a9dd95cf71f"], # subscription details
26 def rpc_authorize(self, username, password):
27 self.username = username
29 reactor.callLater(0, self._send_work)
32 if self.username is None: # authorize hasn't been received yet
35 x, got_response = self.wb.get_work(*self.wb.get_user_details(self.username)[1:])
36 jobid = str(random.randrange(2**128))
37 self.other.svc_mining.rpc_set_difficulty(bitcoin_data.target_to_difficulty(x['share_target'])).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 x, got_response = self.handler_map[job_id]
53 coinb_nonce = pack.IntType(32).unpack(extranonce2.decode('hex'))
54 new_packed_gentx = x['coinb1'] + pack.IntType(32).pack(coinb_nonce) + x['coinb2']
57 previous_block=x['previous_block'],
58 merkle_root=bitcoin_data.check_merkle_link(bitcoin_data.hash256(new_packed_gentx), x['merkle_link']),
59 timestamp=pack.IntType(32).unpack(getwork._swap4(ntime.decode('hex'))),
61 nonce=pack.IntType(32).unpack(getwork._swap4(nonce.decode('hex'))),
63 return got_response(header, worker_name, coinb_nonce)
66 self.wb.new_work_event.unwatch(self.watch_id)
68 class StratumProtocol(jsonrpc.LineBasedPeer):
69 def connectionMade(self):
70 self.svc_mining = StratumRPCMiningProvider(self.factory.wb, self.other)
72 def connectionLost(self, reason):
73 self.svc_mining.close()
75 class StratumServerFactory(protocol.ServerFactory):
76 protocol = StratumProtocol
78 def __init__(self, wb):