Look up the sequence of zone file records by name, optionally up to a specific zonefile index
    Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
423097
def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None):
    
    ret = []
    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = 'SELECT * FROM zonefiles WHERE name = ? ORDER BY inv_index'
        args = (name,)

        if max_index:
            sql += ' AND inv_index <= ?'
            args += (max_index,)

        sql += ';'

        cur = dbcon.cursor()
        res = atlasdb_query_execute(cur, sql, args)

        for zfinfo in res:
            row = {}
            row.update(zfinfo)
            ret.append(row)

    return ret
98647
def is_name_zonefile_hash(name, zonefile_hash, hostport=None, proxy=None):
    
    assert hostport or proxy, 'Need hostport or proxy'
    if proxy is None:
        proxy = connect_hostport(hostport)

    zonefile_check_schema = {
        'type': 'object',
        'properties': {
            'result': {
                'type': 'boolean'
            }
        },
        'required': [ 'result' ]
    }

    schema = json_response_schema(zonefile_check_schema)
    resp = {}
    try:
        resp = proxy.is_name_zonefile_hash(name, zonefile_hash)
        resp = json_validate(schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    return {'result': resp['result']}
579822
function blockChecksums(fs, path, size, callback) {
  var cache = {};

  fs.readFile(path, function (err, data) {
    if (!err) {
      // cache file
      cache[path] = data;
    } else if (err && err.code === 'ENOENT') {
      cache[path] = [];
    } else {
      return callback(err);
    }

    var length = cache[path].length;
    var incr = size;
    var start = 0;
    var end = incr > length ? length : incr;
    var blockIndex = 0;
    var result = [];
    var chunk;
    var weak;
    var strong;

    while (start < length) {
      chunk  = cache[path].slice(start, end);
      weak   = calcWeak32(chunk).sum;
      strong = md5sum(chunk);

      result.push({
        index: blockIndex,
        weak: weak,
        strong: strong
      });
      // update slice indices
      start += incr;
      end = (end + incr) > length ? length : end + incr;
      // update block index
      blockIndex++;
    }

    callback(null, result);
  });
}
1314435
def GET_blockchain_name_record( self, path_info, blockchain_name, name ):
        
        if not check_name(name) and not check_subdomain(name):
            return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)

        if blockchain_name != 'bitcoin':
            # not supported
            self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
            return

        blockstackd_url = get_blockstackd_url()
        name_rec = blockstackd_client.get_name_record(name, include_history=False, hostport=blockstackd_url)
        if json_is_error(name_rec):
            # error
            status_code = name_rec.get('http_status', 502)
            return self._reply_json({'error': name_rec['error']}, status_code=status_code)

        return self._reply_json(name_rec)
909242
def decode_name_zonefile(name, zonefile_txt):
    

    user_zonefile = None
    try:
        # by default, it's a zonefile-formatted text file
        user_zonefile_defaultdict = blockstack_zones.parse_zone_file(zonefile_txt)

        # force dict
        user_zonefile = dict(user_zonefile_defaultdict)

    except (IndexError, ValueError, blockstack_zones.InvalidLineException):
        # might be legacy profile
        log.debug('WARN: failed to parse user zonefile; trying to import as legacy')
        try:
            user_zonefile = json.loads(zonefile_txt)
            if not isinstance(user_zonefile, dict):
                log.debug('Not a legacy user zonefile')
                return None

        except Exception as e:
            log.error('Failed to parse non-standard zonefile')
            return None

    except Exception as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        log.error('Failed to parse zonefile')
        return None

    if user_zonefile is None:
        return None 

    return user_zonefile
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
1213448
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None):
        
        records = []
        rrsets = zone.iterate_rdatasets() if zone else []
        for rname, rdataset in rrsets:
            rtype = dns.rdatatype.to_text(rdataset.rdtype)
            if ((not rdtype or rdtype == rtype)
                    and (not name or name == rname.to_text())):
                for rdata in rdataset:
                    rdata = rdata.to_text()
                    if not content or self._convert_content(rtype, content) == rdata:
                        raw_rdata = self._clean_TXT_record({'type': rtype,
                                                            'content': rdata})['content']
                        data = {
                            'type': rtype,
                            'name': rname.to_text(True),
                            'ttl': int(rdataset.ttl),
                            'content': raw_rdata,
                            'id': Provider._create_identifier(rtype, rname.to_text(), raw_rdata)
                        }
                        records.append(data)
        return records
283240
def atlasdb_get_zonefile( zonefile_hash, con=None, path=None ):
    
    ret = None

    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = "SELECT * FROM zonefiles WHERE zonefile_hash = ? ORDER BY inv_index;"
        args = (zonefile_hash,)

        cur = dbcon.cursor()
        res = atlasdb_query_execute( cur, sql, args )

        ret = {
            'zonefile_hash': zonefile_hash,
            'indexes': [],
            'block_heights': [],
            'present': False,
            'tried_storage': False
        }

        for zfinfo in res:
            ret['indexes'].append( zfinfo['inv_index'] )
            ret['block_heights'].append( zfinfo['block_height'] )
            ret['present'] = ret['present'] or zfinfo['present']
            ret['tried_storage'] = ret['tried_storage'] or zfinfo['tried_storage']

    return ret
95408
def get_ops_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None):
        
        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")

        con = cls.db_open(impl, working_dir)
        range_query = ' WHERE ops_hash IS NOT NULL'
        range_args = ()

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

        query = 'SELECT block_id,ops_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:
            ret[r['block_id']] = r['ops_hash']

            if block_min is None or block_min > r['block_id']:
                block_min = r['block_id']

            if block_max is None or block_max < r['block_id']:
                block_max = r['block_id']

        con.close()
        
        # sanity check
        if block_min is not None and block_max is not None:
            for i in range(block_min,block_max+1):
                oh = ret.get(i, None)

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

        return ret
1217226
def get_block_hash(block_height, coin_symbol='btc', api_key=None):
    '''
    
    '''
    return get_block_overview(block_representation=block_height,
            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash']
881897
def get_records(self, name):
        
        if name in self._cache:
            return self._cache[name].values()
        else:
            return []
742279
def GetLoadingOrder(self):
    """"""
    result = {}
    for filename, mapping in self._file_mapping.iteritems():
      loading_order = mapping['loading_order']
      if loading_order is not None:
        result[loading_order] = filename
    return list(result[key] for key in sorted(result))
227471
def _list_records(self, rtype=None, name=None, content=None):
        
        with self._session(self.domain, self.domain_id) as ddata:
            name = self._fqdn_name(name) if name else None
            return self._list_records_in_zone(ddata['zone']['data'], rtype, name, content)
334644
def _list_records(self, rtype=None, name=None, content=None):
        """"""
        records = [
            {
                'id': record['id'],
                'type': record['type'],
                'name': self._full_name(record['hostname']),
                'content': record['destination'],
                'priority': record['priority'],
                'ttl': self.zone_ttl,
            }
            for record in self._raw_records(None, rtype, name, content)
        ]
        LOGGER.debug('list_records: %s', records)
        return records
1201899
def atlasdb_zonefile_inv_list( bit_offset, bit_length, con=None, path=None ):
    
    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = "SELECT * FROM zonefiles LIMIT ? OFFSET ?;"
        args = (bit_length, bit_offset)

        cur = dbcon.cursor()
        res = atlasdb_query_execute( cur, sql, args )

        ret = []
        for row in res:
            tmp = {}
            tmp.update(row)
            ret.append(tmp)

    return ret
1126345
def _list_records(self, rtype=None, name=None, content=None):
        
        opts = {'domain': self._domain}
        if rtype is not None:
            opts['type'] = rtype.upper()
        if name is not None:
            opts['name'] = self._full_name(name)
        if content is not None:
            opts['content'] = content
        opts.update(self._auth)

        response = self._api.nameserver.info(opts)
        self._validate_response(
            response=response, message='Failed to get records')

        records = []
        if 'record' in response['resData']:
            for record in response['resData']['record']:
                processed_record = {
                    'type': record['type'],
                    'name': record['name'],
                    'ttl': record['ttl'],
                    'content': record['content'],
                    'id': record['id']
                }
                records.append(processed_record)

        return records
1075034
def get_valid_consensus_hashes( self, block_id ):
        
        first_block_to_check = block_id - self.impl.get_valid_transaction_window()

        query = 'SELECT consensus_hash FROM snapshots WHERE block_id >= ? AND block_id <= ?;'
        args = (first_block_to_check,block_id)

        valid_consensus_hashes = []
        
        con = self.db_open(self.impl, self.working_dir)
        rows = self.db_query_execute(con, query, args, verbose=False)

        for r in rows:
            assert r['consensus_hash'] is not None
            assert isinstance(r['consensus_hash'], (str,unicode))

            valid_consensus_hashes.append(str(r['consensus_hash']))

        con.close()
        return valid_consensus_hashes