def historical_update(blockheight): """ Very long running task. Fills out the network difficulty values for all blocks before the site was running. """ def add_one_minute_diff(diff, time): try: m = OneMinuteType(typ='netdiff', value=diff, time=time) db.session.add(m) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() slc = OneMinuteType.query.with_lockmode('update').filter_by( time=time, typ='netdiff').one() # just average the diff of two blocks that occured in the same second.. slc.value = (diff + slc.value) / 2 db.session.commit() for ht in xrange(blockheight, 0, -1): hsh = coinserv.getblockhash(ht) info = coinserv.getblock(hsh) add_one_minute_diff(info['difficulty'] * 1000, datetime.datetime.utcfromtimestamp(info['time'])) current_app.logger.info("Processed block height {}".format(ht)) db.session.commit() OneMinuteType.compress() db.session.commit() FiveMinuteType.compress() db.session.commit()
def update_block_state(self): """ Loops through all immature and non-orphaned blocks. First checks to see if blocks are orphaned, then it checks to see if they are now matured. """ mature_diff = current_app.config['block_mature_confirms'] try: # Select all immature & non-orphaned blocks immature = (Block.query.filter_by(mature=False, orphan=False)) blockheight = coinserv.getblockcount() for block in immature: logger.info("Checking block height: {}".format(block.height)) # Check to see if the block hash exists in the block chain try: output = coinserv.getblock(block.hash) logger.debug("Confirms: {}; Height diff: {}" .format(output['confirmations'], blockheight - block.height)) except CoinRPCException: logger.info("Block {}:{} not in coin database, assume orphan!" .format(block.height, block.hash)) block.orphan = True else: if output['confirmations'] > mature_diff: logger.info("Block {}:{} meets {} confirms, mark mature" .format(block.height, block.hash, mature_diff)) block.mature = True elif (blockheight - block.height) > mature_diff and output['confirmations'] < mature_diff: logger.info("Block {}:{} {} height ago, but not enough confirms. Marking orphan." .format(block.height, block.hash, mature_diff)) block.orphan = True db.session.commit() except Exception as exc: logger.error("Unhandled exception in update block status", exc_info=True) db.session.rollback() raise self.retry(exc=exc)