INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
row factory * convert known booleans to booleans
def atlasdb_row_factory( cursor, row ): """ row factory * convert known booleans to booleans """ d = {} for idx, col in enumerate( cursor.description ): if col[0] in ["present", "tried_storage"]: if row[idx] == 0: d[col[0]] = False elif row[idx] ==...
Turn a query into a string for printing. Useful for debugging.
def atlasdb_format_query( query, values ): """ Turn a query into a string for printing. Useful for debugging. """ return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] )
Open the atlas db. Return a connection. Return None if it doesn't exist
def atlasdb_open( path ): """ Open the atlas db. Return a connection. Return None if it doesn't exist """ if not os.path.exists(path): log.debug("Atlas DB doesn't exist at %s" % path) return None con = sqlite3.connect( path, isolation_level=None ) con.row_factory = atlas...
Add a zonefile to the database. Mark it as present or absent. Keep our in-RAM inventory vector up-to-date
def atlasdb_add_zonefile_info( name, zonefile_hash, txid, present, tried_storage, block_height, con=None, path=None ): """ Add a zonefile to the database. Mark it as present or absent. Keep our in-RAM inventory vector up-to-date """ global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK with...
Get the highest block height in the atlas db
def atlasdb_get_lastblock( con=None, path=None ): """ Get the highest block height in the atlas db """ row = None with AtlasDBOpen(con=con, path=path) as dbcon: sql = "SELECT MAX(block_height) FROM zonefiles;" args = () cur = dbcon.cursor() res = atlasdb_query_execu...
Look up all information on this zonefile. Returns {'zonefile_hash': ..., 'indexes': [...], etc} Zonefile information will be ordered by inv_index
def atlasdb_get_zonefile( zonefile_hash, con=None, path=None ): """ Look up all information on this zonefile. Returns {'zonefile_hash': ..., 'indexes': [...], etc} Zonefile information will be ordered by inv_index """ ret = None with AtlasDBOpen(con=con, path=path) as dbcon: sql = ...
Look up all zonefile hashes in a block range. Optionally filter by name. Returns [{'name': ..., 'zonefile_hash': ..., 'block_height': ..., 'txid': ..., 'inv_index': ...}]
def atlasdb_get_zonefiles_by_block( from_block, to_block, offset, count, name=None, con=None, path=None ): """ Look up all zonefile hashes in a block range. Optionally filter by name. Returns [{'name': ..., 'zonefile_hash': ..., 'block_height': ..., 'txid': ..., 'inv_index': ...}] """ ret = None ...
Look up a zonefile by txid Returns {'zonefile_hash': ..., 'name': ..., etc.} Returns None if not found
def atlasdb_get_zonefile_by_txid( txid, con=None, path=None ): """ Look up a zonefile by txid Returns {'zonefile_hash': ..., 'name': ..., etc.} Returns None if not found """ ret = None with AtlasDBOpen(con=con, path=path) as dbcon: sql = "SELECT * FROM zonefiles WHERE txid = ?;" ...
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
def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None): """ 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 block...
Get the number of missing zone files for a particular name, optionally up to a maximum zonefile index and optionally omitting particular zone files in the count. Returns an integer
def atlasdb_get_zonefiles_missing_count_by_name(name, max_index=None, indexes_exclude=[], con=None, path=None): """ Get the number of missing zone files for a particular name, optionally up to a maximum zonefile index and optionally omitting particular zone files in the count. Returns an integer """...
Find all instances of this zone file in the atlasdb. Optionally filter on block height Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order Returns None if the zone file is not in the db, or if block_hei...
def atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=None, con=None, path=None): """ Find all instances of this zone file in the atlasdb. Optionally filter on block height Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_st...
Mark a zonefile as present (i.e. we stored it). Keep our in-RAM zonefile inventory coherent. Return the previous state. Returns True if the zone file was already present Returns False if it was not
def atlasdb_set_zonefile_present( zonefile_hash, present, con=None, path=None ): """ Mark a zonefile as present (i.e. we stored it). Keep our in-RAM zonefile inventory coherent. Return the previous state. Returns True if the zone file was already present Returns False if it was not """ ...
Make a note that we tried to get the zonefile from storage
def atlasdb_set_zonefile_tried_storage( zonefile_hash, tried_storage, con=None, path=None ): """ Make a note that we tried to get the zonefile from storage """ with AtlasDBOpen(con=con, path=path) as dbcon: if tried_storage: tried_storage = 1 else: tried_storage =...
For zonefiles that we don't have, re-attempt to fetch them from storage.
def atlasdb_reset_zonefile_tried_storage( con=None, path=None ): """ For zonefiles that we don't have, re-attempt to fetch them from storage. """ with AtlasDBOpen(con=con, path=path) as dbcon: sql = "UPDATE zonefiles SET tried_storage = ? WHERE present = ?;" args = (0, 0) cur ...
Load up and cache our zonefile inventory from the database
def atlasdb_cache_zonefile_info( con=None, path=None ): """ Load up and cache our zonefile inventory from the database """ global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK inv = None with ZONEFILE_INV_LOCK: inv_len = atlasdb_zonefile_inv_length( con=con, path=path ) inv...
What bit(s) in a zonefile inventory does a zonefile hash correspond to? Return their indexes in the bit field.
def atlasdb_get_zonefile_bits( zonefile_hash, con=None, path=None ): """ What bit(s) in a zonefile inventory does a zonefile hash correspond to? Return their indexes in the bit field. """ with AtlasDBOpen(con=con, path=path) as dbcon: sql = "SELECT inv_index FROM zonefiles WHERE zonefile_ha...
Queue all zonefile hashes in the BlockstackDB to the zonefile queue NOT THREAD SAFE Returns the list of zonefile infos queued, and whether or not they are present.
def atlasdb_queue_zonefiles( con, db, start_block, zonefile_dir, recover=False, validate=True, end_block=None ): """ Queue all zonefile hashes in the BlockstackDB to the zonefile queue NOT THREAD SAFE Returns the list of zonefile infos queued, and whether or not they are present. """ # pop...
Synchronize atlas DB with name db NOT THREAD SAFE
def atlasdb_sync_zonefiles( db, start_block, zonefile_dir, atlas_state, validate=True, end_block=None, path=None, con=None ): """ Synchronize atlas DB with name db NOT THREAD SAFE """ ret = None with AtlasDBOpen(con=con, path=path) as dbcon: ret = atlasdb_queue_zonefiles( dbcon, db, sta...
Add a peer to the peer table. If the peer conflicts with another peer, ping it first, and only insert the new peer if the old peer is dead. Keep the in-RAM peer table cache-coherent as well. Return True if this peer was added to the table (or preserved) Return False if not
def atlasdb_add_peer( peer_hostport, discovery_time=None, peer_table=None, con=None, path=None, ping_on_evict=True ): """ Add a peer to the peer table. If the peer conflicts with another peer, ping it first, and only insert the new peer if the old peer is dead. Keep the in-RAM peer table cache-cohe...
Remove a peer from the peer db and (if given) peer table.
def atlasdb_remove_peer( peer_hostport, con=None, path=None, peer_table=None ): """ Remove a peer from the peer db and (if given) peer table. """ # remove from db with AtlasDBOpen(con=con, path=path) as dbcon: log.debug("Delete peer '%s'" % peer_hostport) sql = "DELETE FROM peers W...
How many peers are there in the db?
def atlasdb_num_peers( con=None, path=None ): """ How many peers are there in the db? """ with AtlasDBOpen(con=con, path=path) as dbcon: sql = "SELECT MAX(peer_index) FROM peers;" args = () cur = dbcon.cursor() res = atlasdb_query_execute( cur, sql, args ) ret ...
Get the given peer's info
def atlas_get_peer( peer_hostport, peer_table=None ): """ Get the given peer's info """ ret = None with AtlasPeerTableLocked(peer_table) as ptbl: ret = ptbl.get(peer_hostport, None) return ret
Select a peer from the db at random Return None if the table is empty
def atlasdb_get_random_peer( con=None, path=None ): """ Select a peer from the db at random Return None if the table is empty """ ret = {} with AtlasDBOpen(con=con, path=path) as dbcon: num_peers = atlasdb_num_peers( con=con, path=path ) if num_peers is None or num_peers == 0: ...
Get peers older than now - PEER_LIFETIME
def atlasdb_get_old_peers( now, con=None, path=None ): """ Get peers older than now - PEER_LIFETIME """ with AtlasDBOpen(con=con, path=path) as dbcon: if now is None: now = time.time() expire = now - atlas_peer_max_age() sql = "SELECT * FROM peers WHERE discovery_ti...
Renew a peer's discovery time
def atlasdb_renew_peer( peer_hostport, now, con=None, path=None ): """ Renew a peer's discovery time """ with AtlasDBOpen(con=con, path=path) as dbcon: if now is None: now = time.time() sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;" args = (now,...
Create a peer table from the peer DB
def atlasdb_load_peer_table( con=None, path=None ): """ Create a peer table from the peer DB """ peer_table = {} with AtlasDBOpen(con=con, path=path) as dbcon: sql = "SELECT * FROM peers;" args = () cur = dbcon.cursor() res = atlasdb_query_execute( cur, sql, ar...
Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the peer db @db should be an instance of BlockstackDB @initial_peers should be a list of URLs Return the ne...
def atlasdb_init( path, zonefile_dir, db, peer_seeds, peer_blacklist, recover=False, validate=False): """ Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the pee...
Get an inventory listing. offset and length are in bits. Return the list of zonefile information. The list may be less than length elements.
def atlasdb_zonefile_inv_list( bit_offset, bit_length, con=None, path=None ): """ Get an inventory listing. offset and length are in bits. Return the list of zonefile information. The list may be less than length elements. """ with AtlasDBOpen(con=con, path=path) as dbcon: sql = "S...
Get a summary description of the list of zonefiles we have for the given block range (a "zonefile inventory") Zonefile present/absent bits are ordered left-to-right, where the leftmost bit is the earliest zonefile in the blockchain. Offset and length are in bytes. This is slow. Use the in-RAM zo...
def atlas_make_zonefile_inventory( bit_offset, bit_length, con=None, path=None ): """ Get a summary description of the list of zonefiles we have for the given block range (a "zonefile inventory") Zonefile present/absent bits are ordered left-to-right, where the leftmost bit is the earliest zonefile...
Get the in-RAM zonefile inventory vector. offset and length are in *bytes*
def atlas_get_zonefile_inventory( offset=None, length=None ): """ Get the in-RAM zonefile inventory vector. offset and length are in *bytes* """ global ZONEFILE_INV, ZONEFILE_INV_LOCK with ZONEFILE_INV_LOCK: try: assert ZONEFILE_INV is not None except AssertionError:...
Initialize peer info table entry
def atlas_init_peer_info( peer_table, peer_hostport, blacklisted=False, whitelisted=False ): """ Initialize peer info table entry """ peer_table[peer_hostport] = { "time": [], "zonefile_inv": "", "blacklisted": blacklisted, "whitelisted": whitelisted }
Log a socket exception tastefully
def atlas_log_socket_error( method_invocation, peer_hostport, se ): """ Log a socket exception tastefully """ if isinstance( se, socket.timeout ): log.debug("%s %s: timed out (socket.timeout)" % (method_invocation, peer_hostport)) elif isinstance( se, socket.gaierror ): log.debug("%...
Ping a host Return True if alive Return False if not
def atlas_peer_ping( peer_hostport, timeout=None, peer_table=None ): """ Ping a host Return True if alive Return False if not """ if timeout is None: timeout = atlas_ping_timeout() assert not atlas_peer_table_is_locked_by_me() host, port = url_to_host_port( peer_hostport )...
Get host info Return the rpc_getinfo() response on success Return None on error
def atlas_peer_getinfo( peer_hostport, timeout=None, peer_table=None ): """ Get host info Return the rpc_getinfo() response on success Return None on error """ if timeout is None: timeout = atlas_ping_timeout() host, port = url_to_host_port( peer_hostport ) RPC = get_rpc_client...
Find out how many bits are set in inv2 that are not set in inv1.
def atlas_inventory_count_missing( inv1, inv2 ): """ Find out how many bits are set in inv2 that are not set in inv1. """ count = 0 common = min(len(inv1), len(inv2)) for i in xrange(0, common): for j in xrange(0, 8): if ((1 << (7 - j)) & ord(inv2[i])) != 0 and ((1 << (7...
Get a random set of live neighbors (i.e. neighbors we've contacted before)
def atlas_get_live_neighbors( remote_peer_hostport, peer_table=None, min_health=MIN_PEER_HEALTH, min_request_count=1 ): """ Get a random set of live neighbors (i.e. neighbors we've contacted before) """ with AtlasPeerTableLocked(peer_table) as ptbl: alive_peers = [] for peer_hostpor...
Get *all* neighbor information. USED ONLY FOR TESTING
def atlas_get_all_neighbors( peer_table=None ): """ Get *all* neighbor information. USED ONLY FOR TESTING """ if os.environ.get("BLOCKSTACK_ATLAS_NETWORK_SIMULATION") != "1": raise Exception("This method is only available when testing with the Atlas network simulator") ret = {} wit...
Revalidate peers that are older than the maximum peer age. Ping them, and if they don't respond, remove them.
def atlas_revalidate_peers( con=None, path=None, now=None, peer_table=None ): """ Revalidate peers that are older than the maximum peer age. Ping them, and if they don't respond, remove them. """ global MIN_PEER_HEALTH if now is None: now = time_now() old_peer_infos = atlasdb_get_o...
Get the health score for a peer. Health is: (number of responses received / number of requests sent)
def atlas_peer_get_health( peer_hostport, peer_table=None ): """ Get the health score for a peer. Health is: (number of responses received / number of requests sent) """ with AtlasPeerTableLocked(peer_table) as ptbl: # availability score: number of responses / number of requests num...
How many times have we contacted this peer?
def atlas_peer_get_request_count( peer_hostport, peer_table=None ): """ How many times have we contacted this peer? """ with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return 0 count = 0 for (t, r) in ptbl[peer_hostport]['time']: ...
What's the zonefile inventory vector for this peer? Return None if not defined
def atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=None ): """ What's the zonefile inventory vector for this peer? Return None if not defined """ inv = None with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return None ...
Set this peer's zonefile inventory
def atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=None ): """ Set this peer's zonefile inventory """ with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return None ptbl[peer_hostport]['zonefile_inv'] = peer_inv ...
Is a peer whitelisted
def atlas_peer_is_whitelisted( peer_hostport, peer_table=None ): """ Is a peer whitelisted """ ret = None with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return None ret = ptbl[peer_hostport].get("whitelisted", False) return ret
Mark the given peer as alive at this time. Update times at which we contacted it, and update its health score. Use the global health table by default, or use the given health info if set.
def atlas_peer_update_health( peer_hostport, received_response, peer_table=None ): """ Mark the given peer as alive at this time. Update times at which we contacted it, and update its health score. Use the global health table by default, or use the given health info if set. """ with A...
Get the zonefile inventory bit vector for a given peer. The returned range will be [bit_offset, bit_offset+count] Update peer health information as well. bit_offset and bit_count are in bits. Return the bit vector on success (padded to the nearest byte with 0's). Return None if we couldn't co...
def atlas_peer_get_zonefile_inventory_range( my_hostport, peer_hostport, bit_offset, bit_count, timeout=None, peer_table=None ): """ Get the zonefile inventory bit vector for a given peer. The returned range will be [bit_offset, bit_offset+count] Update peer health information as well. bit_off...
Get the zonefile inventory from the remote peer Start from the given bit_offset NOTE: this doesn't update the peer table health by default; you'll have to explicitly pass in a peer table (i.e. setting to {} ensures that nothing happens).
def atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=0, timeout=None, peer_table={} ): """ Get the zonefile inventory from the remote peer Start from the given bit_offset NOTE: this doesn't update the peer table health by default; you'll have to explicitly pass...
Synchronize our knowledge of a peer's zonefiles up to a given byte length NOT THREAD SAFE; CALL FROM ONLY ONE THREAD. maxlen is the maximum length in bits of the expected zonefile. Return the new inv vector if we synced it (updating the peer table in the process) Return None if not
def atlas_peer_sync_zonefile_inventory( my_hostport, peer_hostport, maxlen, timeout=None, peer_table=None ): """ Synchronize our knowledge of a peer's zonefiles up to a given byte length NOT THREAD SAFE; CALL FROM ONLY ONE THREAD. maxlen is the maximum length in bits of the expected zonefile. Retu...
Refresh a peer's zonefile recent inventory vector entries, by removing every bit after byte_offset and re-synchronizing them. The intuition here is that recent zonefiles are much rarer than older zonefiles (which will have been near-100% replicated), meaning the tail of the peer's zonefile inventory is...
def atlas_peer_refresh_zonefile_inventory( my_hostport, peer_hostport, byte_offset, timeout=None, peer_table=None, con=None, path=None, local_inv=None ): """ Refresh a peer's zonefile recent inventory vector entries, by removing every bit after byte_offset and re-synchronizing them. The intuition here ...
Does the given atlas node have a fresh zonefile inventory?
def atlas_peer_has_fresh_zonefile_inventory( peer_hostport, peer_table=None ): """ Does the given atlas node have a fresh zonefile inventory? """ fresh = False with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return False now = time_no...
Mark a zonefile as being present or absent on a peer. Use this method to update our knowledge of what other peers have, based on when we try to ask them for zonefiles (i.e. a peer can lie about what zonefiles it has, and if it advertizes the availability of a zonefile but doesn't deliver, then we need t...
def atlas_peer_set_zonefile_status( peer_hostport, zonefile_hash, present, zonefile_bits=None, peer_table=None, con=None, path=None ): """ Mark a zonefile as being present or absent on a peer. Use this method to update our knowledge of what other peers have, based on when we try to ask them for zonefile...
Find the set of missing zonefiles, as well as their popularity amongst our neighbors. Only consider zonefiles that are known by at least one peer; otherwise they're missing from our clique (and we'll re-sync our neighborss' inventories every so often to make sure we detect when zonefiles becom...
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ): """ Find the set of missing zonefiles, as well as their popularity amongst our neighbors. Only consider zonefiles that are known by at least one peer; otherwise they're missing from ...
Does the given peer have the given zonefile defined? Check its inventory vector Return True if present Return False if not present Return None if we don't know about the zonefile ourselves, or if we don't know about the peer
def atlas_peer_has_zonefile( peer_hostport, zonefile_hash, zonefile_bits=None, con=None, path=None, peer_table=None ): """ Does the given peer have the given zonefile defined? Check its inventory vector Return True if present Return False if not present Return None if we don't know about the zo...
Ask the peer server at the given URL for its neighbors. Update the health info in peer_table (if not given, the global peer table will be used instead) Return the list on success Return None on failure to contact Raise on invalid URL
def atlas_peer_get_neighbors( my_hostport, peer_hostport, timeout=None, peer_table=None, con=None, path=None ): """ Ask the peer server at the given URL for its neighbors. Update the health info in peer_table (if not given, the global peer table will be used instead) Return the list on success ...
Given a list of zonefile hashes. go and get them from the given host. Update node health Return the newly-fetched zonefiles on success (as a dict mapping hashes to zonefile data) Return None on error.
def atlas_get_zonefiles( my_hostport, peer_hostport, zonefile_hashes, timeout=None, peer_table=None ): """ Given a list of zonefile hashes. go and get them from the given host. Update node health Return the newly-fetched zonefiles on success (as a dict mapping hashes to zonefile data) Return N...
Get a ranking of peers to contact for a zonefile. Peers are ranked by health (i.e. response ratio). Optionally include peers we haven't talked to yet (@with_zero_requests) Optionally return [(health, peer)] list instead of just [peer] list (@with_rank)
def atlas_rank_peers_by_health( peer_list=None, peer_table=None, with_zero_requests=False, with_rank=False ): """ Get a ranking of peers to contact for a zonefile. Peers are ranked by health (i.e. response ratio). Optionally include peers we haven't talked to yet (@with_zero_requests) Optionally re...
Get a ranking of peers to contact for a zonefile. Peers are ranked by the number of zonefiles they have which we don't have. This is used to select neighbors.
def atlas_rank_peers_by_data_availability( peer_list=None, peer_table=None, local_inv=None, con=None, path=None ): """ Get a ranking of peers to contact for a zonefile. Peers are ranked by the number of zonefiles they have which we don't have. This is used to select neighbors. """ with Atl...
Begin talking to a new peer, if we aren't already. Don't accept this peer if there are already too many peers in the incoming queue (where "too many" means "more than the maximum neighbor set size") Return True if added Return False if not added
def atlas_peer_enqueue( peer_hostport, peer_table=None, peer_queue=None, max_neighbors=None ): """ Begin talking to a new peer, if we aren't already. Don't accept this peer if there are already too many peers in the incoming queue (where "too many" means "more than the maximum neighbor set size") R...
Get all queued peers
def atlas_peer_dequeue_all( peer_queue=None ): """ Get all queued peers """ peers = [] with AtlasPeerQueueLocked(peer_queue) as pq: while len(pq) > 0: peers.append( pq.pop(0) ) return peers
Find the set of peers that do *not* have this zonefile.
def atlas_zonefile_find_push_peers( zonefile_hash, peer_table=None, zonefile_bits=None, con=None, path=None ): """ Find the set of peers that do *not* have this zonefile. """ if zonefile_bits is None: zonefile_bits = atlasdb_get_zonefile_bits( zonefile_hash, path=path, con=con ) if len(...
Enqueue the given zonefile into our "push" queue, from which it will be replicated to storage and sent out to other peers who don't have it. Return True if we enqueued it Return False if not
def atlas_zonefile_push_enqueue( zonefile_hash, name, txid, zonefile_data, zonefile_queue=None, con=None, path=None ): """ Enqueue the given zonefile into our "push" queue, from which it will be replicated to storage and sent out to other peers who don't have it. Return True if we enqueued it R...
Dequeue a zonefile's information to replicate Return None if there are none queued
def atlas_zonefile_push_dequeue( zonefile_queue=None ): """ Dequeue a zonefile's information to replicate Return None if there are none queued """ ret = None with AtlasZonefileQueueLocked(zonefile_queue) as zfq: if len(zfq) > 0: ret = zfq.pop(0) return ret
Push the given zonefile to the given peer Return True on success Return False on failure
def atlas_zonefile_push( my_hostport, peer_hostport, zonefile_data, timeout=None, peer_table=None ): """ Push the given zonefile to the given peer Return True on success Return False on failure """ if timeout is None: timeout = atlas_push_zonefiles_timeout() zonefile_hash = get_z...
Start up the atlas node. Return a bundle of atlas state
def atlas_node_init(my_hostname, my_portnum, atlasdb_path, zonefile_dir, working_dir): """ Start up the atlas node. Return a bundle of atlas state """ atlas_state = {} atlas_state['peer_crawler'] = AtlasPeerCrawler(my_hostname, my_portnum, atlasdb_path, working_dir) atlas_state['health_check...
Start up atlas threads
def atlas_node_start(atlas_state): """ Start up atlas threads """ for component in atlas_state.keys(): log.debug("Starting Atlas component '%s'" % component) atlas_state[component].start()
Add a callback to the initialized atlas state
def atlas_node_add_callback(atlas_state, callback_name, callback): """ Add a callback to the initialized atlas state """ if callback_name == 'store_zonefile': atlas_state['zonefile_crawler'].set_store_zonefile_callback(callback) else: raise ValueError("Unrecognized callback {}".form...
Stop the atlas node threads
def atlas_node_stop( atlas_state ): """ Stop the atlas node threads """ for component in atlas_state.keys(): log.debug("Stopping Atlas component '%s'" % component) atlas_state[component].ask_join() atlas_state[component].join() return True
Get the canonical peer name
def canonical_peer( self, peer ): """ Get the canonical peer name """ their_host, their_port = url_to_host_port( peer ) if their_host in ['127.0.0.1', '::1']: their_host = 'localhost' return "%s:%s" % (their_host, their_port)
Get neighbors of this peer NOTE: don't lock peer table in production
def get_neighbors( self, peer_hostport, con=None, path=None, peer_table=None ): """ Get neighbors of this peer NOTE: don't lock peer table in production """ if path is None: path = self.atlasdb_path if self.neighbors_timeout is None: self.neighbor...
Ping up to @count new peers from @new_peers that aren't already known to us. If they respond, then add them to the peer set. Return the (list of peers added, the list of peers already known, list of peers ignored)
def add_new_peers( self, count, new_peers, current_peers, con=None, path=None, peer_table=None ): """ Ping up to @count new peers from @new_peers that aren't already known to us. If they respond, then add them to the peer set. Return the (list of peers added, the list of peers...
Remove up to @count unhealthy peers Return the list of peers we removed
def remove_unhealthy_peers( self, count, con=None, path=None, peer_table=None, min_request_count=10, min_health=MIN_PEER_HEALTH ): """ Remove up to @count unhealthy peers Return the list of peers we removed """ if path is None: path = self.atlasdb_path ...
Take one step from current_peer to a neighbor in current_peer_neighbors, based on Metropolis-Hastings Random Walk with Delayed Acceptance (MHRWDA). The basic idea is to reduce the probability (versus MH alone) that we transition to the previous node. We do so using the Metropolis-Hastings Rando...
def random_walk_graph( self, prev_peer, prev_peer_degree, current_peer, current_peer_neighbors, con=None, path=None, peer_table=None ): """ Take one step from current_peer to a neighbor in current_peer_neighbors, based on Metropolis-Hastings Random Walk with Delayed Acceptance (MHRWDA). ...
Get the current set of peers
def get_current_peers( self, peer_table=None ): """ Get the current set of peers """ # get current peers current_peers = None with AtlasPeerTableLocked(peer_table) as ptbl: current_peers = ptbl.keys()[:] return current_peers
Make a list of canonical new peers, using the self.new_peers and the given peers to add Return a shuffled list of canonicalized host:port strings.
def canonical_new_peer_list( self, peers_to_add ): """ Make a list of canonical new peers, using the self.new_peers and the given peers to add Return a shuffled list of canonicalized host:port strings. """ new_peers = list(set(self.new_peers + peers_to_add)) ...
Add at most $num_new_peers new peers from the pending peer queue to the peer DB. Ping them first (to see if they're alive), and drop hosts from the pending queue if it gets too long. Update our new peer queue, and update the peer table. Return the number of peers processed
def update_new_peers( self, num_new_peers, current_peers, peer_queue=None, peer_table=None, con=None, path=None ): """ Add at most $num_new_peers new peers from the pending peer queue to the peer DB. Ping them first (to see if they're alive), and drop hosts from the pending queue if it g...
Update the set of existing peers: * revalidate the existing but old peers * remove at most $num_to_remove unhealthy peers Return the number of peers removed
def update_existing_peers( self, num_to_remove, peer_table=None, con=None, path=None ): """ Update the set of existing peers: * revalidate the existing but old peers * remove at most $num_to_remove unhealthy peers Return the number of peers removed """ i...
Execute one round of the peer discovery algorithm: * Add at most 10 new peers from the pending peer queue (but ping them first, and drop hosts if the pending queue gets to be too long). * Execute one step of the MHRWDA algorithm. Add any new peers from the neighbor sets discover...
def step( self, local_inv=None, peer_table=None, peer_queue=None, con=None, path=None ): """ Execute one round of the peer discovery algorithm: * Add at most 10 new peers from the pending peer queue (but ping them first, and drop hosts if the pending queue gets to be too long). ...
Find peers with stale zonefile inventory data, and refresh them. Return True on success Return False on error
def step(self, con=None, path=None, peer_table=None, local_inv=None): """ Find peers with stale zonefile inventory data, and refresh them. Return True on success Return False on error """ if path is None: path = self.atlasdb_path peer_hostpor...
Loop forever, pinging someone every pass.
def run(self, peer_table=None): """ Loop forever, pinging someone every pass. """ self.running = True while self.running: local_inv = atlas_get_zonefile_inventory() t1 = time_now() self.step( peer_table=peer_table, local_inv=local_inv, path=sel...
Set a zonefile as present, and if it was previously absent, inform the storage listener
def set_zonefile_present(self, zfhash, block_height, con=None, path=None): """ Set a zonefile as present, and if it was previously absent, inform the storage listener """ was_present = atlasdb_set_zonefile_present( zfhash, True, con=con, path=path ) # tell anyone who cares that ...
Store the fetched zonefile (as a serialized string) to storage and cache it locally. Update internal state to mark it present Return True on success Return False on error
def store_zonefile_data( self, fetched_zfhash, zonefile_data, min_block_height, peer_hostport, con, path ): """ Store the fetched zonefile (as a serialized string) to storage and cache it locally. Update internal state to mark it present Return True on success Return False on err...
Store a list of RPC-fetched zonefiles (but only ones in peer_zonefile_hashes) from the given peer_hostport Return the list of zonefile hashes stored.
def store_zonefiles( self, zonefile_names, zonefiles, zonefile_txids, zonefile_block_heights, peer_zonefile_hashes, peer_hostport, path, con=None ): """ Store a list of RPC-fetched zonefiles (but only ones in peer_zonefile_hashes) from the given peer_hostport Return the list of zonefile hashes s...
Find out which peers can serve which zonefiles
def find_zonefile_origins( self, missing_zfinfo, peer_hostports ): """ Find out which peers can serve which zonefiles """ zonefile_origins = {} # map peer hostport to list of zonefile hashes # which peers can serve each zonefile? for zfhash in missing_zfinfo.keys(): ...
Run one step of this algorithm: * find the set of missing zonefiles * try to fetch each of them * store them * update our zonefile database Fetch rarest zonefiles first, but batch whenever possible. Return the number of zonefiles fetched
def step(self, path=None, peer_table=None): """ Run one step of this algorithm: * find the set of missing zonefiles * try to fetch each of them * store them * update our zonefile database Fetch rarest zonefiles first, but batch whenever possible. ...
Run one step of this algorithm. Push the zonefile to all the peers that need it. Return the number of peers we sent to
def step( self, peer_table=None, zonefile_queue=None, path=None ): """ Run one step of this algorithm. Push the zonefile to all the peers that need it. Return the number of peers we sent to """ if path is None: path = self.atlasdb_path if BLOCKSTACK_T...
Create a sqlite3 db at the given path. Create all the tables and indexes we need. Raises if the table already exists
def queuedb_create(path): """ Create a sqlite3 db at the given path. Create all the tables and indexes we need. Raises if the table already exists """ global QUEUE_SQL, ERROR_SQL lines = [l + ";" for l in QUEUE_SQL.split(";")] con = sqlite3.connect( path, isolation_level=None ) db_...
Dict row factory
def queuedb_row_factory(cursor, row): """ Dict row factory """ d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
Find a record by name and queue ID. Return the rows on success (empty list if not found) Raise on error
def queuedb_find(path, queue_id, name, offset=None, limit=None): """ Find a record by name and queue ID. Return the rows on success (empty list if not found) Raise on error """ return queuedb_findall(path, queue_id, name=name, offset=offset, limit=limit)
Get all queued entries for a queue and a name. If name is None, then find all queue entries Return the rows on success (empty list if not found) Raise on error
def queuedb_findall(path, queue_id, name=None, offset=None, limit=None): """ Get all queued entries for a queue and a name. If name is None, then find all queue entries Return the rows on success (empty list if not found) Raise on error """ sql = "SELECT * FROM queue WHERE queue_id = ? ORDE...
Append an element to the back of the queue. Return True on success Raise on error
def queuedb_append(path, queue_id, name, data): """ Append an element to the back of the queue. Return True on success Raise on error """ sql = "INSERT INTO queue VALUES (?,?,?);" args = (name, queue_id, data) db = queuedb_open(path) if db is None: raise Exception("Failed to...
Remove an element from a queue. Return True on success Raise on error
def queuedb_remove(path, entry, cur=None): """ Remove an element from a queue. Return True on success Raise on error """ sql = "DELETE FROM queue WHERE queue_id = ? AND name = ?;" args = (entry['queue_id'], entry['name']) cursor = None if cur: cursor = cur else: ...
Remove all entries from a queue
def queuedb_removeall(path, entries): """ Remove all entries from a queue """ db = queuedb_open(path) if db is None: raise Exception("Failed to open %s" % path) cursor = db.cursor() queuedb_query_execute(cursor, 'BEGIN', ()) for entry in entries: queuedb_remove(path, en...
There are four poutputs: the OP_RETURN, the registration (owner) address, the change address (i.e. from the preorderer), and the burn address with the renewal fee. Get the burn address and value
def get_renew_burn_info( outputs ): """ There are four poutputs: the OP_RETURN, the registration (owner) address, the change address (i.e. from the preorderer), and the burn address with the renewal fee. Get the burn address and value """ if len(outputs) < 4: raise Exception("Malfor...
Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction.
def get_num_names_owned( state_engine, checked_ops, sender ): """ Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction. """ count = 0 registers = find_by_opcode( checked_ops, "NAME_REGISTRATION" ) for reg in registers: if reg['sender'...
Find out how many tokens were paid for this nameop, if any. You need to have called state_create_put_preorder() *before* calling this on a NAME_REGISTRATION. Return {'status': True, 'token_units': ..., 'tokens_paid': ...} on success Return {'status': False} on error (i.e. this is not the right kind of name...
def get_stacks_payment(state_engine, nameop, state_op_type): """ Find out how many tokens were paid for this nameop, if any. You need to have called state_create_put_preorder() *before* calling this on a NAME_REGISTRATION. Return {'status': True, 'token_units': ..., 'tokens_paid': ...} on success R...
Check a token payment was enough and was of the right type Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not
def check_token_payment(name, token_price, stacks_payment_info): """ Check a token payment was enough and was of the right type Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not """ token_units = stacks_payment_info['token_units'] tokens_pa...
Verify that if tokens were paid for a name priced in BTC, that enough were paid. Does not check account balances or namespace types; it only inspects the transaction data. Returns {'status': True, 'tokens_paid': ..., 'token_units': ...} on success Returns {'status': False} on error
def check_payment_in_stacks(state_engine, nameop, state_op_type, fee_block_id): """ Verify that if tokens were paid for a name priced in BTC, that enough were paid. Does not check account balances or namespace types; it only inspects the transaction data. Returns {'status': True, 'tokens_paid': ..., 't...
Verify that for a version-1 namespace, the nameop paid the right amount of BTC or STACKs. nameop is either a name registration or name renewal Return {'status': True, 'tokens_paid': ..., 'token_units': ...} Return {'status': False} if not
def check_payment_v1(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): """ Verify that for a version-1 namespace, the nameop paid the right amount of BTC or STACKs. nameop is either a name registration or name renewal Return {'status': True, 'tokens_pai...
Verify that for a version-2 namespace (burn-to-creator), the nameop paid the right amount of BTC or Stacks. It can pay either through a preorder (for registers), or directly (for renewals) Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not.
def check_payment_v2(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): """ Verify that for a version-2 namespace (burn-to-creator), the nameop paid the right amount of BTC or Stacks. It can pay either through a preorder (for registers), or directly (for ren...
Verify that for a version-3 namespace (burn Stacks), the nameop paid the right amount of STACKs. Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not
def check_payment_v3(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): """ Verify that for a version-3 namespace (burn Stacks), the nameop paid the right amount of STACKs. Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'st...
Verify that the right payment was made, in the right cryptocurrency units. Does not check any accounts or modify the nameop in any way; it only checks that the name was paid for by the transaction. NOTE: if state_op_type is NAME_REGISTRATION, you will need to have called state_create_put_preorder() before call...
def check_payment(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): """ Verify that the right payment was made, in the right cryptocurrency units. Does not check any accounts or modify the nameop in any way; it only checks that the name was paid for by the ...