def fix_previous_block(block, chain): logger.info('fixing previous block for {}'.format(block)) prev_hash = get_block_hash(block.height - 1, schema_name=chain) if not prev_hash: return try: prev_block = Block.objects.get(hash=prev_hash) except Block.DoesNotExist: prev_block = Block(hash=prev_hash) try: prev_height_block = Block.objects.get(height=block.height - 1) except Block.DoesNotExist: prev_height_block = prev_block if prev_block != prev_height_block: # the block with the previous height doesn't match the hash from this block # likely to be an orphan so remove it prev_height_block.delete() block.previous_block = prev_block block.save() prev_block.height = block.height - 1 prev_block.next_block = block prev_block.save()