_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q225800
atlas_node_add_callback
train
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...
python
{ "resource": "" }
q225801
atlas_node_stop
train
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
python
{ "resource": "" }
q225802
AtlasPeerCrawler.canonical_peer
train
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)
python
{ "resource": "" }
q225803
AtlasPeerCrawler.remove_unhealthy_peers
train
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 ...
python
{ "resource": "" }
q225804
AtlasPeerCrawler.get_current_peers
train
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
python
{ "resource": "" }
q225805
AtlasPeerCrawler.canonical_new_peer_list
train
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)) ...
python
{ "resource": "" }
q225806
AtlasHealthChecker.step
train
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...
python
{ "resource": "" }
q225807
AtlasHealthChecker.run
train
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...
python
{ "resource": "" }
q225808
AtlasZonefileCrawler.set_zonefile_present
train
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 ...
python
{ "resource": "" }
q225809
AtlasZonefileCrawler.find_zonefile_origins
train
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(): ...
python
{ "resource": "" }
q225810
AtlasZonefilePusher.step
train
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...
python
{ "resource": "" }
q225811
queuedb_create
train
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_...
python
{ "resource": "" }
q225812
queuedb_row_factory
train
def queuedb_row_factory(cursor, row): """ Dict row factory """ d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
python
{ "resource": "" }
q225813
queuedb_findall
train
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...
python
{ "resource": "" }
q225814
queuedb_append
train
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...
python
{ "resource": "" }
q225815
queuedb_remove
train
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: ...
python
{ "resource": "" }
q225816
queuedb_removeall
train
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...
python
{ "resource": "" }
q225817
check_payment_in_stacks
train
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...
python
{ "resource": "" }
q225818
check_payment
train
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 ...
python
{ "resource": "" }
q225819
check
train
def check( state_engine, nameop, block_id, checked_ops ): """ Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not. """ namespace_id_hash = nameop['preorder_hash'] consensus_hash = nameop['consensus_hash'] tok...
python
{ "resource": "" }
q225820
snapshot_peek_number
train
def snapshot_peek_number( fd, off ): """ Read the last 8 bytes of fd and interpret it as an int. """ # read number of 8 bytes fd.seek( off - 8, os.SEEK_SET ) value_hex = fd.read(8) if len(value_hex) != 8: return None try: value = int(value_hex, 16) except ValueEr...
python
{ "resource": "" }
q225821
get_file_hash
train
def get_file_hash( fd, hashfunc, fd_len=None ): """ Get the hex-encoded hash of the fd's data """ h = hashfunc() fd.seek(0, os.SEEK_SET) count = 0 while True: buf = fd.read(65536) if len(buf) == 0: break if fd_len is not None: if count + len...
python
{ "resource": "" }
q225822
fast_sync_sign_snapshot
train
def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ): """ Append a signature to the end of a snapshot path with the given private key. If first is True, then don't expect the signature trailer. Return True on success Return False on error """ if not os.path.exists...
python
{ "resource": "" }
q225823
fast_sync_snapshot_compress
train
def fast_sync_snapshot_compress( snapshot_dir, export_path ): """ Given the path to a directory, compress it and export it to the given path. Return {'status': True} on success Return {'error': ...} on failure """ snapshot_dir = os.path.abspath(snapshot_dir) export_path = os.path.abspa...
python
{ "resource": "" }
q225824
fast_sync_snapshot_decompress
train
def fast_sync_snapshot_decompress( snapshot_path, output_dir ): """ Given the path to a snapshot file, decompress it and write its contents to the given output directory Return {'status': True} on success Return {'error': ...} on failure """ if not tarfile.is_tarfile(snapshot_path): ...
python
{ "resource": "" }
q225825
fast_sync_fetch
train
def fast_sync_fetch(working_dir, import_url): """ Get the data for an import snapshot. Store it to a temporary path Return the path on success Return None on error """ try: fd, tmppath = tempfile.mkstemp(prefix='.blockstack-fast-sync-', dir=working_dir) except Exception, e: ...
python
{ "resource": "" }
q225826
state_check_collisions
train
def state_check_collisions( state_engine, nameop, history_id_key, block_id, checked_ops, collision_checker ): """ See that there are no state-creating or state-preordering collisions at this block, for this history ID. Return True if collided; False if not """ # verify no collisions against already...
python
{ "resource": "" }
q225827
state_create_is_valid
train
def state_create_is_valid( nameop ): """ Is a nameop a valid state-preorder operation? """ assert '__state_create__' in nameop, "Not tagged with @state_create" assert nameop['__state_create__'], "BUG: tagged False by @state_create" assert '__preorder__' in nameop, "No preorder" assert '__tab...
python
{ "resource": "" }
q225828
state_transition_is_valid
train
def state_transition_is_valid( nameop ): """ Is this a valid state transition? """ assert '__state_transition__' in nameop, "Not tagged with @state_transition" assert nameop['__state_transition__'], "BUG: @state_transition tagged False" assert '__history_id_key__' in nameop, "Missing __history_i...
python
{ "resource": "" }
q225829
_read_atlas_zonefile
train
def _read_atlas_zonefile( zonefile_path, zonefile_hash ): """ Read and verify an atlas zone file """ with open(zonefile_path, "rb") as f: data = f.read() # sanity check if zonefile_hash is not None: if not verify_zonefile( data, zonefile_hash ): log.debug("Corrupt ...
python
{ "resource": "" }
q225830
get_atlas_zonefile_data
train
def get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=True ): """ Get a serialized cached zonefile from local disk Return None if not found """ zonefile_path = atlas_zonefile_path(zonefile_dir, zonefile_hash) zonefile_path_legacy = atlas_zonefile_path_legacy(zonefile_dir, zonefile_has...
python
{ "resource": "" }
q225831
store_atlas_zonefile_data
train
def store_atlas_zonefile_data(zonefile_data, zonefile_dir, fsync=True): """ Store a validated zonefile. zonefile_data should be a dict. The caller should first authenticate the zonefile. Return True on success Return False on error """ if not os.path.exists(zonefile_dir): os.make...
python
{ "resource": "" }
q225832
remove_atlas_zonefile_data
train
def remove_atlas_zonefile_data( zonefile_hash, zonefile_dir ): """ Remove a cached zonefile. Idempotent; returns True if deleted or it didn't exist. Returns False on error """ if not os.path.exists(zonefile_dir): return True zonefile_path = atlas_zonefile_path( zonefile_dir, zonefil...
python
{ "resource": "" }
q225833
add_atlas_zonefile_data
train
def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True): """ Add a zone file to the atlas zonefiles Return True on success Return False on error """ rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync) if not rc: zonefile_hash = get_zonefile_data_has...
python
{ "resource": "" }
q225834
transfer_sanity_check
train
def transfer_sanity_check( name, consensus_hash ): """ Verify that data for a transfer is valid. Return True on success Raise Exception on error """ if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1): raise Exception("Name '%s' has non-base-38 characters" ...
python
{ "resource": "" }
q225835
find_transfer_consensus_hash
train
def find_transfer_consensus_hash( name_rec, block_id, vtxindex, nameop_consensus_hash ): """ Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation. @name_rec is the current name record, before this NAME_TRANSFER. @block_id is the current block height. @vtxindex is t...
python
{ "resource": "" }
q225836
canonicalize
train
def canonicalize(parsed_op): """ Get the "canonical form" of this operation, putting it into a form where it can be serialized to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases. For NAME_TRANSFER, this means: * add 'keep_data' flag """ ass...
python
{ "resource": "" }
q225837
get_bitcoind
train
def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ): """ Get or instantiate our bitcoind client. Optionally re-set the bitcoind options. """ global bitcoind if reset: bitcoind = None elif not new and bitcoind is not None: return bitcoind if new or bitcoind is None:...
python
{ "resource": "" }
q225838
get_pidfile_path
train
def get_pidfile_path(working_dir): """ Get the PID file path. """ pid_filename = virtualchain_hooks.get_virtual_chain_name() + ".pid" return os.path.join( working_dir, pid_filename )
python
{ "resource": "" }
q225839
put_pidfile
train
def put_pidfile( pidfile_path, pid ): """ Put a PID into a pidfile """ with open( pidfile_path, "w" ) as f: f.write("%s" % pid) os.fsync(f.fileno()) return
python
{ "resource": "" }
q225840
get_logfile_path
train
def get_logfile_path(working_dir): """ Get the logfile path for our service endpoint. """ logfile_filename = virtualchain_hooks.get_virtual_chain_name() + ".log" return os.path.join( working_dir, logfile_filename )
python
{ "resource": "" }
q225841
get_index_range
train
def get_index_range(working_dir): """ Get the bitcoin block index range. Mask connection failures with timeouts. Always try to reconnect. The last block will be the last block to search for names. This will be NUM_CONFIRMATIONS behind the actual last-block the cryptocurrency node knows abou...
python
{ "resource": "" }
q225842
rpc_start
train
def rpc_start( working_dir, port, subdomain_index=None, thread=True ): """ Start the global RPC server thread Returns the RPC server thread """ rpc_srv = BlockstackdRPCServer( working_dir, port, subdomain_index=subdomain_index ) log.debug("Starting RPC on port {}".format(port)) if thread: ...
python
{ "resource": "" }
q225843
rpc_chain_sync
train
def rpc_chain_sync(server_state, new_block_height, finish_time): """ Flush the global RPC server cache, and tell the rpc server that we've reached the given block height at the given time. """ rpc_srv = server_state['rpc'] if rpc_srv is not None: rpc_srv.cache_flush() rpc_srv.set...
python
{ "resource": "" }
q225844
rpc_stop
train
def rpc_stop(server_state): """ Stop the global RPC server thread """ rpc_srv = server_state['rpc'] if rpc_srv is not None: log.info("Shutting down RPC") rpc_srv.stop_server() rpc_srv.join() log.info("RPC joined") else: log.info("RPC already joined") ...
python
{ "resource": "" }
q225845
gc_stop
train
def gc_stop(): """ Stop a the optimistic GC thread """ global gc_thread if gc_thread: log.info("Shutting down GC thread") gc_thread.signal_stop() gc_thread.join() log.info("GC thread joined") gc_thread = None else: log.info("GC thread already ...
python
{ "resource": "" }
q225846
api_start
train
def api_start(working_dir, host, port, thread=True): """ Start the global API server Returns the API server thread """ api_srv = BlockstackdAPIServer( working_dir, host, port ) log.info("Starting API server on port {}".format(port)) if thread: api_srv.start() return api_srv
python
{ "resource": "" }
q225847
api_stop
train
def api_stop(server_state): """ Stop the global API server thread """ api_srv = server_state['api'] if api_srv is not None: log.info("Shutting down API") api_srv.stop_server() api_srv.join() log.info("API server joined") else: log.info("API already joined...
python
{ "resource": "" }
q225848
atlas_init
train
def atlas_init(blockstack_opts, db, recover=False, port=None): """ Start up atlas functionality """ if port is None: port = blockstack_opts['rpc_port'] # start atlas node atlas_state = None if is_atlas_enabled(blockstack_opts): atlas_seed_peers = filter( lambda x: len(x) > 0...
python
{ "resource": "" }
q225849
read_pid_file
train
def read_pid_file(pidfile_path): """ Read the PID from the PID file """ try: fin = open(pidfile_path, "r") except Exception, e: return None else: pid_data = fin.read().strip() fin.close() try: pid = int(pid_data) return pid ...
python
{ "resource": "" }
q225850
check_server_running
train
def check_server_running(pid): """ Determine if the given process is running """ if pid == os.getpid(): # special case--we're in Docker or some other kind of container # (or we got really unlucky and got the same PID twice). # this PID does not correspond to another running serve...
python
{ "resource": "" }
q225851
stop_server
train
def stop_server( working_dir, clean=False, kill=False ): """ Stop the blockstackd server. """ timeout = 1.0 dead = False for i in xrange(0, 5): # try to kill the main supervisor pid_file = get_pidfile_path(working_dir) if not os.path.exists(pid_file): dead =...
python
{ "resource": "" }
q225852
genesis_block_load
train
def genesis_block_load(module_path=None): """ Make sure the genesis block is good to go. Load and instantiate it. """ if os.environ.get('BLOCKSTACK_GENESIS_BLOCK_PATH') is not None: log.warning('Using envar-given genesis block') module_path = os.environ['BLOCKSTACK_GENESIS_BLOCK_PATH...
python
{ "resource": "" }
q225853
server_setup
train
def server_setup(working_dir, port=None, api_port=None, indexer_enabled=None, indexer_url=None, api_enabled=None, recover=False): """ Set up the server. Start all subsystems, write pid file, set up signal handlers, set up DB. Returns a server instance. """ if not is_genesis_block_instantiated():...
python
{ "resource": "" }
q225854
server_shutdown
train
def server_shutdown(server_state): """ Shut down server subsystems. Remove PID file. """ set_running( False ) # stop API servers rpc_stop(server_state) api_stop(server_state) # stop atlas node server_atlas_shutdown(server_state) # stopping GC gc_stop() # clear PID...
python
{ "resource": "" }
q225855
run_server
train
def run_server(working_dir, foreground=False, expected_snapshots=GENESIS_SNAPSHOT, port=None, api_port=None, use_api=None, use_indexer=None, indexer_url=None, recover=False): """ Run blockstackd. Optionally daemonize. Return 0 on success Return negative on error """ global rpc_server global...
python
{ "resource": "" }
q225856
setup
train
def setup(working_dir, interactive=False): """ Do one-time initialization. Call this to set up global state. """ # set up our implementation log.debug("Working dir: {}".format(working_dir)) if not os.path.exists( working_dir ): os.makedirs( working_dir, 0700 ) node_config = load...
python
{ "resource": "" }
q225857
reconfigure
train
def reconfigure(working_dir): """ Reconfigure blockstackd. """ configure(working_dir, force=True, interactive=True) print "Blockstack successfully reconfigured." sys.exit(0)
python
{ "resource": "" }
q225858
verify_database
train
def verify_database(trusted_consensus_hash, consensus_block_height, untrusted_working_dir, trusted_working_dir, start_block=None, expected_snapshots={}): """ Verify that a database is consistent with a known-good consensus hash. Return True if valid. Return False if not """ db = BlockstackDB...
python
{ "resource": "" }
q225859
check_and_set_envars
train
def check_and_set_envars( argv ): """ Go through argv and find any special command-line flags that set environment variables that affect multiple modules. If any of them are given, then set them in this process's environment and re-exec the process without the CLI flags. argv should be like sy...
python
{ "resource": "" }
q225860
load_expected_snapshots
train
def load_expected_snapshots( snapshots_path ): """ Load expected consensus hashes from a .snapshots file. Return the snapshots as a dict on success Return None on error """ # use snapshots? snapshots_path = os.path.expanduser(snapshots_path) expected_snapshots = {} # legacy chainsta...
python
{ "resource": "" }
q225861
do_genesis_block_audit
train
def do_genesis_block_audit(genesis_block_path=None, key_id=None): """ Loads and audits the genesis block, optionally using an alternative key """ signing_keys = GENESIS_BLOCK_SIGNING_KEYS if genesis_block_path is not None: # alternative genesis block genesis_block_load(genesis_block_...
python
{ "resource": "" }
q225862
setup_recovery
train
def setup_recovery(working_dir): """ Set up the recovery metadata so we can fully recover secondary state, like subdomains. """ db = get_db_state(working_dir) bitcoind_session = get_bitcoind(new=True) assert bitcoind_session is not None _, current_block = virtualchain.get_index_range('b...
python
{ "resource": "" }
q225863
check_recovery
train
def check_recovery(working_dir): """ Do we need to recover on start-up? """ recovery_start_block, recovery_end_block = get_recovery_range(working_dir) if recovery_start_block is not None and recovery_end_block is not None: local_current_block = virtualchain_hooks.get_last_block(working_dir) ...
python
{ "resource": "" }
q225864
BlockstackdRPC.success_response
train
def success_response(self, method_resp, **kw): """ Make a standard "success" response, which contains some ancilliary data. Also, detect if this node is too far behind the Bitcoin blockchain, and if so, convert this into an error message. """ resp = { ...
python
{ "resource": "" }
q225865
BlockstackdRPC.load_name_info
train
def load_name_info(self, db, name_record): """ Get some extra name information, given a db-loaded name record. Return the updated name_record """ name = str(name_record['name']) name_record = self.sanitize_rec(name_record) namespace_id = get_namespace_from_name(n...
python
{ "resource": "" }
q225866
BlockstackdRPC.get_name_DID_info
train
def get_name_DID_info(self, name): """ Get a name's DID info Returns None if not found """ db = get_db_state(self.working_dir) did_info = db.get_name_DID_info(name) if did_info is None: return {'error': 'No such name', 'http_status': 404} retu...
python
{ "resource": "" }
q225867
BlockstackdRPC.rpc_get_name_DID
train
def rpc_get_name_DID(self, name, **con_info): """ Given a name or subdomain, return its DID. """ did_info = None if check_name(name): did_info = self.get_name_DID_info(name) elif check_subdomain(name): did_info = self.get_subdomain_DID_info(name) ...
python
{ "resource": "" }
q225868
BlockstackdRPC.rpc_get_DID_record
train
def rpc_get_DID_record(self, did, **con_info): """ Given a DID, return the name or subdomain it corresponds to """ if not isinstance(did, (str,unicode)): return {'error': 'Invalid DID: not a string', 'http_status': 400} try: did_info = parse_DID(did) ...
python
{ "resource": "" }
q225869
BlockstackdRPC.rpc_get_blockstack_ops_at
train
def rpc_get_blockstack_ops_at(self, block_id, offset, count, **con_info): """ Get the name operations that occured in the given block. Does not include account operations. Returns {'nameops': [...]} on success. Returns {'error': ...} on error """ if not check_blo...
python
{ "resource": "" }
q225870
BlockstackdRPC.rpc_get_blockstack_ops_hash_at
train
def rpc_get_blockstack_ops_hash_at( self, block_id, **con_info ): """ Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error """ ...
python
{ "resource": "" }
q225871
BlockstackdRPC.get_bitcoind_info
train
def get_bitcoind_info(self): """ Get bitcoind info. Try the cache, and on cache miss, fetch from bitcoind and cache. """ cached_bitcoind_info = self.get_cached_bitcoind_info() if cached_bitcoind_info: return cached_bitcoind_info bitcoind_opts = defa...
python
{ "resource": "" }
q225872
BlockstackdRPC.get_consensus_info
train
def get_consensus_info(self): """ Get block height and consensus hash. Try the cache, and on cache miss, fetch from the db """ cached_consensus_info = self.get_cached_consensus_info() if cached_consensus_info: return cached_consensus_info db = get_db...
python
{ "resource": "" }
q225873
BlockstackdRPC.rpc_get_account_tokens
train
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_...
python
{ "resource": "" }
q225874
BlockstackdRPC.rpc_get_account_balance
train
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...
python
{ "resource": "" }
q225875
BlockstackdRPC.export_account_state
train
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']), ...
python
{ "resource": "" }
q225876
BlockstackdRPC.rpc_get_account_record
train
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...
python
{ "resource": "" }
q225877
BlockstackdRPC.rpc_get_account_at
train
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'...
python
{ "resource": "" }
q225878
BlockstackdRPC.rpc_get_consensus_hashes
train
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 ...
python
{ "resource": "" }
q225879
BlockstackdRPC.get_zonefile_data
train
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 ) ...
python
{ "resource": "" }
q225880
BlockstackdRPC.rpc_get_zonefiles_by_block
train
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...
python
{ "resource": "" }
q225881
BlockstackdRPC.peer_exchange
train
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...
python
{ "resource": "" }
q225882
BlockstackdRPC.rpc_atlas_peer_exchange
train
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...
python
{ "resource": "" }
q225883
BlockstackdRPCServer.stop_server
train
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...
python
{ "resource": "" }
q225884
get_last_block
train
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)
python
{ "resource": "" }
q225885
get_or_instantiate_db_state
train
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...
python
{ "resource": "" }
q225886
check_quirks
train
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...
python
{ "resource": "" }
q225887
sync_blockchain
train
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...
python
{ "resource": "" }
q225888
url_protocol
train
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...
python
{ "resource": "" }
q225889
make_DID
train
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...
python
{ "resource": "" }
q225890
BoundedThreadingMixIn.process_request_thread
train
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...
python
{ "resource": "" }
q225891
BoundedThreadingMixIn.get_request
train
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 ...
python
{ "resource": "" }
q225892
get_epoch_config
train
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() ...
python
{ "resource": "" }
q225893
get_epoch_namespace_lifetime_multiplier
train
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...
python
{ "resource": "" }
q225894
get_epoch_namespace_lifetime_grace_period
train
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]...
python
{ "resource": "" }
q225895
get_epoch_namespace_prices
train
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_...
python
{ "resource": "" }
q225896
op_get_opcode_name
train
def op_get_opcode_name(op_string): """ Get the name of an opcode, given the 'op' byte sequence of the operation. """ global OPCODE_NAMES # special case... if op_string == '{}:'.format(NAME_REGISTRATION): return 'NAME_RENEWAL' op = op_string[0] if op not in OPCODE_NAMES: ...
python
{ "resource": "" }
q225897
get_announce_filename
train
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
python
{ "resource": "" }
q225898
is_indexing
train
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
python
{ "resource": "" }
q225899
set_indexing
train
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: ...
python
{ "resource": "" }