INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get the number of names owned by an address throughout history Return {'status': True, 'count': ...} on success Return {'error': ...} on failure
def rpc_get_num_historic_names_by_address(self, address, **con_info): """ Get the number of names owned by an address throughout history Return {'status': True, 'count': ...} on success Return {'error': ...} on failure """ if not check_address(address): return...
Return the cost of a given name. Returns {'amount': ..., 'units': ...}
def rpc_get_name_cost( self, name, **con_info ): """ Return the cost of a given name. Returns {'amount': ..., 'units': ...} """ if not check_name(name): return {'error': 'Invalid name or namespace', 'http_status': 400} db = get_db_state(self.working_dir) ...
Return the cost of a given namespace, including fees. Returns {'amount': ..., 'units': ...}
def rpc_get_namespace_cost( self, namespace_id, **con_info ): """ Return the cost of a given namespace, including fees. Returns {'amount': ..., 'units': ...} """ if not check_namespace(namespace_id): return {'error': 'Invalid namespace', 'http_status': 400} d...
Get the types of tokens that an account owns Returns the list on success
def rpc_get_account_tokens(self, address, **con_info): """ Get the types of tokens that an account owns Returns the list on success """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status': 400} # must be b58 if is_...
Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0, or if there is no address
def rpc_get_account_balance(self, address, token_type, **con_info): """ Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0, or if there is no address """ if not check_account_address(address): r...
Make an account state presentable to external consumers
def export_account_state(self, account_state): """ Make an account state presentable to external consumers """ return { 'address': account_state['address'], 'type': account_state['type'], 'credit_value': '{}'.format(account_state['credit_value']), ...
Get the current state of an account
def rpc_get_account_record(self, address, token_type, **con_info): """ Get the current state of an account """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status': 400} if not check_token_type(token_type): return {'err...
Get the history of an account, pagenated over a block range. Returns the sequence of history states on success (can be empty)
def rpc_get_account_history(self, address, page, **con_info): """ Get the history of an account, pagenated over a block range. Returns the sequence of history states on success (can be empty) """ if not check_account_address(address): return {'error': 'Invalid address...
Get the account's statuses at a particular block height. Returns the sequence of history states on success
def rpc_get_account_at(self, address, block_height, **con_info): """ Get the account's statuses at a particular block height. Returns the sequence of history states on success """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status'...
Return the namespace with the given namespace_id Return {'status': True, 'record': ...} on success Return {'error': ...} on error
def rpc_get_namespace_blockchain_record( self, namespace_id, **con_info ): """ Return the namespace with the given namespace_id Return {'status': True, 'record': ...} on success Return {'error': ...} on error """ if not check_namespace(namespace_id): return {...
Get the number of names that exist and are not expired Return {'status': True, 'count': count} on success Return {'error': ...} on error
def rpc_get_num_names( self, **con_info ): """ Get the number of names that exist and are not expired Return {'status': True, 'count': count} on success Return {'error': ...} on error """ db = get_db_state(self.working_dir) num_names = db.get_num_names() d...
Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error
def rpc_get_num_names_cumulative( self, **con_info ): """ Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error """ db = get_db_state(self.working_dir) num_names = db.get_num_names(include_...
Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
def rpc_get_all_names( self, offset, count, **con_info ): """ Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_offset(offset): return {'error': 'invalid offset', 'http_status'...
Get all subdomains, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
def rpc_get_all_subdomains( self, offset, count, **conf_info): """ Get all subdomains, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_offset(offset): return {'error': 'invalid offset', 'http_status'...
Get all names that have ever existed, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
def rpc_get_all_names_cumulative( self, offset, count, **con_info ): """ Get all names that have ever existed, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_offset(offset): return {'error': 'invali...
Get all namespace names Return {'status': true, 'namespaces': [...]} on success Return {'error': ...} on error
def rpc_get_all_namespaces( self, **con_info ): """ Get all namespace names Return {'status': true, 'namespaces': [...]} on success Return {'error': ...} on error """ db = get_db_state(self.working_dir) all_namespaces = db.get_all_namespace_ids() db.close(...
Get the number of names in a namespace Return {'status': true, 'count': count} on success Return {'error': ...} on error
def rpc_get_num_names_in_namespace( self, namespace_id, **con_info ): """ Get the number of names in a namespace Return {'status': true, 'count': count} on success Return {'error': ...} on error """ if not check_namespace(namespace_id): return {'error': 'Inval...
Return all names in a namespace, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
def rpc_get_names_in_namespace( self, namespace_id, offset, count, **con_info ): """ Return all names in a namespace, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_namespace(namespace_id): return {...
Return the list of subdomain operations accepted within a given txid. Return {'status': True, 'subdomain_ops': [{...}]} on success Return {'error': ...} on error
def rpc_get_subdomain_ops_at_txid(self, txid, **con_info): """ Return the list of subdomain operations accepted within a given txid. Return {'status': True, 'subdomain_ops': [{...}]} on success Return {'error': ...} on error """ if not check_string(txid, min_length=64, ma...
Return the consensus hash at a block number. Return {'status': True, 'consensus': ...} on success Return {'error': ...} on error
def rpc_get_consensus_at( self, block_id, **con_info ): """ Return the consensus hash at a block number. Return {'status': True, 'consensus': ...} on success Return {'error': ...} on error """ if not check_block(block_id): return {'error': 'Invalid block heigh...
Return the consensus hashes at multiple block numbers Return a dict mapping each block ID to its consensus hash. Returns {'status': True, 'consensus_hashes': dict} on success Returns {'error': ...} on success
def rpc_get_consensus_hashes( self, block_id_list, **con_info ): """ Return the consensus hashes at multiple block numbers Return a dict mapping each block ID to its consensus hash. Returns {'status': True, 'consensus_hashes': dict} on success Returns {'error': ...} on success ...
Given the consensus hash, find the block number (or None)
def rpc_get_block_from_consensus( self, consensus_hash, **con_info ): """ Given the consensus hash, find the block number (or None) """ if not check_string(consensus_hash, min_length=LENGTHS['consensus_hash']*2, max_length=LENGTHS['consensus_hash']*2, pattern=OP_CONSENSUS_HASH_PATTERN): ...
Get a zonefile by hash Return the serialized zonefile on success Return None on error
def get_zonefile_data( self, zonefile_hash, zonefile_dir ): """ Get a zonefile by hash Return the serialized zonefile on success Return None on error """ # check cache atlas_zonefile_data = get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=False ) ...
Get zonefiles from the local zonefile set. Only return at most 100 zonefiles. Return {'status': True, 'zonefiles': {zonefile_hash: zonefile}} on success Return {'error': ...} on error zonefiles will be serialized to string and base64-encoded
def rpc_get_zonefiles( self, zonefile_hashes, **con_info ): """ Get zonefiles from the local zonefile set. Only return at most 100 zonefiles. Return {'status': True, 'zonefiles': {zonefile_hash: zonefile}} on success Return {'error': ...} on error zonefiles will be seria...
Replicate one or more zonefiles, given as serialized strings. Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files) Returns {'status': True, 'saved': [0|1]'} on success ('saved' is a vector of success/failure) Returns {'error': ...} on err...
def rpc_put_zonefiles( self, zonefile_datas, **con_info ): """ Replicate one or more zonefiles, given as serialized strings. Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files) Returns {'status': True, 'saved': [0|1]'} on success...
Get information about zonefiles announced in blocks [@from_block, @to_block] @offset - offset into result set @count - max records to return, must be <= 100 Returns {'status': True, 'lastblock' : blockNumber, 'zonefile_info' : [ { 'block_height' : 470000, ...
def rpc_get_zonefiles_by_block( self, from_block, to_block, offset, count, **con_info ): """ Get information about zonefiles announced in blocks [@from_block, @to_block] @offset - offset into result set @count - max records to return, must be <= 100 Returns {'status': True, 'last...
Exchange peers. Add the given peer to the list of new peers to consider. Return the list of healthy peers
def peer_exchange(self, peer_host, peer_port): """ Exchange peers. Add the given peer to the list of new peers to consider. Return the list of healthy peers """ # get peers peer_list = atlas_get_live_neighbors( "%s:%s" % (peer_host, peer_port) ) if len(pee...
Get the list of peer atlas nodes. Give its own atlas peer hostport. Return at most atlas_max_neighbors() peers Return {'status': True, 'peers': ...} on success Return {'error': ...} on failure
def rpc_get_atlas_peers( self, **con_info ): """ Get the list of peer atlas nodes. Give its own atlas peer hostport. Return at most atlas_max_neighbors() peers Return {'status': True, 'peers': ...} on success Return {'error': ...} on failure """ conf = get...
Accept a remotely-given atlas peer, and return our list of healthy peers. The remotely-given atlas peer will only be considered if the caller is localhost; otherwise, the caller's socket-given information will be used. This is to prevent a malicious node from filling up this node's pee...
def rpc_atlas_peer_exchange(self, remote_peer, **con_info): """ Accept a remotely-given atlas peer, and return our list of healthy peers. The remotely-given atlas peer will only be considered if the caller is localhost; otherwise, the caller's socket-given information will be us...
Stop serving. Also stops the thread.
def stop_server(self): """ Stop serving. Also stops the thread. """ if self.rpc_server is not None: try: self.rpc_server.socket.shutdown(socket.SHUT_RDWR) except: log.warning("Failed to shut down server socket") self.r...
Get an inventory bit vector for the zonefiles in the given bit range (i.e. offset and length are in bytes) Returns at most 64k of inventory (or 524288 bits) Return {'status': True, 'inv': ...} on success, where 'inv' is a b64-encoded bit vector string Return {'error': ...} on error.
def rpc_get_zonefile_inventory( self, offset, length, **con_info ): """ Get an inventory bit vector for the zonefiles in the given bit range (i.e. offset and length are in bytes) Returns at most 64k of inventory (or 524288 bits) Return {'status': True, 'inv': ...} on success, whe...
Stop serving
def stop_server(self): """ Stop serving """ if self.api_server is not None: try: self.api_server.socket.shutdown(socket.SHUT_RDWR) except: log.warning("Failed to shut down API server socket") self.api_server.shutdown()
Get the last block processed Return the integer on success Return None on error
def get_last_block(working_dir): """ Get the last block processed Return the integer on success Return None on error """ # make this usable even if we haven't explicitly configured virtualchain impl = sys.modules[__name__] return BlockstackDB.get_lastblock(impl, working_dir)
Read the virtualchain snapshots Returns the dict of {snapshots: {$block_height: $consensus_hash}} on success Returns None on error
def get_snapshots(working_dir, start_block=None, end_block=None): """ Read the virtualchain snapshots Returns the dict of {snapshots: {$block_height: $consensus_hash}} on success Returns None on error """ # make this usable even if we haven't explicitly configured virtualchain impl = sys.m...
Callback to the virtual chain state engine. Get a *read-only* handle to our state engine implementation (i.e. our name database). Note that in this implementation, the database handle returned will only support read-only operations by default. Attempts to save state with the handle will lead to pro...
def get_db_state(working_dir): """ Callback to the virtual chain state engine. Get a *read-only* handle to our state engine implementation (i.e. our name database). Note that in this implementation, the database handle returned will only support read-only operations by default. Attempts to ...
Get a read-only handle to the DB. Instantiate it first if it doesn't exist. DO NOT CALL WHILE INDEXING Returns the handle on success Raises on error
def get_or_instantiate_db_state(working_dir): """ Get a read-only handle to the DB. Instantiate it first if it doesn't exist. DO NOT CALL WHILE INDEXING Returns the handle on success Raises on error """ # instantiates new_db = BlockstackDB.borrow_readwrite_instance(working_dir, -1...
(required by virtualchain state engine) Parse a blockstack operation from a transaction. The transaction fields are as follows: * `block_id` is the blockchain height at which this transaction occurs * `txid` is the transaction ID * `data` is the scratch area of the transaction that contains the actual ...
def db_parse( block_id, txid, vtxindex, op, data, senders, inputs, outputs, fee, db_state=None, **virtualchain_hints ): """ (required by virtualchain state engine) Parse a blockstack operation from a transaction. The transaction fields are as follows: * `block_id` is the blockchain height at which this...
Verify that all mutate fields are present. Return True if so. Raise an exception (AssertionError) if not.
def check_mutate_fields( op, op_data ): """ Verify that all mutate fields are present. Return True if so. Raise an exception (AssertionError) if not. """ mutate_fields = op_get_mutate_fields( op ) assert mutate_fields is not None, "No mutate fields defined for %s" % op missing = [] ...
(required by virtualchain state engine) Given the block ID and the list of virtualchain operations in the block, do block-level preprocessing: * find the state-creation operations we will accept * make sure there are no collisions. This modifies op_list, but returns nothing. This aborts on run...
def db_scan_block( block_id, op_list, db_state=None ): """ (required by virtualchain state engine) Given the block ID and the list of virtualchain operations in the block, do block-level preprocessing: * find the state-creation operations we will accept * make sure there are no collisions. ...
(required by virtualchain state engine) Given the block ID and a parsed operation, check to see if this is a *valid* operation. Is this operation consistent with blockstack's rules? checked_ops is a list of operations already checked by this method for this block. A name or namespace can...
def db_check( block_id, new_ops, op, op_data, txid, vtxindex, checked_ops, db_state=None ): """ (required by virtualchain state engine) Given the block ID and a parsed operation, check to see if this is a *valid* operation. Is this operation consistent with blockstack's rules? checked_ops is...
Check that all serialization compatibility quirks have been preserved. Used primarily for testing.
def check_quirks(block_id, block_op, db_state): """ Check that all serialization compatibility quirks have been preserved. Used primarily for testing. """ if op_get_opcode_name(block_op['op']) in OPCODE_NAME_NAMEOPS and op_get_opcode_name(block_op['op']) not in OPCODE_NAME_STATE_PREORDER: as...
(required by virtualchain state engine) Advance the state of the state engine: get a list of all externally visible state transitions. Given a block ID and checked opcode, record it as part of the database. This does *not* need to write the data to persistent storage, since save() will be ...
def db_commit( block_id, op, op_data, txid, vtxindex, db_state=None ): """ (required by virtualchain state engine) Advance the state of the state engine: get a list of all externally visible state transitions. Given a block ID and checked opcode, record it as part of the database. This do...
(required by virtualchain state engine) Save all persistent state to stable storage. Called once per block. In Blockstack's case, we save transactions as we process them. The only thing to do here is to synchronize the Atlas DB and clean up the BlockstackDB instance in preparation for receiving the...
def db_save( block_height, consensus_hash, ops_hash, accepted_ops, virtualchain_ops_hints, db_state=None ): """ (required by virtualchain state engine) Save all persistent state to stable storage. Called once per block. In Blockstack's case, we save transactions as we process them. The only thing...
(required by virtualchain state engine) Called when virtualchain has synchronized all state for this block. Blockstack uses this as a preemption point where it can safely exit if the user has so requested.
def db_continue( block_id, consensus_hash ): """ (required by virtualchain state engine) Called when virtualchain has synchronized all state for this block. Blockstack uses this as a preemption point where it can safely exit if the user has so requested. """ # every so often, clean up ...
synchronize state with the blockchain. Return True on success Return False if we're supposed to stop indexing Abort on error
def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ): """ synchronize state with the blockchain. Return True on success Return False if we're supposed to stop indexing Abort on error """ subdomain_index = server_state['subdoma...
Given a URL, turn it into (host, port) for a blockstack server. Return (None, None) on invalid URL
def url_to_host_port(url, port=None): """ Given a URL, turn it into (host, port) for a blockstack server. Return (None, None) on invalid URL """ if not url.startswith('http://') and not url.startswith('https://'): url = 'http://' + url if not port: port = RPC_SERVER_PORT ur...
Get the protocol to use for a URL. return 'http' or 'https' or None
def url_protocol(url, port=None): """ Get the protocol to use for a URL. return 'http' or 'https' or None """ if not url.startswith('http://') and not url.startswith('https://'): return None urlinfo = urllib2.urlparse.urlparse(url) assert urlinfo.scheme in ['http', 'https'], 'Invali...
Inventory to string (bitwise big-endian)
def atlas_inventory_to_string( inv ): """ Inventory to string (bitwise big-endian) """ ret = "" for i in range(0, len(inv)): for j in range(0, 8): bit_index = 1 << (7 - j) val = (ord(inv[i]) & bit_index) if val != 0: ret += "1" ...
Standard way of making a DID. name_type is "name" or "subdomain"
def make_DID(name_type, address, index): """ Standard way of making a DID. name_type is "name" or "subdomain" """ if name_type not in ['name', 'subdomain']: raise ValueError("Require 'name' or 'subdomain' for name_type") if name_type == 'name': address = virtualchain.address_ree...
Given a DID string, parse it into {'address': ..., 'index': ..., 'name_type'} Raise on invalid DID
def parse_DID(did, name_type=None): """ Given a DID string, parse it into {'address': ..., 'index': ..., 'name_type'} Raise on invalid DID """ did_pattern = '^did:stack:v0:({}{{25,35}})-([0-9]+)$'.format(OP_BASE58CHECK_CLASS) m = re.match(did_pattern, did) assert m, 'Invalid DID: {}'.format...
Double-fork and make a daemon. Have the intermediate child call child_wait() to block its exit until the child is "ready" (i.e. child_wait() returns) Return 0 if we're the daemon child Return >0 if we're the parent
def daemonize(logfile): """ Double-fork and make a daemon. Have the intermediate child call child_wait() to block its exit until the child is "ready" (i.e. child_wait() returns) Return 0 if we're the daemon child Return >0 if we're the parent """ # turn off GC across the fork ...
Same as in BaseServer but as a thread. In addition, exception handling is done here.
def process_request_thread(self, request, client_address): """ Same as in BaseServer but as a thread. In addition, exception handling is done here. """ from ..blockstackd import get_gc_thread try: self.finish_request(request, client_address) except Ex...
Accept a request, up to the given number of allowed threads. Defer to self.overloaded if there are already too many pending requests.
def get_request(self): """ Accept a request, up to the given number of allowed threads. Defer to self.overloaded if there are already too many pending requests. """ # Note that this class must be mixed with another class that implements get_request() request, client_addr ...
Start a new thread to process the request.
def process_request(self, request, client_address): """ Start a new thread to process the request. """ if request is None or client_address is None: # request was never initialized, i.e. due to overload return t = threading.Thread(target = self.process_r...
Which epoch are we in? Return integer (>=0) on success
def get_epoch_number( block_height ): """ Which epoch are we in? Return integer (>=0) on success """ 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][...
Get the epoch constants for the given block height
def get_epoch_config( block_height ): """ Get the epoch constants for the given block height """ global EPOCHS epoch_number = get_epoch_number( block_height ) if epoch_number < 0 or epoch_number >= len(EPOCHS): log.error("FATAL: invalid epoch %s" % epoch_number) os.abort() ...
what's the namespace lifetime multipler for this epoch?
def get_epoch_namespace_lifetime_multiplier( block_height, namespace_id ): """ what's the namespace lifetime multipler for this epoch? """ epoch_config = get_epoch_config( block_height ) if epoch_config['namespaces'].has_key(namespace_id): return epoch_config['namespaces'][namespace_id]['NAM...
what's the namespace lifetime grace period for this epoch?
def get_epoch_namespace_lifetime_grace_period( block_height, namespace_id ): """ what's the namespace lifetime grace period for this epoch? """ epoch_config = get_epoch_config( block_height ) if epoch_config['namespaces'].has_key(namespace_id): return epoch_config['namespaces'][namespace_id]...
what's the name price multiplier for this epoch? Not all epochs have one---if this epoch has BLOCKSTACK_INT_DIVISION set, use get_epoch_price_divisor() instead.
def get_epoch_price_multiplier( block_height, namespace_id, units ): """ what's the name price multiplier for this epoch? Not all epochs have one---if this epoch has BLOCKSTACK_INT_DIVISION set, use get_epoch_price_divisor() instead. """ try: assert units in [TOKEN_TYPE_STACKS, 'BTC'], '...
what's the name price divisor for this epoch? Not all epochs have one---if this epoch does NOT have BLOCKSTACK_INT_DIVISION set, use get_epoch_price_multiplier() instead.
def get_epoch_price_divisor( block_height, namespace_id, units ): """ what's the name price divisor for this epoch? Not all epochs have one---if this epoch does NOT have BLOCKSTACK_INT_DIVISION set, use get_epoch_price_multiplier() instead. """ try: assert units in [TOKEN_TYPE_STACKS, 'B...
how long can a namespace receive register/renewal fees?
def get_epoch_namespace_receive_fees_period( block_height, namespace_id ): """ how long can a namespace receive register/renewal fees? """ epoch_config = get_epoch_config( block_height ) if epoch_config['namespaces'].has_key(namespace_id): return epoch_config['namespaces'][namespace_id]['NAM...
get the list of namespace prices by block height
def get_epoch_namespace_prices( block_height, units ): """ get the list of namespace prices by block height """ assert units in ['BTC', TOKEN_TYPE_STACKS], 'Invalid unit {}'.format(units) epoch_config = get_epoch_config( block_height ) if units == 'BTC': return epoch_config['namespace_...
Get the path to the file that stores all of the announcements.
def get_announce_filename( working_dir ): """ Get the path to the file that stores all of the announcements. """ announce_filepath = os.path.join( working_dir, get_default_virtualchain_impl().get_virtual_chain_name() ) + '.announce' return announce_filepath
Is the blockstack daemon synchronizing with the blockchain?
def is_indexing(working_dir): """ Is the blockstack daemon synchronizing with the blockchain? """ indexing_path = get_indexing_lockfile(working_dir) if os.path.exists( indexing_path ): return True else: return False
Set a flag in the filesystem as to whether or not we're indexing.
def set_indexing(working_dir, flag): """ Set a flag in the filesystem as to whether or not we're indexing. """ indexing_path = get_indexing_lockfile(working_dir) if flag: try: fd = open( indexing_path, "w+" ) fd.close() return True except: ...
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
def get_recovery_range(working_dir): """ 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 """ recovery_range_path = os.path.join(working_dir, '.recovery') if not os....
Set the recovery block range if we're restoring and reporcessing transactions from a backup. Writes the recovery range to the working directory if the working directory is given and persist is True
def set_recovery_range(working_dir, start_block, end_block): """ Set the recovery block range if we're restoring and reporcessing transactions from a backup. Writes the recovery range to the working directory if the working directory is given and persist is True """ recovery_range_path = os.pat...
Clear out our recovery hint
def clear_recovery_range(working_dir): """ Clear out our recovery hint """ recovery_range_path = os.path.join(working_dir, '.recovery') if os.path.exists(recovery_range_path): os.unlink(recovery_range_path)
Can we do atlas operations?
def is_atlas_enabled(blockstack_opts): """ Can we do atlas operations? """ if not blockstack_opts['atlas']: log.debug("Atlas is disabled") return False if 'zonefiles' not in blockstack_opts: log.debug("Atlas is disabled: no 'zonefiles' path set") return False if...
Can we do subdomain operations?
def is_subdomains_enabled(blockstack_opts): """ Can we do subdomain operations? """ if not is_atlas_enabled(blockstack_opts): log.debug("Subdomains are disabled") return False if 'subdomaindb_path' not in blockstack_opts: log.debug("Subdomains are disabled: no 'subdomaindb_p...
Store a new announcement locally, atomically.
def store_announcement( working_dir, announcement_hash, announcement_text, force=False ): """ Store a new announcement locally, atomically. """ if not force: # don't store unless we haven't seen it before if announcement_hash in ANNOUNCEMENTS: return announce_filename = get_ann...
Get our default blockstack opts from a config file or from sane defaults.
def default_blockstack_opts( working_dir, config_file=None ): """ Get our default blockstack opts from a config file or from sane defaults. """ global RPC_SERVER_IP, RPC_SERVER_PORT from .util import url_to_host_port from .scripts import is_name_valid if config_file is None: config_file...
Get our default blockstack RESTful API opts from a config file, or from sane defaults.
def default_blockstack_api_opts(working_dir, config_file=None): """ Get our default blockstack RESTful API opts from a config file, or from sane defaults. """ from .util import url_to_host_port, url_protocol if config_file is None: config_file = virtualchain.get_config_filename(get_default_vir...
Prompt the user for a series of parameters Return a dict mapping the parameter name to the user-given value.
def interactive_prompt(message, parameters, default_opts): """ Prompt the user for a series of parameters Return a dict mapping the parameter name to the user-given value. """ # pretty-print the message lines = message.split('\n') max_line_len = max([len(l) for l in lines]) print('...
Find and interactively prompt the user for missing parameters, given the list of all valid parameters and a dict of known options. Return the (updated dict of known options, missing, num_prompted), with the user's input.
def find_missing(message, all_params, given_opts, default_opts, header=None, prompt_missing=True): """ Find and interactively prompt the user for missing parameters, given the list of all valid parameters and a dict of known options. Return the (updated dict of known options, missing, num_prompted), wi...
Given a dict of opts that start with prefix, remove the prefix from each of them.
def opt_strip(prefix, opts): """ Given a dict of opts that start with prefix, remove the prefix from each of them. """ ret = {} for opt_name, opt_value in opts.items(): # remove prefix if opt_name.startswith(prefix): opt_name = opt_name[len(prefix):] ret[opt...
Given a dict of opts, add the given prefix to each key
def opt_restore(prefix, opts): """ Given a dict of opts, add the given prefix to each key """ return {prefix + name: value for name, value in opts.items()}
Get our default bitcoind options, such as from a config file, or from sane defaults
def default_bitcoind_opts(config_file=None, prefix=False): """ Get our default bitcoind options, such as from a config file, or from sane defaults """ default_bitcoin_opts = virtualchain.get_bitcoind_config(config_file=config_file) # drop dict values that are None default_bitcoin_opts = {k...
Get the default configuration directory for blockstackd
def default_working_dir(): """ Get the default configuration directory for blockstackd """ import nameset.virtualchain_hooks as virtualchain_hooks return os.path.expanduser('~/.{}'.format(virtualchain_hooks.get_virtual_chain_name()))
Write our config file with the given options dict. Each key is a section name, and each value is the list of options. If the file exists, do not remove unaffected sections. Instead, merge the sections in opts into the file. Return True on success Raise on error
def write_config_file(opts, config_file): """ Write our config file with the given options dict. Each key is a section name, and each value is the list of options. If the file exists, do not remove unaffected sections. Instead, merge the sections in opts into the file. Return True on success ...
Verify (as semantic versions) if v1 < v2 Patch versions can be different
def semver_newer(v1, v2): """ Verify (as semantic versions) if v1 < v2 Patch versions can be different """ v1_parts = v1.split('.') v2_parts = v2.split('.') if len(v1_parts) < 3 or len(v2_parts) < 3: # one isn't a semantic version return False v1_major, v1_minor, v1_patc...
Load the system configuration and set global variables Return the configuration of the node on success. Return None on failure
def load_configuration(working_dir): """ Load the system configuration and set global variables Return the configuration of the node on success. Return None on failure """ import nameset.virtualchain_hooks as virtualchain_hooks # acquire configuration, and store it globally opts = conf...
Verify the validity of a NAMESPACE_READY operation. It is only valid if it has been imported by the same sender as the corresponding NAMESPACE_REVEAL, and the namespace is still in the process of being imported.
def check( state_engine, nameop, block_id, checked_ops ): """ Verify the validity of a NAMESPACE_READY operation. It is only valid if it has been imported by the same sender as the corresponding NAMESPACE_REVEAL, and the namespace is still in the process of being imported. """ namespace_id ...
NOTE: the first three bytes will be missing NOTE: the first byte in bin_payload is a '.'
def parse( bin_payload ): """ NOTE: the first three bytes will be missing NOTE: the first byte in bin_payload is a '.' """ if len(bin_payload) == 0: log.error("empty namespace") return None if bin_payload[0] != '.': log.error("Missing namespace delimiter '.'") return N...
Turn a non-negative integer into a string. >>> int_to_charset(0, B40_CHARS) '0' >>> int_to_charset(658093, B40_CHARS) 'abcd' >>> int_to_charset(40, B40_CHARS) '10' >>> int_to_charset(149190078205533, B40_CHARS) 'muneeb.id' >>> int_to_charset(-1, B40_CHARS) Traceback (most recent...
def int_to_charset(val, charset): """ Turn a non-negative integer into a string. >>> int_to_charset(0, B40_CHARS) '0' >>> int_to_charset(658093, B40_CHARS) 'abcd' >>> int_to_charset(40, B40_CHARS) '10' >>> int_to_charset(149190078205533, B40_CHARS) 'muneeb.id' >>> int_to_charset...
Turn a string into a non-negative integer. >>> charset_to_int('0', B40_CHARS) 0 >>> charset_to_int('10', B40_CHARS) 40 >>> charset_to_int('abcd', B40_CHARS) 658093 >>> charset_to_int('', B40_CHARS) 0 >>> charset_to_int('muneeb.id', B40_CHARS) 149190078205533 >>> charset_to_i...
def charset_to_int(s, charset): """ Turn a string into a non-negative integer. >>> charset_to_int('0', B40_CHARS) 0 >>> charset_to_int('10', B40_CHARS) 40 >>> charset_to_int('abcd', B40_CHARS) 658093 >>> charset_to_int('', B40_CHARS) 0 >>> charset_to_int('muneeb.id', B40_CHARS) ...
Convert a string from one charset to another.
def change_charset(s, original_charset, target_charset): """ Convert a string from one charset to another. """ if not isinstance(s, str): raise ValueError('"s" must be a string.') intermediate_integer = charset_to_int(s, original_charset) output_string = int_to_charset(intermediate_integer,...
Decorator to automatically fill in extra useful fields that aren't stored in the db.
def autofill(*autofill_fields): """ Decorator to automatically fill in extra useful fields that aren't stored in the db. """ def wrap( reader ): def wrapped_reader( *args, **kw ): rec = reader( *args, **kw ) if rec is not None: for field in autofill_fi...
Get a read-only handle to the blockstack-specific name db. Multiple read-only handles may exist. Returns the handle on success. Returns None on error
def get_readonly_instance(cls, working_dir, expected_snapshots={}): """ Get a read-only handle to the blockstack-specific name db. Multiple read-only handles may exist. Returns the handle on success. Returns None on error """ import virtualchain_hooks db_...
Get a read/write instance to the db, without the singleton check. Used for low-level operations like db restore. Not used in the steady state behavior of the system.
def get_readwrite_instance(cls, working_dir, restore=False, restore_block_height=None): """ Get a read/write instance to the db, without the singleton check. Used for low-level operations like db restore. Not used in the steady state behavior of the system. """ log.warnin...
Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() Returns the handle on success Returns None if we can't set up the db. Aborts if ther...
def borrow_readwrite_instance(cls, working_dir, block_number, expected_snapshots={}): """ Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() ...
Release the read/write instance of the blockstack db. This must be called after borrow_readwrite_instance, with the same block number. After this method completes, it's possible to call borrow_readwrite_instance again. Returns True on success Aborts on error
def release_readwrite_instance( cls, db_inst, block_number ): """ Release the read/write instance of the blockstack db. This must be called after borrow_readwrite_instance, with the same block number. After this method completes, it's possible to call borrow_readwrite_instance again. ...
Calculate the virtulachain-required opfields dict.
def make_opfields( cls ): """ Calculate the virtulachain-required opfields dict. """ # construct fields opfields = {} for opname in SERIALIZE_FIELDS.keys(): opcode = NAME_OPCODES[opname] opfields[opcode] = SERIALIZE_FIELDS[opname] return ...
Get the paths to the relevant db files to back up
def get_state_paths(cls, impl, working_dir): """ Get the paths to the relevant db files to back up """ return super(BlockstackDB, cls).get_state_paths(impl, working_dir) + [ os.path.join(working_dir, 'atlas.db'), os.path.join(working_dir, 'subdomains.db')...
Close the db and release memory
def close( self ): """ Close the db and release memory """ if self.db is not None: self.db.commit() self.db.close() self.db = None return
Copy all database info to a given directory. Used primarily for testing; production users should just pull a backup db from ~/.blockstack-server/backups (or whatever the working directory is)
def export_db(self, dirpath): """ Copy all database info to a given directory. Used primarily for testing; production users should just pull a backup db from ~/.blockstack-server/backups (or whatever the working directory is) """ if self.db is not None: ...
Get the path to the import keychain
def get_import_keychain_path( cls, keychain_dir, namespace_id ): """ Get the path to the import keychain """ cached_keychain = os.path.join( keychain_dir, "{}.keychain".format(namespace_id) ) return cached_keychain
Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key
def build_import_keychain( cls, keychain_dir, namespace_id, pubkey_hex ): """ Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key """ pubkey_addr = virtualchain.BitcoinPublicKey(str(pubkey_hex)).address() # do we have a cached one on disk? c...
Get an import keychain from disk. Return None if it doesn't exist.
def load_import_keychain( cls, working_dir, namespace_id ): """ Get an import keychain from disk. Return None if it doesn't exist. """ # do we have a cached one on disk? cached_keychain = os.path.join(working_dir, "%s.keychain" % namespace_id) if os.path.ex...
Called when the block is finished. Commits all data.
def commit_finished( self, block_id ): """ Called when the block is finished. Commits all data. """ self.db.commit() # NOTE: tokens vest for the *next* block in order to make the immediately usable assert block_id+1 in self.vesting, 'BUG: failed to vest at {}'.f...