Пример #1
0
    def on_template(cls, is_new_block):
        """This is called when TemplateRegistry registers
           new block which we have to broadcast clients."""
        
        start = Interfaces.timestamper.time()
        clean_jobs = is_new_block
        
        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
            Interfaces.template_registry.get_last_broadcast_args()

        # Push new job to subscribed clients
        for subscription in Pubsub.iterate_subscribers(cls.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault('authorized', {})
                    if session['authorized'].keys():
                        worker_name = session['authorized'].keys()[0]
                        difficulty = session['difficulty']
                        work_id = Interfaces.worker_manager.register_work(worker_name, job_id, difficulty)
                        #log.debug("emitting for work id %s job id %s block %s " % (work_id, job_id, prevhash))
                        subscription.emit_single(work_id, prevhash, coinb1, coinb2, merkle_branch, version,
                                                 nbits, ntime, clean_jobs)
                    else:
                        subscription.emit_single(job_id, prevhash, coinb1, coinb2, merkle_branch, version,
                                                 nbits, ntime, clean_jobs)
            except Exception as e:
                log.exception("Error broadcasting work to client %s" % str(e))
                pass
        
        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (Interfaces.timestamper.time() - start)))
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''
        
        start = Interfaces.timestamper.time()
        clean_jobs = is_new_block
        
        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
                Interfaces.template_registry.get_last_broadcast_args()

        # Push new job to subscribed clients
        for subscription in Pubsub.iterate_subscribers(cls.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault('authorized', {})
                    if session['authorized'].keys():
                        worker_name = session['authorized'].keys()[0]
                        difficulty = session['difficulty']
                        work_id = Interfaces.worker_manager.register_work(worker_name, job_id, difficulty)             
                        subscription.emit_single(work_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
                    else:
                        subscription.emit_single(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
            except Exception as e:
                log.exception("Error broadcasting work to client %s" % str(e))
                pass
        
        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (Interfaces.timestamper.time() - start)))
    def subscribe(self, *args):
        if self._f.client == None or not self._f.client.connected:
            yield self._f.on_connect

        if self._f.client == None or not self._f.client.connected:
            raise UpstreamServiceException("Upstream not connected")

        if self.extranonce1 == None:
            # This should never happen, because _f.on_connect is fired *after*
            # connection receive mining.subscribe response
            raise UpstreamServiceException("Not subscribed on upstream yet")

        (tail, extranonce2_size) = self._get_unused_tail()

        session = self.connection_ref().get_session()
        session['tail'] = tail

        # Remove extranonce from registry when client disconnect
        self.connection_ref().on_disconnect.addCallback(self._drop_tail, tail)

        subs1 = Pubsub.subscribe(self.connection_ref(),
                                 DifficultySubscription())[0]
        subs2 = Pubsub.subscribe(self.connection_ref(),
                                 MiningSubscription())[0]
        defer.returnValue(((subs1, subs2), ) +
                          (self.extranonce1 + tail, extranonce2_size))
Пример #4
0
    def subscribe(self, *args):
        f = self._get_stratum_proxy().f
        job = self._get_stratum_proxy().jobreg

        if f.client is None or not f.client.connected:
            yield f.on_connect

        conn = self.connection_ref()

        if f.client is None or not f.client.connected or not conn:
            raise UpstreamServiceException("Upstream not connected")

        if job.extranonce1 is None:
            # This should never happen, because _f.on_connect is fired *after*
            # connection receive mining.subscribe response
            raise UpstreamServiceException("Not subscribed on upstream yet")

        (tail, extranonce2_size) = job._get_unused_tail()
        session = self.connection_ref().get_session()
        session['tail'] = tail
        # Remove extranonce from registry when client disconnect
        conn.on_disconnect.addCallback(job._drop_tail, tail)
        subs1 = Pubsub.subscribe(conn, DifficultySubscription())[0]
        subs2 = Pubsub.subscribe(conn, MiningSubscription())[0]
        log.info("Sending subscription to worker: %s/%s" %
                 (job.extranonce1 + tail, extranonce2_size))
        defer.returnValue(((subs1, subs2), ) +
                          (job.extranonce1 + tail, extranonce2_size))
    def subscribe(self, *args):
        f = self._get_stratum_proxy().f
        job = self._get_stratum_proxy().jobreg

        if f.client is None or not f.client.connected:
            yield f.on_connect

        conn = self.connection_ref()

        if f.client is None or not f.client.connected or not conn:
            raise UpstreamServiceException("Upstream not connected")

        if job.extranonce1 is None:
            # This should never happen, because _f.on_connect is fired *after*
            # connection receive mining.subscribe response
            raise UpstreamServiceException("Not subscribed on upstream yet")

        (tail, extranonce2_size) = job._get_unused_tail()
        session = self.connection_ref().get_session()
        session['tail'] = tail
        # Remove extranonce from registry when client disconnect
        conn.on_disconnect.addCallback(job._drop_tail, tail)
        subs1 = Pubsub.subscribe(conn, DifficultySubscription())[0]
        subs2 = Pubsub.subscribe(conn, MiningSubscription())[0]
        log.info(
            "Sending subscription to worker: %s/%s" %
            (job.extranonce1 + tail, extranonce2_size))
        defer.returnValue(
            ((subs1, subs2),) + (job.extranonce1 + tail, extranonce2_size))
Пример #6
0
    def subscribe(self, *args):
        connection = self.connection_ref()
        session = connection.get_session()

        if session.get('extranonce1'):
            # Already subscribed

            subs1 = Pubsub.get_subscription(connection, DifficultySubscription.event)
            subs2 = Pubsub.get_subscription(connection, MiningSubscription.event)

            extranonce1_hex = binascii.hexlify(session['extranonce1'])
            extranonce2_size = Interfaces.template_registry.extranonce2_size

            log.warning('Already subscribed')
            return (((subs1.event, subs1.get_key()), (subs2.event, subs2.get_key())),) + \
                   (extranonce1_hex, extranonce2_size)

        extranonce1 = Interfaces.template_registry.get_new_extranonce1()
        extranonce2_size = Interfaces.template_registry.extranonce2_size
        extranonce1_hex = binascii.hexlify(extranonce1)

        session['extranonce1'] = extranonce1
        session['subscribed_at'] = posix_time()
        # Don't accept job_id if job_id < min_job_id
        session['min_job_id'] = 0
        session['client_sw'] = self._get_client_sw(*args)

        subs1 = Pubsub.subscribe(connection, DifficultySubscription())[0]
        subs2 = Pubsub.subscribe(connection, MiningSubscription())[0]

        Interfaces.reporter.new_subscription(session)

        return ((subs1, subs2),) + (extranonce1_hex, extranonce2_size)
Пример #7
0
 def print_subs(cls):
     c = Pubsub.get_subscription_count(cls.event)
     log.info(c)
     for subs in Pubsub.iterate_subscribers(cls.event):
         s = Pubsub.get_subscription(subs.connection_ref(),
                                     cls.event,
                                     key=None)
         log.info(s)
 def print_subs(cls):
     c = Pubsub.get_subscription_count(cls.event)
     log.info(c)
     for subs in Pubsub.iterate_subscribers(cls.event):
         s = Pubsub.get_subscription(
             subs.connection_ref(),
             cls.event,
             key=None)
         log.info(s)
Пример #9
0
    def request(self, *args):
        if not (self.authorize(args[0], args[1])):
            log.info("Failed worker authorization: IP %s" % str(ip))
            raise SubmitException("Failed worker authorization")

        session = self.connection_ref().get_session()
        extranonce1_bin = session.get('extranonce1', None)

        if not extranonce1_bin:
            log.info("Connection is not subscribed for mining: IP %s" %
                     str(ip))
            raise SubmitException("Connection is not subscribed for mining")

        extranonce2 = struct.pack('>L', 0)

        (job_id, prevhash, version, nbits, ntime,
         _) = Interfaces.template_registry.get_last_broadcast_args()

        coinbase_bin = Interfaces.template_registry.last_block.serialize_coinbase(
            extranonce1_bin, extranonce2)
        coinbase_hash = util.doublesha(coinbase_bin)
        merkle_root_bin = Interfaces.template_registry.last_block.merkletree.withFirst(
            coinbase_hash)
        merkle_root = binascii.hexlify(merkle_root_bin)

        work_id = Interfaces.worker_manager.register_work(
            session['extranonce1'], merkle_root, session['difficulty'], job_id,
            session['basediff'])
        job = {}
        job['data'] = version + prevhash + merkle_root + ntime + nbits
        job['difficulty'] = session['difficulty']

        return Pubsub.subscribe(self.connection_ref(), MiningSubscription(),
                                job)
Пример #10
0
    def _on_worker_refresh(self, facts):
        '''
        Callback passed to WorkerDB's refresh method for being
        notified about refreshed workers. We update the memory worker
        data appropriately.

        See WorkerDB.refresh_from_source for details about passed
        'facts' dictionary.
        '''
        worker_name = facts['worker_name']

        # The worker is not in memory, there is nothing to be updated
        worker = self.workers.get(worker_name)
        if not worker:
            return

        # We should update the id and password unconditionally
        worker['worker_id'] = facts['worker_id']

        # Suggested difficulty has been changed ..
        if worker['difficulty_suggested'] != facts['difficulty_suggested']:
            # Assign the new suggested difficulty
            worker['difficulty_suggested'] = facts['difficulty_suggested']
            # .. so let's poke DifficultySubscription and let it
            # recalculate difficulties
            for conn in worker['connections'].keys():
                diff_sub = Pubsub.get_subscription(
                    conn, DifficultySubscription.event)
                diff_sub.recalculate_difficulty(worker_name)
Пример #11
0
    def configure_downstream(cls, connection_ref, values):
        """Version rolling configuration for downstream miners

        :param connection_ref:
        :param values:
        :return:
        :todo consider whether the result should indicate version rolling
        disabled in case there is no intersection between the upstream mask
        and the downstream requested mask
        """
        result = super(VersionRollingExtension,
                       cls).configure_downstream(connection_ref, values)

        try:
            downstream_proposed_mask = cls._get_mask_from_values(values)
            # Only when subscription is enabled compose a valid mask
            if VersionMaskSubscription.enabled:
                sub = VersionMaskSubscription(downstream_proposed_mask)
                result = {
                    cls.namespace: True,
                    cls.namespace + '.mask': '%x' % sub.get_effective_mask()
                }
                _ = Pubsub.subscribe(connection_ref(), sub)
        except Exception as e:
            log.error("Version mask not calculated, error: '%s'" % e)

        return result
Пример #12
0
    def _on_worker_refresh(self, facts):
        '''
        Callback passed to WorkerDB's refresh method for being
        notified about refreshed workers. We update the memory worker
        data appropriately.

        See WorkerDB.refresh_from_source for details about passed
        'facts' dictionary.
        '''
        worker_name = facts['worker_name']

        # The worker is not in memory, there is nothing to be updated
        worker = self.workers.get(worker_name)
        if not worker:
            return

        # We should update the id and password unconditionally
        worker['worker_id'] = facts['worker_id']

        # Suggested difficulty has been changed ..
        if worker['difficulty_suggested'] != facts['difficulty_suggested']:
            # Assign the new suggested difficulty
            worker['difficulty_suggested'] = facts['difficulty_suggested']
            # .. so let's poke DifficultySubscription and let it
            # recalculate difficulties
            for conn in worker['connections'].keys():
                diff_sub = Pubsub.get_subscription(conn, DifficultySubscription.event)
                diff_sub.recalculate_difficulty(worker_name)
Пример #13
0
    def login(self, params, *args):
        if self._f.client == None or not self._f.client.connected:
            yield self._f.on_connect

        if self._f.client == None or not self._f.client.connected:
            raise UpstreamServiceException("Upstream not connected")

        tail = self._get_unused_tail()
        
        session = self.connection_ref().get_session()
        session['tail'] = tail

        custom_user = self.custom_user
        if self.enable_worker_id and params.has_key("login"):
            if self.worker_id_from_ip:
                ip_login = self.connection_ref()._get_ip()
                ip_temp = ip_login.split('.')
                ip_int = int(ip_temp[0])*16777216 + int(ip_temp[1])*65536 + int(ip_temp[2])*256 + int(ip_temp[3])
                custom_user = "******" % (custom_user, ip_int)
            else:
                params_login = re.sub(r'[^\d]', '', params["login"])
                if params_login and int(params_login)>0:
                    custom_user = "******" % (custom_user, params_login)

        first_job = (yield self._f.rpc('login', {"login":custom_user, "pass":self.custom_password}))

        try:
            self.connection_ref().on_disconnect.addCallback(self._drop_tail, tail)
        except Exception:
            pass
        subs = Pubsub.subscribe(self.connection_ref(), MiningSubscription())[0]

        MiningSubscription.add_user_id(subs[2], first_job['id'])

        defer.returnValue(first_job)
Пример #14
0
    def login(self, params, *args):
        if self._f.client == None or not self._f.client.connected:
            yield self._f.on_connect

        if self._f.client == None or not self._f.client.connected:
            raise UpstreamServiceException("Upstream not connected")

        tail = self._get_unused_tail()
        
        session = self.connection_ref().get_session()
        session['tail'] = tail

        custom_user = self.custom_user
        if self.enable_worker_id and params.has_key("login"):
            if self.worker_id_from_ip:
                ip_login = self.connection_ref()._get_ip()
                ip_temp = ip_login.split('.')
                ip_int = int(ip_temp[0])*16777216 + int(ip_temp[1])*65536 + int(ip_temp[2])*256 + int(ip_temp[3])
                custom_user = "******" % (custom_user, ip_int)
            else:
                params_login = re.sub(r'[^\d]', '', params["login"])
                if params_login and int(params_login)>0:
                    custom_user = "******" % (custom_user, params_login)

        first_job = (yield self._f.rpc('login', {"login":custom_user, "pass":self.custom_password}))

        try:
            self.connection_ref().on_disconnect.addCallback(self._drop_tail, tail)
        except Exception:
            pass
        subs = Pubsub.subscribe(self.connection_ref(), MiningSubscription())[0]

        MiningSubscription.add_user_id(subs[2], first_job['id'])

        defer.returnValue(first_job)
Пример #15
0
    def subscribe(self, *args):
        conn = self.connection_ref()

        if conn is None or not conn.connected:
            log.info(
                'subscribe miner connection lost.............................%s'
                % (conn))
            raise SubscribeException("Miner connection lost")

        stp = stproxy_ng.StratumServer._get_miner_proxy(conn._get_ip())

        try:
            yield stp.connected
            log.info(
                'subscribe yield proxy connected result......................%s %s'
                % (conn, stp))
        except Exception as e:
            log.info(
                'subscribe yield proxy connected exception.................. %s %s %s'
                % (conn, stp, e))

        if not conn.connected:
            log.info(
                'subscribe miner connection lost.............................%s %s'
                % (conn, stp))
            raise SubscribeException("Miner connection lost")

        MinerConnectSubscription.emit(conn._get_ip(), id(stp.f))

        session = conn.get_session()
        session['proxy'] = stp

        (tail, extranonce2_size) = stp.job_registry._get_unused_tail()
        # Remove extranonce from registry when client disconnect
        conn.on_disconnect.addCallback(stp.job_registry._drop_tail, tail)
        session['tail'] = tail

        subs1 = Pubsub.subscribe(conn, DifficultySubscription(stp))[0]
        subs2 = Pubsub.subscribe(conn, MiningSubscription(stp))[0]

        log.info(
            "Sending subscription to worker: %s/%s connection: %s proxy: %s" %
            (stp.job_registry.extranonce1 + tail, extranonce2_size, conn, stp))

        defer.returnValue(((subs1, subs2), ) + (stp.job_registry.extranonce1 +
                                                tail, extranonce2_size))
Пример #16
0
class MiningSubscription(Subscription):
    u'''This subscription object implements
    logic for broadcasting new jobs to the clients.'''

    event = u'mining.notify'

    @classmethod
    def on_template(cls, is_new_block):
        u'''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''

        start = Interfaces.timestamper.time()
        clean_jobs = is_new_block

        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits,
         ntime, _) = Interfaces.template_registry.get_last_broadcast_args()

        # Push new job to subscribed clients
        for subscription in Pubsub.iterate_subscribers(cls.event):
            try:
                if subscription is not None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault(u'authorized', {})
                    if list(session[u'authorized'].keys()):
                        worker_name = list(session[u'authorized'].keys())[0]
                        difficulty = session[u'difficulty']
                        work_id = Interfaces.worker_manager.register_work(
                            worker_name, job_id, difficulty)
                        subscription.emit_single(
                            work_id,
                            prevhash,
                            coinb1,
                            coinb2,
                            merkle_branch,
                            version,
                            nbits,
                            ntime,
                            clean_jobs)
                    else:
                        subscription.emit_single(
                            job_id,
                            prevhash,
                            coinb1,
                            coinb2,
                            merkle_branch,
                            version,
                            nbits,
                            ntime,
                            clean_jobs)
            except Exception, e:
                log.exception(u"Error broadcasting work to client %s" % unicode(e))
                pass

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info(u"BROADCASTED to %d connections in %.03f sec" %
                 (cnt, (Interfaces.timestamper.time() - start)))
Пример #17
0
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''

        start = Interfaces.timestamper.time()
        clean_jobs = is_new_block

        (job_id, prevhash, version, nbits, ntime,
         _) = Interfaces.template_registry.get_last_broadcast_args()

        # Push new job to subscribed clients
        for subscription in Pubsub.iterate_subscribers(cls.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault('authorized', {})
                    if session['authorized'].keys():
                        worker_name = session['authorized'].keys()[0]
                        extranonce1 = session.get('extranonce1', None)
                        extranonce2 = struct.pack('>L', 0)
                        coinbase_bin = Interfaces.template_registry.last_block.serialize_coinbase(
                            extranonce1, extranonce2)
                        coinbase_hash = util.doublesha(coinbase_bin)
                        merkle_root_bin = Interfaces.template_registry.last_block.merkletree.withFirst(
                            coinbase_hash)
                        merkle_root = binascii.hexlify(merkle_root_bin)
                        job = {}
                        job['data'] = version + prevhash + merkle_root + ntime + nbits
                        job['difficulty'] = session['difficulty']
                        work_id = Interfaces.worker_manager.register_work(
                            extranonce1, merkle_root, session['difficulty'],
                            job_id, session['basediff'])
                        subscription.emit_single(job)
                    else:
                        continue

            except Exception as e:
                log.exception("Error broadcasting work to client %s" % str(e))
                pass

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" %
                 (cnt, (Interfaces.timestamper.time() - start)))
Пример #18
0
    def reconnect_all(cls, stp):
        for subs in Pubsub.iterate_subscribers(cls.event):
            conn = subs.connection_ref()

            if conn is None or conn.transport is None:
                continue

            session = conn.get_session()

            if session['proxy'] is stp:
                conn.transport.loseConnection()
Пример #19
0
    def emit_single_before_mining_notify(self, connection):
        try:
            # Get the related subscription if there is some already
            diff_subs = Pubsub.get_subscription(connection, DifficultySubscription.event)

            # Plan the emission
            diff_subs.plan_single_emission()

        except PubsubException:
            # Connection is not subscribed for mining yet
            pass
Пример #20
0
 def subscribe(self, *args):
     '''Subscribe for receiving mining jobs. This will
     return subscription details, extranonce1_hex and extranonce2_size'''
     
     extranonce1 = Interfaces.template_registry.get_new_extranonce1()
     extranonce2_size = Interfaces.template_registry.extranonce2_size
     extranonce1_hex = binascii.hexlify(extranonce1)
     
     session = self.connection_ref().get_session()
     session['extranonce1'] = extranonce1
     session['difficulty'] = settings.POOL_TARGET  # Following protocol specs, default diff is 1
     return Pubsub.subscribe(self.connection_ref(), MiningSubscription()) + (extranonce1_hex, extranonce2_size)
Пример #21
0
    def emit_single_before_mining_notify(self, connection):
        try:
            # Get the related subscription if there is some already
            diff_subs = Pubsub.get_subscription(connection,
                                                DifficultySubscription.event)

            # Plan the emission
            diff_subs.plan_single_emission()

        except PubsubException:
            # Connection is not subscribed for mining yet
            pass
Пример #22
0
 def subscribe(self, *args):
     '''Subscribe for receiving mining jobs. This will
     return subscription details, extranonce1_hex and extranonce2_size'''
     
     extranonce1 = Interfaces.template_registry.get_new_extranonce1()
     extranonce2_size = Interfaces.template_registry.extranonce2_size
     extranonce1_hex = binascii.hexlify(extranonce1)
     
     session = self.connection_ref().get_session()
     session['extranonce1'] = extranonce1
     session['difficulty'] = settings.POOL_TARGET  # Following protocol specs, default diff is 1
     return Pubsub.subscribe(self.connection_ref(), MiningSubscription()) + (extranonce1_hex, extranonce2_size)
    def subscribe(self, *args):    
        if self._f.client == None or not self._f.client.connected:
            yield self._f.on_connect
            
        if self._f.client == None or not self._f.client.connected:
            raise UpstreamServiceException("Upstream not connected")
         
        if self.extranonce1 == None:
            # This should never happen, because _f.on_connect is fired *after*
            # connection receive mining.subscribe response
            raise UpstreamServiceException("Not subscribed on upstream yet")
        
        (tail, extranonce2_size) = self._get_unused_tail()
        
        session = self.connection_ref().get_session()
        session['tail'] = tail
                
        # Remove extranonce from registry when client disconnect
        self.connection_ref().on_disconnect.addCallback(self._drop_tail, tail)

        subs1 = Pubsub.subscribe(self.connection_ref(), DifficultySubscription())[0]
        subs2 = Pubsub.subscribe(self.connection_ref(), MiningSubscription())[0]            
        defer.returnValue(((subs1, subs2),) + (self.extranonce1+tail, extranonce2_size))
Пример #24
0
 def set_difficulty(self, diff):
     if 600 <= diff <= settings.VDIFF_MAX_TARGET:
         settings.POOL_TARGET = diff
         settings.VDIFF_MIN_TARGET = diff
         for subscription in Pubsub.iterate_subscribers(self.event):
             try:
                 if subscription and subscription.connection_ref():
                     subscription.connection_ref().rpc(
                         'mining.set_difficulty', [diff],
                         is_notification=True)
             except:
                 pass
         return True
     return False
Пример #25
0
 def on_template(cls, is_new_block):
     '''This is called when TemplateRegistry registers
        new block which we have to broadcast clients.'''
     
     start = Interfaces.timestamper.time()
     
     clean_jobs = is_new_block
     (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
                     Interfaces.template_registry.get_last_broadcast_args()
     
     # Push new job to subscribed clients
     cls.emit(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
     
     cnt = Pubsub.get_subscription_count(cls.event)
     log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (Interfaces.timestamper.time() - start)))
Пример #26
0
 def on_template(cls, is_new_block):
     '''This is called when TemplateRegistry registers
        new block which we have to broadcast clients.'''
     
     start = Interfaces.timestamper.time()
     clean_jobs = is_new_block
     
     (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
         Interfaces.template_registry.get_last_broadcast_args()
     
     # Push new job to subscribed clients
     cls.emit(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
     
     cnt = Pubsub.get_subscription_count(cls.event)
     log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (Interfaces.timestamper.time() - start)))
Пример #27
0
    def subscribe(self, *args):
        '''Subscribe for receiving mining jobs. This will
        return subscription details, extranonce_hex and extranonce_size'''

        extranonce = Interfaces.template_registry.get_new_extranonce()
        extranonce_size = Interfaces.template_registry.extranonce_size
        extranonce_hex = binascii.hexlify(extranonce).decode('utf_8')

        session = self.connection_ref().get_session()
        session['extranonce'] = extranonce
        session['difficulty'] = settings.POOL_TARGET

        return Pubsub.subscribe(
            self.connection_ref(),
            MiningSubscription()) + (extranonce_hex, extranonce_size)
Пример #28
0
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''
        start = Interfaces.timestamper.time()
        clean_jobs = is_new_block
        #(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _, rsk_job) = \
        #                Interfaces.template_registry.get_last_broadcast_args()
        bc_args = Interfaces.template_registry.get_last_broadcast_args()
        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits,
         ntime, _, rsk_flag) = bc_args
        # Push new job to subscribed clients
        cls.emit(job_id, prevhash, coinb1, coinb2, merkle_branch, version,
                 nbits, ntime, clean_jobs)

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" %
                 (cnt, (Interfaces.timestamper.time() - start)))
        if rsk_flag:
            log.info(
                json.dumps({
                    "rsk": "[RSKLOG]",
                    "tag": "[RSK_BLOCK_RECEIVED_END]",
                    "uuid": util.id_generator(),
                    "start": start,
                    "elapsed": Interfaces.timestamper.time() - start,
                    "data": bc_args,
                    "clients": cnt
                }))
        else:
            log.info(
                json.dumps({
                    "rsk": "[RSKLOG]",
                    "tag": "[BTC_BLOCK_RECEIVED_END]",
                    "uuid": util.id_generator(),
                    "start": start,
                    "elapsed": Interfaces.timestamper.time() - start,
                    "data": bc_args,
                    "clients": cnt
                }))
        log.info(
            json.dumps({
                "rsk": "[RSKLOG]",
                "tag": "[WORK_SENT]",
                "uuid": util.id_generator(),
                "start": start,
                "elapsed": Interfaces.timestamper.time() - start
            }))
Пример #29
0
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''

        start = Interfaces.timestamper.time()

        clean_jobs = is_new_block
        (job_id, height, version, prevhash, prevkeystone, secondkeystone, intermediate_merkles, time, difficulty, clean_jobs) = \
                        Interfaces.template_registry.get_last_broadcast_args()

        # Push new job to subscribed clients
        cls.emit(job_id, height, version, prevhash, prevkeystone,
                 secondkeystone, intermediate_merkles, time, difficulty,
                 clean_jobs)

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" %
                 (cnt, (Interfaces.timestamper.time() - start)))
Пример #30
0
    def get_server_stats(self):
        serialized = ""
        for subscription in Pubsub.iterate_subscribers(self.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault("authorized", {})
                    if session["authorized"].keys():
                        worker_name = session["authorized"].keys()[0]
                        difficulty = session["difficulty"]
                        ip = subscription.connection_ref()._get_ip()
                        serialized += json.dumps({"worker_name": worker_name, "ip": ip, "difficulty": difficulty})
                    else:
                        pass
            except Exception as e:
                log.exception("Error getting subscriptions %s" % str(e))
                pass

        log.debug("Server stats request: %s" % serialized)
        return "%s" % serialized
Пример #31
0
    def get_server_stats(self):
        serialized = '' 
        for subscription in Pubsub.iterate_subscribers(self.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault('authorized', {})
                    if session['authorized'].keys():
                        worker_name = session['authorized'].keys()[0]
                        difficulty = session['difficulty']
                        ip = subscription.connection_ref()._get_ip()
                        serialized += json.dumps({'worker_name': worker_name, 'ip': ip, 'difficulty': difficulty})
                    else:
                        pass
            except Exception as e:
                log.exception('Error getting subscriptions %s' % str(e))
                pass

        log.debug('Server stats request: %s' % serialized)
        return '%s' % serialized
Пример #32
0
    def subscribe(self, *args):
        '''Subscribe for receiving mining jobs. This will
        return subscription details, extranonce1_hex and extranonce2_size'''

        extranonce1 = Interfaces.template_registry.get_new_extranonce1()
        extranonce2_size = Interfaces.template_registry.extranonce2_size
        extranonce1_hex = binascii.hexlify(extranonce1)

        session = self.connection_ref().get_session()
        session['extranonce1'] = extranonce1
        if settings.RSK_DEV_MODE and hasattr(settings,
                                             'RSK_STRATUM_DIFFICULTY'):
            session['difficulty'] = settings.RSK_STRATUM_DIFFICULTY
        else:
            session[
                'difficulty'] = 1  # Following protocol specs, default diff is 1

        return Pubsub.subscribe(
            self.connection_ref(),
            MiningSubscription()) + (extranonce1_hex, extranonce2_size)
Пример #33
0
    def get_server_stats(self):
        serialized = '' 
        for subscription in Pubsub.iterate_subscribers(self.event):
            try:
                if subscription != None:
                    session = subscription.connection_ref().get_session()
                    session.setdefault('authorized', {})
                    if session['authorized'].keys():
                        worker_name = session['authorized'].keys()[0]
                        difficulty = session['difficulty']
                        ip = subscription.connection_ref()._get_ip()
                        serialized += json.dumps({'worker_name': worker_name, 'ip': ip, 'difficulty': difficulty})
                    else:
                        pass
            except Exception as e:
                log.exception("Error getting subscriptions %s" % str(e))
                pass

        log.debug("Server stats request: %s" % serialized)
        return '%s' % serialized
Пример #34
0
 def get_server_stats(self):
     serialized = u''
     for subscription in Pubsub.iterate_subscribers(self.event):
         try:
             if subscription is not None:
                 session = subscription.connection_ref().get_session()
                 session.setdefault(u'authorized', {})
                 if list(session[u'authorized'].keys()):
                     worker_name = list(session[u'authorized'].keys())[0]
                     difficulty = session[u'difficulty']
                     ip = subscription.connection_ref()._get_ip()
                     serialized += json.dumps({
                         u'worker_name': worker_name,
                         u'ip': ip,
                         u'difficulty': difficulty
                     })
                 else:
                     pass
         except Exception, e:
             log.exception(u"Error getting subscriptions %s" % unicode(e))
             pass
Пример #35
0
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''

        start = posix_time()

        clean_jobs = is_new_block
        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
                        Interfaces.template_registry.get_last_template_broadcast_args()

        if not is_new_block:
            try:
                cls.before_broadcast.callback(True)
                cls.before_broadcast = defer.Deferred()
            except:
                log.exception("before_broadcast callback failed!")

        # Push new job to subscribed clients
        cls.emit("%x"%job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" % (cnt, (posix_time() - start)))
Пример #36
0
    def on_template(cls, is_new_block):
        '''This is called when TemplateRegistry registers
           new block which we have to broadcast clients.'''

        start = posix_time()

        clean_jobs = is_new_block
        (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, _) = \
                        Interfaces.template_registry.get_last_template_broadcast_args()

        if not is_new_block:
            try:
                cls.before_broadcast.callback(True)
                cls.before_broadcast = defer.Deferred()
            except:
                log.exception("before_broadcast callback failed!")

        # Push new job to subscribed clients
        cls.emit("%x" % job_id, prevhash, coinb1, coinb2, merkle_branch,
                 version, nbits, ntime, clean_jobs)

        cnt = Pubsub.get_subscription_count(cls.event)
        log.info("BROADCASTED to %d connections in %.03f sec" %
                 (cnt, (posix_time() - start)))
 def disconnect_all(cls):
     for subs in Pubsub.iterate_subscribers(cls.event):
         subs.connection_ref().transport.loseConnection()
Пример #38
0
 def get_num_connections(cls):
     return Pubsub.get_subscription_count(cls.event)
 def disconnect_all(cls):
     for subs in Pubsub.iterate_subscribers(cls.event):
         if subs.connection_ref().transport != None:
             subs.connection_ref().transport.loseConnection()
 def get_num_connections(cls):
     return Pubsub.get_subscription_count(cls.event)
 def reconnect_all(cls):
     for subs in Pubsub.iterate_subscribers(cls.event):
         if subs.connection_ref().transport is not None:
             subs.connection_ref().transport.loseConnection()