Get the range of blocks for which we are reprocessing
    transactions on recovery.
    Returns (start_block, end_block) tu↵ple, which will be
    (None, None) if we're not recovering
353689
def get_recovery_range(working_dir):
    
    recovery_range_path = os.path.join(working_dir, '.recovery')
    if not os.path.exists(recovery_range_path):
        return (None, None)

    with open(recovery_range_path) as f:
        data = f.read()

    lines = filter(lambda l: len(l) > 0, map(lambda l2: l2.strip(), data.split()))
    assert len(lines) == 2, 'Invalid .recovery file'
    try:
        start_block = int(lines[0])
        end_block = int(lines[1])
    except:
        raise ValueError('Failed to parse {}'.format(recovery_range_path))

    return (start_block, end_block)
819091
def _find_block(starts, ends, cur_block, rec_num):   # @NoSelf
        '''
        
        '''
        total = len(starts)
        if (cur_block == -1):
            cur_block = 0
        for x in range(cur_block, total):
            if (starts[x] <= rec_num and ends[x] >= rec_num):
                return x, x
            if (starts[x] > rec_num):
                break
        return -1, x-1
144442
def replay_block(self, block_to_replay, limit=5):
        

        if block_to_replay == 'latest':
            if self.verbose:
                print("Getting latest %s block header" % source.upper())
            block = get_block(self.source, latest=True, verbose=self.verbose)
            if self.verbose:
                print("Latest %s block is #%s" % (self.source.upper(), block['block_number']))
        else:
            blocknum = block_to_replay if type(block_to_replay) == int else block_to_replay['block_number']
            if blocknum < self.parent_fork_block or blocknum < self.child_fork_block:
                raise Exception("Can't replay blocks mined before the fork")

        if type(block_to_replay) is not dict:
            if self.verbose:
                print("Getting %s block header #%s" % (self.source.upper(), block_to_replay))
            block = get_block(self.source, block_number=int(block_to_replay), verbose=self.verbose)
        else:
            block = block_to_replay

        if self.verbose:
            print("Using %s for pushing to %s" % (self.pusher.name, self.destination.upper()))
            print("Using %s for getting %s transactions" % (self.tx_fetcher.name, self.source.upper()))
            print("Finished getting block header,", len(block['txids']), "transactions in block, will replay", (limit or "all of them"))

        results = []
        enforced_limit = (limit or len(block['txids']))

        for i, txid in enumerate(block['txids'][:enforced_limit]):
            print("outside", txid)
            self._replay_tx(txid, i)
285634
def getoneblock(astr, start, end):
    """"""
    alist = astr.split(start)
    astr = alist[-1]
    alist = astr.split(end)
    astr = alist[0]
    return astr
602159
def op_range(self, start, end):
        
        while start < end:
            yield start
            start += instruction_size(self.code[start], self.opc)
812542
private Range<RowKeyWrapper> rowRangeToRange(RowRange btRange) {
    final BoundType startBound;
    final ByteString startKey;

    switch (btRange.getStartKeyCase()) {
      case START_KEY_OPEN:
        startBound = BoundType.OPEN;
        startKey = btRange.getStartKeyOpen();
        break;
      case START_KEY_CLOSED:
        startBound = BoundType.CLOSED;
        startKey = btRange.getStartKeyClosed();
        break;
      case STARTKEY_NOT_SET:
        startBound = BoundType.CLOSED;
        startKey = ByteString.EMPTY;
        break;
      default:
        throw new IllegalArgumentException("Unexpected start key case: " +
            btRange.getStartKeyCase());
    }

    final BoundType endBound;
    final ByteString endKey;
    switch (btRange.getEndKeyCase()) {
      case END_KEY_OPEN:
        endBound = BoundType.OPEN;
        endKey = btRange.getEndKeyOpen();
        break;
      case END_KEY_CLOSED:
        endBound = BoundType.CLOSED;
        endKey = btRange.getEndKeyClosed();
        break;
      case ENDKEY_NOT_SET:
        endBound = BoundType.OPEN;
        endKey = ByteString.EMPTY;
        break;
      default:
        throw new IllegalArgumentException("Unexpected end key case: " + btRange.getEndKeyCase());
    }

    return boundedRange(startBound, startKey, endBound, endKey);
  }
491519
def get_last_block(working_dir):
    

    # make this usable even if we haven't explicitly configured virtualchain 
    impl = sys.modules[__name__]
    return BlockstackDB.get_lastblock(impl, working_dir)
32236
def updateIfNeeded(self):
        """"""
        headBlock = self.db.reader._get_head_block()
        if headBlock is not None:
            # avoid restarting search if head block is same & we already initialized
            # this is required for fastSync handling
            if self.lastBlock is not None:
                self.lastBlock = max(self.lastBlock, headBlock.number)
            else:
                self.lastBlock = headBlock.number
        lastProcessed = self.db.reader._get_last_indexed_number()
        if lastProcessed is not None:
            self.lastProcessedBlock = utils.big_endian_to_int(lastProcessed)

        # in fast sync head block is at 0 (e.g. in fastSync), we can't use it to determine length
        if self.lastBlock is not None and self.lastBlock == 0:
            self.lastBlock = 2e9

        if self.lastBlock is None or (
            self.lastProcessedBlock is not None
            and self.lastBlock <= self.lastProcessedBlock
        ):
            return

        blockNum = 0
        if self.lastProcessedBlock is not None:
            blockNum = self.lastProcessedBlock + 1
            print(
                "Updating hash-to-address index from block "
                + str(self.lastProcessedBlock)
            )
        else:
            print("Starting hash-to-address index")

        count = 0
        processed = 0

        while blockNum <= self.lastBlock:
            # leveldb cannot be accessed on multiple processes (not even readonly)
            # multithread version performs significantly worse than serial
            try:
                results = self._process(blockNum)
            except:
                break

            # store new mappings
            self.db.writer._start_writing()
            count += len(results)
            for addr in results:
                self.db.writer._store_account_address(addr)

            self.db.writer._commit_batch()

            processed += BATCH_SIZE
            blockNum = min(blockNum + BATCH_SIZE, self.lastBlock + 1)

            cost_time = time.time() - ethereum.start_time
            print(
                "%d blocks processed (in %d seconds), %d unique addresses found, next block: %d"
                % (processed, cost_time, count, min(self.lastBlock, blockNum))
            )

            self.lastProcessedBlock = blockNum - 1
            self.db.writer._set_last_indexed_number(self.lastProcessedBlock)

        print("Finished indexing")
        self.lastBlock = self.lastProcessedBlock
1065983
def getBlock(block, _ignore_alloc = false)
      raise "Ext3::Superblock.getBlock: block is nil" if block.nil?

      unless @block_cache.key?(block)
        if block == 0
          @block_cache[block] = MemoryBuffer.create(@blockSize)
        else
          # raise "Block #{block} is not allocated" if (not gde.blockAllocBmp[offset] and not ignore_alloc)

          address = blockToAddress(block)  # This function will read the block into our cache

          @stream.seek(address)
          @block_cache[block] = @stream.read(@blockSize)
        end
      end
      @block_cache[block]
    end
740392
def next(self):
        

        if self._stopped_iteration:
            raise StopIteration()

        # we do this because if get blocks, we can't catch a KeyboardInterrupt
        # so the slight timeout allows for that.
        while True:
            try:
                chunk = self.process._pipe_queue.get(True, 0.001)
            except Empty:
                if self.call_args["iter_noblock"]:
                    return errno.EWOULDBLOCK
            else:
                if chunk is None:
                    self.wait()
                    self._stopped_iteration = True
                    raise StopIteration()
                try:
                    return chunk.decode(self.call_args["encoding"],
                        self.call_args["decode_errors"])
                except UnicodeDecodeError:
                    return chunk
118993
def range_end(self):
        '''
        '''
        count = self.count
        range_end = self.range_start + self.limit - 1
        if count < range_end:
            range_end = count
        return range_end
572549
def _elsed_block_range(self, lineno, orelse, last=None):
        
        if lineno == self.fromlineno:
            return lineno, lineno
        if orelse:
            if lineno >= orelse[0].fromlineno:
                return lineno, orelse[-1].tolineno
            return lineno, orelse[0].fromlineno - 1
        return lineno, last or self.tolineno
768971
def get_epoch_number( block_height ):
    
    global EPOCHS

    if block_height <= EPOCHS[0]['end_block']:
        return 0

    for i in xrange(1, len(EPOCHS)):
        if EPOCHS[i-1]['end_block'] < block_height and (block_height <= EPOCHS[i]['end_block'] or EPOCHS[i]['end_block'] == EPOCH_NOW):
            return i

    # should never happen 
    log.error("FATAL: No epoch for %s" % block_height)
    os.abort()
404909
def get_block_count(self, is_full: bool = False) -> int or dict:
        
        payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK_COUNT)
        response = self.__post(self.__url, payload)
        if is_full:
            return response
        return response['result']
240608
def source_range(start, end, nr_var_dict):
    

    return OrderedDict((k, e-s)
        for k, (s, e)
        in source_range_tuple(start, end, nr_var_dict).iteritems())
717340
def get_block_info(self):
        
        if not self.finished:
            raise Exception("Not finished downloading")

        ret = []
        for (block_hash, block_data) in self.block_info.items():
            ret.append( (block_data['height'], block_data['txns']) )

        return ret
278027
def get_consensus_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None, db_con=None, completeness_check=True):
        
        if (start_block_height is None and end_block_height is not None) or (start_block_height is not None and end_block_height is None):
            raise ValueError("Need either both or neither start/end block height")

        we_opened = False
        if db_con is not None:
            con = db_con

        else:
            assert impl and working_dir, 'Need impl and working_dir if db_con is not given'
            con = cls.db_open(impl, working_dir)
            we_opened = True

        range_query = ''
        range_args = ()

        if start_block_height and end_block_height:
            range_query += ' WHERE block_id >= ? AND block_id < ?'
            range_args += (start_block_height,end_block_height)

        query = 'SELECT block_id,consensus_hash FROM snapshots' + range_query + ';'
        args = range_args

        rows = cls.db_query_execute(con, query, range_args, verbose=False)
        ret = {}
        block_min = None
        block_max = None

        for r in rows:
            block_id = int(r['block_id'])
            ret[block_id] = r['consensus_hash']

            if block_min is None or block_min > block_id:
                block_min = block_id

            if block_max is None or block_max < block_id:
                block_max = block_id

        if we_opened:
            con.close()
       
        if completeness_check:
            # sanity check
            for i in range(block_min,block_max+1):
                ch = ret.get(i, None)

                assert ch is not None, 'Missing consensus hash for {}'.format(i)
                assert isinstance(ret[i], (str,unicode)), 'consensus hash for {} is type {}'.format(i, type(ret[i]))

        return ret