Improved exception handling of submit()
[stratum-mining.git] / lib / template_registry.py
1 import weakref
2 import binascii
3 import util
4 import StringIO
5
6 from twisted.internet import defer
7 from lib.exceptions import SubmitException
8
9 import stratum.logger
10 log = stratum.logger.get_logger('template_registry')
11
12 from mining.interfaces import Interfaces
13 from extranonce_counter import ExtranonceCounter
14
15 class JobIdGenerator(object):
16     '''Generate pseudo-unique job_id. It does not need to be absolutely unique,
17     because pool sends "clean_jobs" flag to clients and they should drop all previous jobs.'''
18     counter = 0
19     
20     @classmethod
21     def get_new_id(cls):
22         cls.counter += 1
23         if cls.counter % 0xffff == 0:
24             cls.counter = 1
25         return "%x" % cls.counter
26                 
27 class TemplateRegistry(object):
28     '''Implements the main logic of the pool. Keep track
29     on valid block templates, provide internal interface for stratum
30     service and implements block validation and submits.'''
31     
32     def __init__(self, block_template_class, coinbaser, bitcoin_rpc, instance_id,
33                  on_block_callback):
34         self.prevhashes = {}
35         self.jobs = weakref.WeakValueDictionary()
36         
37         self.extranonce_counter = ExtranonceCounter(instance_id)
38         self.extranonce2_size = block_template_class.coinbase_transaction_class.extranonce_size \
39                 - self.extranonce_counter.get_size()
40                  
41         self.coinbaser = coinbaser
42         self.block_template_class = block_template_class
43         self.bitcoin_rpc = bitcoin_rpc
44         self.on_block_callback = on_block_callback
45         
46         self.last_block = None
47         self.update_in_progress = False
48         self.last_update = None
49         
50         # Create first block template on startup
51         self.update_block()
52         
53     def get_new_extranonce1(self):
54         '''Generates unique extranonce1 (e.g. for newly
55         subscribed connection.'''
56         return self.extranonce_counter.get_new_bin()
57     
58     def get_last_broadcast_args(self):
59         '''Returns arguments for mining.notify
60         from last known template.'''
61         return self.last_block.broadcast_args
62         
63     def add_template(self, block):
64         '''Adds new template to the registry.
65         It also clean up templates which should
66         not be used anymore.'''
67         
68         prevhash = block.prevhash_hex
69
70         if prevhash in self.prevhashes.keys():
71             new_block = False
72         else:
73             new_block = True
74             self.prevhashes[prevhash] = []
75                
76         # Blocks sorted by prevhash, so it's easy to drop
77         # them on blockchain update
78         self.prevhashes[prevhash].append(block)
79         
80         # Weak reference for fast lookup using job_id
81         self.jobs[block.job_id] = block
82         
83         # Use this template for every new request
84         self.last_block = block
85         
86         # Drop templates of obsolete blocks
87         for ph in self.prevhashes.keys():
88             if ph != prevhash:
89                 del self.prevhashes[ph]
90                 
91         log.info("New template for %s" % prevhash)
92         self.on_block_callback(new_block)
93         #from twisted.internet import reactor
94         #reactor.callLater(10, self.on_block_callback, new_block) 
95               
96     def update_block(self):
97         '''Registry calls the getblocktemplate() RPC
98         and build new block template.'''
99         
100         if self.update_in_progress:
101             # Block has been already detected
102             return
103         
104         self.update_in_progress = True
105         self.last_update = Interfaces.timestamper.time()
106         
107         d = self.bitcoin_rpc.getblocktemplate()
108         d.addCallback(self._update_block)
109         d.addErrback(self._update_block_failed)
110         
111     def _update_block_failed(self, failure):
112         log.error(str(failure))
113         self.update_in_progress = False
114         
115     def _update_block(self, data):
116         start = Interfaces.timestamper.time()
117                 
118         template = self.block_template_class(Interfaces.timestamper, self.coinbaser, JobIdGenerator.get_new_id())
119         template.fill_from_rpc(data)
120         self.add_template(template)
121
122         log.info("Update finished, %.03f sec, %d txes" % \
123                     (Interfaces.timestamper.time() - start, len(template.vtx)))
124         
125         self.update_in_progress = False        
126         return data
127     
128     def diff_to_target(self, difficulty):
129         '''Converts difficulty to target'''
130         diff1 = 0x00000000ffff0000000000000000000000000000000000000000000000000000 
131         return diff1 / difficulty
132     
133     def get_job(self, job_id):
134         '''For given job_id returns BlockTemplate instance or None'''
135         try:
136             j = self.jobs[job_id]
137         except:
138             log.info("Job id '%s' not found" % job_id)
139             return None
140         
141         # Now we have to check if job is still valid.
142         # Unfortunately weak references are not bulletproof and
143         # old reference can be found until next run of garbage collector.
144         if j.prevhash_hex not in self.prevhashes:
145             log.info("Prevhash of job '%s' is unknown" % job_id)
146             return None
147         
148         if j not in self.prevhashes[j.prevhash_hex]:
149             log.info("Job %s is unknown" % job_id)
150             return None
151         
152         return j
153         
154     def submit_share(self, job_id, worker_name, extranonce1_bin, extranonce2, ntime, nonce,
155                      difficulty):
156         '''Check parameters and finalize block template. If it leads
157            to valid block candidate, asynchronously submits the block
158            back to the bitcoin network.
159         
160             - extranonce1_bin is binary. No checks performed, it should be from session data
161             - job_id, extranonce2, ntime, nonce - in hex form sent by the client
162             - difficulty - decimal number from session, again no checks performed
163             - submitblock_callback - reference to method which receive result of submitblock()
164         '''
165         
166         # Check if extranonce2 looks correctly. extranonce2 is in hex form...
167         if len(extranonce2) != self.extranonce2_size * 2:
168             raise SubmitException("Incorrect size of extranonce2. Expected %d chars" % (self.extranonce2_size*2))
169         
170         # Check for job
171         job = self.get_job(job_id)
172         if job == None:
173             raise SubmitException("Job '%s' not found" % job_id)
174                 
175         # Check if ntime looks correct
176         if len(ntime) != 8:
177             raise SubmitException("Incorrect size of ntime. Expected 8 chars")
178
179         if not job.check_ntime(int(ntime, 16)):
180             raise SubmitException("Ntime out of range")
181         
182         # Check nonce        
183         if len(nonce) != 8:
184             raise SubmitException("Incorrect size of nonce. Expected 8 chars")
185         
186         # Check for duplicated submit
187         if not job.register_submit(extranonce1_bin, extranonce2, ntime, nonce):
188             log.info("Duplicate from %s, (%s %s %s %s)" % \
189                     (worker_name, binascii.hexlify(extranonce1_bin), extranonce2, ntime, nonce))
190             raise SubmitException("Duplicate share")
191         
192         # Now let's do the hard work!
193         # ---------------------------
194         
195         # 0. Some sugar
196         extranonce2_bin = binascii.unhexlify(extranonce2)
197         ntime_bin = binascii.unhexlify(ntime)
198         nonce_bin = binascii.unhexlify(nonce)
199                 
200         # 1. Build coinbase
201         coinbase_bin = job.serialize_coinbase(extranonce1_bin, extranonce2_bin)
202         coinbase_hash = util.doublesha(coinbase_bin)
203         
204         # 2. Calculate merkle root
205         merkle_root_bin = job.merkletree.withFirst(coinbase_hash)
206         merkle_root_int = util.uint256_from_str(merkle_root_bin)
207                 
208         # 3. Serialize header with given merkle, ntime and nonce
209         header_bin = job.serialize_header(merkle_root_int, ntime_bin, nonce_bin)
210     
211         # 4. Reverse header and compare it with target of the user
212         hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
213         hash_int = util.uint256_from_str(hash_bin)
214         block_hash_hex = "%064x" % hash_int
215         header_hex = binascii.hexlify(header_bin)
216                  
217         target_user = self.diff_to_target(difficulty)        
218         if hash_int > target_user:
219             raise SubmitException("Share is above target")
220
221         # Mostly for debugging purposes
222         target_info = self.diff_to_target(100000)
223         if hash_int <= target_info:
224             log.info("Yay, share with diff above 100000")
225
226         # 5. Compare hash with target of the network        
227         if hash_int <= job.target:
228             # Yay! It is block candidate! 
229             log.info("We found a block candidate! %s" % block_hash_hex)
230            
231             # 6. Finalize and serialize block object 
232             job.finalize(merkle_root_int, extranonce1_bin, extranonce2_bin, int(ntime, 16), int(nonce, 16))
233             
234             if not job.is_valid():
235                 # Should not happen
236                 log.error("Final job validation failed!")
237                             
238             # 7. Submit block to the network
239             serialized = binascii.hexlify(job.serialize())
240             on_submit = self.bitcoin_rpc.submitblock(serialized)
241             
242             return (header_hex, block_hash_hex, on_submit)
243         
244         return (header_hex, block_hash_hex, None)