id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,500 | blockstack/blockstack-core | blockstack/blockstackd.py | get_logfile_path | 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 | 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 ) | [
"def",
"get_logfile_path",
"(",
"working_dir",
")",
":",
"logfile_filename",
"=",
"virtualchain_hooks",
".",
"get_virtual_chain_name",
"(",
")",
"+",
"\".log\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"logfile_filename",
")"
] | Get the logfile path for our service endpoint. | [
"Get",
"the",
"logfile",
"path",
"for",
"our",
"service",
"endpoint",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L155-L160 |
230,501 | blockstack/blockstack-core | blockstack/blockstackd.py | get_index_range | 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 about.
"""
bitcoind_session = get_bitcoind(new=True)
assert bitcoind_session is not None
first_block = None
last_block = None
wait = 1.0
while last_block is None and is_running():
first_block, last_block = virtualchain.get_index_range('bitcoin', bitcoind_session, virtualchain_hooks, working_dir)
if first_block is None or last_block is None:
# try to reconnnect
log.error("Reconnect to bitcoind in {} seconds".format(wait))
time.sleep(wait)
wait = min(wait * 2.0 + random.random() * wait, 60)
bitcoind_session = get_bitcoind( new=True )
continue
else:
return first_block, last_block - NUM_CONFIRMATIONS
return None, None | python | 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 about.
"""
bitcoind_session = get_bitcoind(new=True)
assert bitcoind_session is not None
first_block = None
last_block = None
wait = 1.0
while last_block is None and is_running():
first_block, last_block = virtualchain.get_index_range('bitcoin', bitcoind_session, virtualchain_hooks, working_dir)
if first_block is None or last_block is None:
# try to reconnnect
log.error("Reconnect to bitcoind in {} seconds".format(wait))
time.sleep(wait)
wait = min(wait * 2.0 + random.random() * wait, 60)
bitcoind_session = get_bitcoind( new=True )
continue
else:
return first_block, last_block - NUM_CONFIRMATIONS
return None, None | [
"def",
"get_index_range",
"(",
"working_dir",
")",
":",
"bitcoind_session",
"=",
"get_bitcoind",
"(",
"new",
"=",
"True",
")",
"assert",
"bitcoind_session",
"is",
"not",
"None",
"first_block",
"=",
"None",
"last_block",
"=",
"None",
"wait",
"=",
"1.0",
"while",
"last_block",
"is",
"None",
"and",
"is_running",
"(",
")",
":",
"first_block",
",",
"last_block",
"=",
"virtualchain",
".",
"get_index_range",
"(",
"'bitcoin'",
",",
"bitcoind_session",
",",
"virtualchain_hooks",
",",
"working_dir",
")",
"if",
"first_block",
"is",
"None",
"or",
"last_block",
"is",
"None",
":",
"# try to reconnnect",
"log",
".",
"error",
"(",
"\"Reconnect to bitcoind in {} seconds\"",
".",
"format",
"(",
"wait",
")",
")",
"time",
".",
"sleep",
"(",
"wait",
")",
"wait",
"=",
"min",
"(",
"wait",
"*",
"2.0",
"+",
"random",
".",
"random",
"(",
")",
"*",
"wait",
",",
"60",
")",
"bitcoind_session",
"=",
"get_bitcoind",
"(",
"new",
"=",
"True",
")",
"continue",
"else",
":",
"return",
"first_block",
",",
"last_block",
"-",
"NUM_CONFIRMATIONS",
"return",
"None",
",",
"None"
] | 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 about. | [
"Get",
"the",
"bitcoin",
"block",
"index",
"range",
".",
"Mask",
"connection",
"failures",
"with",
"timeouts",
".",
"Always",
"try",
"to",
"reconnect",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L163-L197 |
230,502 | blockstack/blockstack-core | blockstack/blockstackd.py | rpc_start | 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:
rpc_srv.start()
return rpc_srv | python | 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:
rpc_srv.start()
return rpc_srv | [
"def",
"rpc_start",
"(",
"working_dir",
",",
"port",
",",
"subdomain_index",
"=",
"None",
",",
"thread",
"=",
"True",
")",
":",
"rpc_srv",
"=",
"BlockstackdRPCServer",
"(",
"working_dir",
",",
"port",
",",
"subdomain_index",
"=",
"subdomain_index",
")",
"log",
".",
"debug",
"(",
"\"Starting RPC on port {}\"",
".",
"format",
"(",
"port",
")",
")",
"if",
"thread",
":",
"rpc_srv",
".",
"start",
"(",
")",
"return",
"rpc_srv"
] | Start the global RPC server thread
Returns the RPC server thread | [
"Start",
"the",
"global",
"RPC",
"server",
"thread",
"Returns",
"the",
"RPC",
"server",
"thread"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2079-L2090 |
230,503 | blockstack/blockstack-core | blockstack/blockstackd.py | rpc_chain_sync | 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_last_index_time(finish_time) | python | 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_last_index_time(finish_time) | [
"def",
"rpc_chain_sync",
"(",
"server_state",
",",
"new_block_height",
",",
"finish_time",
")",
":",
"rpc_srv",
"=",
"server_state",
"[",
"'rpc'",
"]",
"if",
"rpc_srv",
"is",
"not",
"None",
":",
"rpc_srv",
".",
"cache_flush",
"(",
")",
"rpc_srv",
".",
"set_last_index_time",
"(",
"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. | [
"Flush",
"the",
"global",
"RPC",
"server",
"cache",
"and",
"tell",
"the",
"rpc",
"server",
"that",
"we",
"ve",
"reached",
"the",
"given",
"block",
"height",
"at",
"the",
"given",
"time",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2093-L2101 |
230,504 | blockstack/blockstack-core | blockstack/blockstackd.py | rpc_stop | 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")
server_state['rpc'] = None | python | 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")
server_state['rpc'] = None | [
"def",
"rpc_stop",
"(",
"server_state",
")",
":",
"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\"",
")",
"server_state",
"[",
"'rpc'",
"]",
"=",
"None"
] | Stop the global RPC server thread | [
"Stop",
"the",
"global",
"RPC",
"server",
"thread"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2104-L2119 |
230,505 | blockstack/blockstack-core | blockstack/blockstackd.py | gc_stop | 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 joined") | python | 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 joined") | [
"def",
"gc_stop",
"(",
")",
":",
"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 joined\"",
")"
] | Stop a the optimistic GC thread | [
"Stop",
"a",
"the",
"optimistic",
"GC",
"thread"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2133-L2146 |
230,506 | blockstack/blockstack-core | blockstack/blockstackd.py | api_start | 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 | 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 | [
"def",
"api_start",
"(",
"working_dir",
",",
"host",
",",
"port",
",",
"thread",
"=",
"True",
")",
":",
"api_srv",
"=",
"BlockstackdAPIServer",
"(",
"working_dir",
",",
"host",
",",
"port",
")",
"log",
".",
"info",
"(",
"\"Starting API server on port {}\"",
".",
"format",
"(",
"port",
")",
")",
"if",
"thread",
":",
"api_srv",
".",
"start",
"(",
")",
"return",
"api_srv"
] | Start the global API server
Returns the API server thread | [
"Start",
"the",
"global",
"API",
"server",
"Returns",
"the",
"API",
"server",
"thread"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2157-L2167 |
230,507 | blockstack/blockstack-core | blockstack/blockstackd.py | api_stop | 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")
server_state['api'] = None | python | 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")
server_state['api'] = None | [
"def",
"api_stop",
"(",
"server_state",
")",
":",
"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\"",
")",
"server_state",
"[",
"'api'",
"]",
"=",
"None"
] | Stop the global API server thread | [
"Stop",
"the",
"global",
"API",
"server",
"thread"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2170-L2184 |
230,508 | blockstack/blockstack-core | blockstack/blockstackd.py | atlas_init | 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, blockstack_opts['atlas_seeds'].split(","))
atlas_blacklist = filter( lambda x: len(x) > 0, blockstack_opts['atlas_blacklist'].split(","))
zonefile_dir = blockstack_opts['zonefiles']
my_hostname = blockstack_opts['atlas_hostname']
my_port = blockstack_opts['atlas_port']
initial_peer_table = atlasdb_init(blockstack_opts['atlasdb_path'], zonefile_dir, db, atlas_seed_peers, atlas_blacklist, validate=True, recover=recover)
atlas_peer_table_init(initial_peer_table)
atlas_state = atlas_node_init(my_hostname, my_port, blockstack_opts['atlasdb_path'], zonefile_dir, db.working_dir)
return atlas_state | python | 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, blockstack_opts['atlas_seeds'].split(","))
atlas_blacklist = filter( lambda x: len(x) > 0, blockstack_opts['atlas_blacklist'].split(","))
zonefile_dir = blockstack_opts['zonefiles']
my_hostname = blockstack_opts['atlas_hostname']
my_port = blockstack_opts['atlas_port']
initial_peer_table = atlasdb_init(blockstack_opts['atlasdb_path'], zonefile_dir, db, atlas_seed_peers, atlas_blacklist, validate=True, recover=recover)
atlas_peer_table_init(initial_peer_table)
atlas_state = atlas_node_init(my_hostname, my_port, blockstack_opts['atlasdb_path'], zonefile_dir, db.working_dir)
return atlas_state | [
"def",
"atlas_init",
"(",
"blockstack_opts",
",",
"db",
",",
"recover",
"=",
"False",
",",
"port",
"=",
"None",
")",
":",
"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",
",",
"blockstack_opts",
"[",
"'atlas_seeds'",
"]",
".",
"split",
"(",
"\",\"",
")",
")",
"atlas_blacklist",
"=",
"filter",
"(",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
">",
"0",
",",
"blockstack_opts",
"[",
"'atlas_blacklist'",
"]",
".",
"split",
"(",
"\",\"",
")",
")",
"zonefile_dir",
"=",
"blockstack_opts",
"[",
"'zonefiles'",
"]",
"my_hostname",
"=",
"blockstack_opts",
"[",
"'atlas_hostname'",
"]",
"my_port",
"=",
"blockstack_opts",
"[",
"'atlas_port'",
"]",
"initial_peer_table",
"=",
"atlasdb_init",
"(",
"blockstack_opts",
"[",
"'atlasdb_path'",
"]",
",",
"zonefile_dir",
",",
"db",
",",
"atlas_seed_peers",
",",
"atlas_blacklist",
",",
"validate",
"=",
"True",
",",
"recover",
"=",
"recover",
")",
"atlas_peer_table_init",
"(",
"initial_peer_table",
")",
"atlas_state",
"=",
"atlas_node_init",
"(",
"my_hostname",
",",
"my_port",
",",
"blockstack_opts",
"[",
"'atlasdb_path'",
"]",
",",
"zonefile_dir",
",",
"db",
".",
"working_dir",
")",
"return",
"atlas_state"
] | Start up atlas functionality | [
"Start",
"up",
"atlas",
"functionality"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2187-L2208 |
230,509 | blockstack/blockstack-core | blockstack/blockstackd.py | read_pid_file | 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
except:
return None | python | 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
except:
return None | [
"def",
"read_pid_file",
"(",
"pidfile_path",
")",
":",
"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",
"except",
":",
"return",
"None"
] | Read the PID from the PID file | [
"Read",
"the",
"PID",
"from",
"the",
"PID",
"file"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2220-L2238 |
230,510 | blockstack/blockstack-core | blockstack/blockstackd.py | check_server_running | 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 server, either way.
return False
try:
os.kill(pid, 0)
return True
except OSError as oe:
if oe.errno == errno.ESRCH:
return False
else:
raise | python | 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 server, either way.
return False
try:
os.kill(pid, 0)
return True
except OSError as oe:
if oe.errno == errno.ESRCH:
return False
else:
raise | [
"def",
"check_server_running",
"(",
"pid",
")",
":",
"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 server, either way.",
"return",
"False",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"0",
")",
"return",
"True",
"except",
"OSError",
"as",
"oe",
":",
"if",
"oe",
".",
"errno",
"==",
"errno",
".",
"ESRCH",
":",
"return",
"False",
"else",
":",
"raise"
] | Determine if the given process is running | [
"Determine",
"if",
"the",
"given",
"process",
"is",
"running"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2241-L2258 |
230,511 | blockstack/blockstack-core | blockstack/blockstackd.py | stop_server | 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 = True
break
pid = read_pid_file(pid_file)
if pid is not None:
try:
os.kill(pid, signal.SIGTERM)
except OSError, oe:
if oe.errno == errno.ESRCH:
# already dead
log.info("Process %s is not running" % pid)
try:
os.unlink(pid_file)
except:
pass
return
except Exception, e:
log.exception(e)
os.abort()
else:
log.info("Corrupt PID file. Please make sure all instances of this program have stopped and remove {}".format(pid_file))
os.abort()
# is it actually dead?
blockstack_opts = get_blockstack_opts()
srv = BlockstackRPCClient('localhost', blockstack_opts['rpc_port'], timeout=5, protocol='http')
try:
res = blockstack_ping(proxy=srv)
except socket.error as se:
# dead?
if se.errno == errno.ECONNREFUSED:
# couldn't connect, so infer dead
try:
os.kill(pid, 0)
log.info("Server %s is not dead yet..." % pid)
except OSError, oe:
log.info("Server %s is dead to us" % pid)
dead = True
break
else:
continue
log.info("Server %s is still running; trying again in %s seconds" % (pid, timeout))
time.sleep(timeout)
timeout *= 2
if not dead and kill:
# be sure to clean up the pidfile
log.info("Killing server %s" % pid)
clean = True
try:
os.kill(pid, signal.SIGKILL)
except Exception, e:
pass
if clean:
# blow away the pid file
try:
os.unlink(pid_file)
except:
pass
log.debug("Blockstack server stopped") | python | 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 = True
break
pid = read_pid_file(pid_file)
if pid is not None:
try:
os.kill(pid, signal.SIGTERM)
except OSError, oe:
if oe.errno == errno.ESRCH:
# already dead
log.info("Process %s is not running" % pid)
try:
os.unlink(pid_file)
except:
pass
return
except Exception, e:
log.exception(e)
os.abort()
else:
log.info("Corrupt PID file. Please make sure all instances of this program have stopped and remove {}".format(pid_file))
os.abort()
# is it actually dead?
blockstack_opts = get_blockstack_opts()
srv = BlockstackRPCClient('localhost', blockstack_opts['rpc_port'], timeout=5, protocol='http')
try:
res = blockstack_ping(proxy=srv)
except socket.error as se:
# dead?
if se.errno == errno.ECONNREFUSED:
# couldn't connect, so infer dead
try:
os.kill(pid, 0)
log.info("Server %s is not dead yet..." % pid)
except OSError, oe:
log.info("Server %s is dead to us" % pid)
dead = True
break
else:
continue
log.info("Server %s is still running; trying again in %s seconds" % (pid, timeout))
time.sleep(timeout)
timeout *= 2
if not dead and kill:
# be sure to clean up the pidfile
log.info("Killing server %s" % pid)
clean = True
try:
os.kill(pid, signal.SIGKILL)
except Exception, e:
pass
if clean:
# blow away the pid file
try:
os.unlink(pid_file)
except:
pass
log.debug("Blockstack server stopped") | [
"def",
"stop_server",
"(",
"working_dir",
",",
"clean",
"=",
"False",
",",
"kill",
"=",
"False",
")",
":",
"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",
"=",
"True",
"break",
"pid",
"=",
"read_pid_file",
"(",
"pid_file",
")",
"if",
"pid",
"is",
"not",
"None",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"except",
"OSError",
",",
"oe",
":",
"if",
"oe",
".",
"errno",
"==",
"errno",
".",
"ESRCH",
":",
"# already dead",
"log",
".",
"info",
"(",
"\"Process %s is not running\"",
"%",
"pid",
")",
"try",
":",
"os",
".",
"unlink",
"(",
"pid_file",
")",
"except",
":",
"pass",
"return",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"os",
".",
"abort",
"(",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Corrupt PID file. Please make sure all instances of this program have stopped and remove {}\"",
".",
"format",
"(",
"pid_file",
")",
")",
"os",
".",
"abort",
"(",
")",
"# is it actually dead?",
"blockstack_opts",
"=",
"get_blockstack_opts",
"(",
")",
"srv",
"=",
"BlockstackRPCClient",
"(",
"'localhost'",
",",
"blockstack_opts",
"[",
"'rpc_port'",
"]",
",",
"timeout",
"=",
"5",
",",
"protocol",
"=",
"'http'",
")",
"try",
":",
"res",
"=",
"blockstack_ping",
"(",
"proxy",
"=",
"srv",
")",
"except",
"socket",
".",
"error",
"as",
"se",
":",
"# dead?",
"if",
"se",
".",
"errno",
"==",
"errno",
".",
"ECONNREFUSED",
":",
"# couldn't connect, so infer dead",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"0",
")",
"log",
".",
"info",
"(",
"\"Server %s is not dead yet...\"",
"%",
"pid",
")",
"except",
"OSError",
",",
"oe",
":",
"log",
".",
"info",
"(",
"\"Server %s is dead to us\"",
"%",
"pid",
")",
"dead",
"=",
"True",
"break",
"else",
":",
"continue",
"log",
".",
"info",
"(",
"\"Server %s is still running; trying again in %s seconds\"",
"%",
"(",
"pid",
",",
"timeout",
")",
")",
"time",
".",
"sleep",
"(",
"timeout",
")",
"timeout",
"*=",
"2",
"if",
"not",
"dead",
"and",
"kill",
":",
"# be sure to clean up the pidfile",
"log",
".",
"info",
"(",
"\"Killing server %s\"",
"%",
"pid",
")",
"clean",
"=",
"True",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGKILL",
")",
"except",
"Exception",
",",
"e",
":",
"pass",
"if",
"clean",
":",
"# blow away the pid file",
"try",
":",
"os",
".",
"unlink",
"(",
"pid_file",
")",
"except",
":",
"pass",
"log",
".",
"debug",
"(",
"\"Blockstack server stopped\"",
")"
] | Stop the blockstackd server. | [
"Stop",
"the",
"blockstackd",
"server",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2261-L2340 |
230,512 | blockstack/blockstack-core | blockstack/blockstackd.py | genesis_block_load | 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']
genesis_block = None
genesis_block_stages = None
if module_path:
log.debug('Load genesis block from {}'.format(module_path))
genesis_block_path = module_path
try:
genesis_block_mod = imp.load_source('genesis_block', genesis_block_path)
genesis_block = genesis_block_mod.GENESIS_BLOCK
genesis_block_stages = genesis_block_mod.GENESIS_BLOCK_STAGES
if BLOCKSTACK_TEST:
print ''
print 'genesis block'
print json.dumps(genesis_block, indent=4, sort_keys=True)
print ''
except Exception as e:
log.exception(e)
log.fatal('Failed to load genesis block')
os.abort()
else:
log.debug('Load built-in genesis block')
genesis_block = get_genesis_block()
genesis_block_stages = get_genesis_block_stages()
try:
for stage in genesis_block_stages:
jsonschema.validate(GENESIS_BLOCK_SCHEMA, stage)
jsonschema.validate(GENESIS_BLOCK_SCHEMA, genesis_block)
set_genesis_block(genesis_block)
set_genesis_block_stages(genesis_block_stages)
log.debug('Genesis block has {} stages'.format(len(genesis_block_stages)))
for i, stage in enumerate(genesis_block_stages):
log.debug('Stage {} has {} row(s)'.format(i+1, len(stage['rows'])))
except Exception as e:
log.fatal("Invalid genesis block")
os.abort()
return True | python | 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']
genesis_block = None
genesis_block_stages = None
if module_path:
log.debug('Load genesis block from {}'.format(module_path))
genesis_block_path = module_path
try:
genesis_block_mod = imp.load_source('genesis_block', genesis_block_path)
genesis_block = genesis_block_mod.GENESIS_BLOCK
genesis_block_stages = genesis_block_mod.GENESIS_BLOCK_STAGES
if BLOCKSTACK_TEST:
print ''
print 'genesis block'
print json.dumps(genesis_block, indent=4, sort_keys=True)
print ''
except Exception as e:
log.exception(e)
log.fatal('Failed to load genesis block')
os.abort()
else:
log.debug('Load built-in genesis block')
genesis_block = get_genesis_block()
genesis_block_stages = get_genesis_block_stages()
try:
for stage in genesis_block_stages:
jsonschema.validate(GENESIS_BLOCK_SCHEMA, stage)
jsonschema.validate(GENESIS_BLOCK_SCHEMA, genesis_block)
set_genesis_block(genesis_block)
set_genesis_block_stages(genesis_block_stages)
log.debug('Genesis block has {} stages'.format(len(genesis_block_stages)))
for i, stage in enumerate(genesis_block_stages):
log.debug('Stage {} has {} row(s)'.format(i+1, len(stage['rows'])))
except Exception as e:
log.fatal("Invalid genesis block")
os.abort()
return True | [
"def",
"genesis_block_load",
"(",
"module_path",
"=",
"None",
")",
":",
"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'",
"]",
"genesis_block",
"=",
"None",
"genesis_block_stages",
"=",
"None",
"if",
"module_path",
":",
"log",
".",
"debug",
"(",
"'Load genesis block from {}'",
".",
"format",
"(",
"module_path",
")",
")",
"genesis_block_path",
"=",
"module_path",
"try",
":",
"genesis_block_mod",
"=",
"imp",
".",
"load_source",
"(",
"'genesis_block'",
",",
"genesis_block_path",
")",
"genesis_block",
"=",
"genesis_block_mod",
".",
"GENESIS_BLOCK",
"genesis_block_stages",
"=",
"genesis_block_mod",
".",
"GENESIS_BLOCK_STAGES",
"if",
"BLOCKSTACK_TEST",
":",
"print",
"''",
"print",
"'genesis block'",
"print",
"json",
".",
"dumps",
"(",
"genesis_block",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"print",
"''",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"fatal",
"(",
"'Failed to load genesis block'",
")",
"os",
".",
"abort",
"(",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'Load built-in genesis block'",
")",
"genesis_block",
"=",
"get_genesis_block",
"(",
")",
"genesis_block_stages",
"=",
"get_genesis_block_stages",
"(",
")",
"try",
":",
"for",
"stage",
"in",
"genesis_block_stages",
":",
"jsonschema",
".",
"validate",
"(",
"GENESIS_BLOCK_SCHEMA",
",",
"stage",
")",
"jsonschema",
".",
"validate",
"(",
"GENESIS_BLOCK_SCHEMA",
",",
"genesis_block",
")",
"set_genesis_block",
"(",
"genesis_block",
")",
"set_genesis_block_stages",
"(",
"genesis_block_stages",
")",
"log",
".",
"debug",
"(",
"'Genesis block has {} stages'",
".",
"format",
"(",
"len",
"(",
"genesis_block_stages",
")",
")",
")",
"for",
"i",
",",
"stage",
"in",
"enumerate",
"(",
"genesis_block_stages",
")",
":",
"log",
".",
"debug",
"(",
"'Stage {} has {} row(s)'",
".",
"format",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"stage",
"[",
"'rows'",
"]",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"fatal",
"(",
"\"Invalid genesis block\"",
")",
"os",
".",
"abort",
"(",
")",
"return",
"True"
] | Make sure the genesis block is good to go.
Load and instantiate it. | [
"Make",
"sure",
"the",
"genesis",
"block",
"is",
"good",
"to",
"go",
".",
"Load",
"and",
"instantiate",
"it",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2431-L2484 |
230,513 | blockstack/blockstack-core | blockstack/blockstackd.py | server_setup | 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():
# default genesis block
genesis_block_load()
blockstack_opts = get_blockstack_opts()
blockstack_api_opts = get_blockstack_api_opts()
pid_file = get_pidfile_path(working_dir)
indexer_enabled = indexer_enabled if indexer_enabled is not None else blockstack_opts['enabled']
api_enabled = api_enabled if api_enabled is not None else blockstack_api_opts['enabled']
indexer_url = indexer_url if indexer_url is not None else blockstack_api_opts.get('indexer_url', None)
# sanity check
if api_enabled and not indexer_url:
print("FATAL: no 'indexer_url' in the config file, and no --indexer_url given in the arguments")
sys.exit(1)
if port is None:
port = blockstack_opts['rpc_port']
if api_port is None:
api_port = blockstack_api_opts['api_port']
# set up signals
signal.signal( signal.SIGINT, blockstack_signal_handler )
signal.signal( signal.SIGQUIT, blockstack_signal_handler )
signal.signal( signal.SIGTERM, blockstack_signal_handler )
# put pid file
put_pidfile(pid_file, os.getpid())
# clear indexing state
set_indexing(working_dir, False)
# process overrides
if blockstack_opts['enabled'] != indexer_enabled:
log.debug("Override blockstack.enabled to {}".format(indexer_enabled))
blockstack_opts['enabled'] = indexer_enabled
set_blockstack_opts(blockstack_opts)
if blockstack_api_opts['enabled'] != api_enabled:
log.debug("Override blockstack-api.enabled to {}".format(indexer_enabled))
blockstack_api_opts['enabled'] = api_enabled
set_blockstack_api_opts(blockstack_api_opts)
if blockstack_api_opts['indexer_url'] != indexer_url:
log.debug("Override blockstack-api.indexer_url to {}".format(indexer_url))
blockstack_api_opts['indexer_url'] = indexer_url
set_blockstack_api_opts(blockstack_api_opts)
# start API servers
rpc_srv = None
api_srv = None
atlas_state = None
subdomain_state = None
if blockstack_opts['enabled']:
# get db state
db = get_or_instantiate_db_state(working_dir)
# set up atlas state, if we're an indexer
atlas_state = atlas_init(blockstack_opts, db, port=port, recover=recover)
db.close()
# set up subdomains state
subdomain_state = subdomains_init(blockstack_opts, working_dir, atlas_state)
# start atlas node
if atlas_state:
atlas_node_start(atlas_state)
# start back-plane API server
rpc_srv = rpc_start(working_dir, port, subdomain_index=subdomain_state, thread=False)
if blockstack_api_opts['enabled']:
# start public RESTful API server
api_srv = api_start(working_dir, blockstack_api_opts['api_host'], api_port, thread=False)
if rpc_srv:
rpc_srv.start()
if api_srv:
api_srv.start()
# start GC
gc_start()
set_running(True)
# clear any stale indexing state
set_indexing(working_dir, False)
log.debug("Server setup: API = {}, Indexer = {}, Indexer URL = {}".format(blockstack_api_opts['enabled'], blockstack_opts['enabled'], blockstack_api_opts['indexer_url']))
ret = {
'working_dir': working_dir,
'atlas': atlas_state,
'subdomains': subdomain_state,
'subdomains_initialized': False,
'rpc': rpc_srv,
'api': api_srv,
'pid_file': pid_file,
'port': port,
'api_port': api_port
}
return ret | python | 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():
# default genesis block
genesis_block_load()
blockstack_opts = get_blockstack_opts()
blockstack_api_opts = get_blockstack_api_opts()
pid_file = get_pidfile_path(working_dir)
indexer_enabled = indexer_enabled if indexer_enabled is not None else blockstack_opts['enabled']
api_enabled = api_enabled if api_enabled is not None else blockstack_api_opts['enabled']
indexer_url = indexer_url if indexer_url is not None else blockstack_api_opts.get('indexer_url', None)
# sanity check
if api_enabled and not indexer_url:
print("FATAL: no 'indexer_url' in the config file, and no --indexer_url given in the arguments")
sys.exit(1)
if port is None:
port = blockstack_opts['rpc_port']
if api_port is None:
api_port = blockstack_api_opts['api_port']
# set up signals
signal.signal( signal.SIGINT, blockstack_signal_handler )
signal.signal( signal.SIGQUIT, blockstack_signal_handler )
signal.signal( signal.SIGTERM, blockstack_signal_handler )
# put pid file
put_pidfile(pid_file, os.getpid())
# clear indexing state
set_indexing(working_dir, False)
# process overrides
if blockstack_opts['enabled'] != indexer_enabled:
log.debug("Override blockstack.enabled to {}".format(indexer_enabled))
blockstack_opts['enabled'] = indexer_enabled
set_blockstack_opts(blockstack_opts)
if blockstack_api_opts['enabled'] != api_enabled:
log.debug("Override blockstack-api.enabled to {}".format(indexer_enabled))
blockstack_api_opts['enabled'] = api_enabled
set_blockstack_api_opts(blockstack_api_opts)
if blockstack_api_opts['indexer_url'] != indexer_url:
log.debug("Override blockstack-api.indexer_url to {}".format(indexer_url))
blockstack_api_opts['indexer_url'] = indexer_url
set_blockstack_api_opts(blockstack_api_opts)
# start API servers
rpc_srv = None
api_srv = None
atlas_state = None
subdomain_state = None
if blockstack_opts['enabled']:
# get db state
db = get_or_instantiate_db_state(working_dir)
# set up atlas state, if we're an indexer
atlas_state = atlas_init(blockstack_opts, db, port=port, recover=recover)
db.close()
# set up subdomains state
subdomain_state = subdomains_init(blockstack_opts, working_dir, atlas_state)
# start atlas node
if atlas_state:
atlas_node_start(atlas_state)
# start back-plane API server
rpc_srv = rpc_start(working_dir, port, subdomain_index=subdomain_state, thread=False)
if blockstack_api_opts['enabled']:
# start public RESTful API server
api_srv = api_start(working_dir, blockstack_api_opts['api_host'], api_port, thread=False)
if rpc_srv:
rpc_srv.start()
if api_srv:
api_srv.start()
# start GC
gc_start()
set_running(True)
# clear any stale indexing state
set_indexing(working_dir, False)
log.debug("Server setup: API = {}, Indexer = {}, Indexer URL = {}".format(blockstack_api_opts['enabled'], blockstack_opts['enabled'], blockstack_api_opts['indexer_url']))
ret = {
'working_dir': working_dir,
'atlas': atlas_state,
'subdomains': subdomain_state,
'subdomains_initialized': False,
'rpc': rpc_srv,
'api': api_srv,
'pid_file': pid_file,
'port': port,
'api_port': api_port
}
return ret | [
"def",
"server_setup",
"(",
"working_dir",
",",
"port",
"=",
"None",
",",
"api_port",
"=",
"None",
",",
"indexer_enabled",
"=",
"None",
",",
"indexer_url",
"=",
"None",
",",
"api_enabled",
"=",
"None",
",",
"recover",
"=",
"False",
")",
":",
"if",
"not",
"is_genesis_block_instantiated",
"(",
")",
":",
"# default genesis block",
"genesis_block_load",
"(",
")",
"blockstack_opts",
"=",
"get_blockstack_opts",
"(",
")",
"blockstack_api_opts",
"=",
"get_blockstack_api_opts",
"(",
")",
"pid_file",
"=",
"get_pidfile_path",
"(",
"working_dir",
")",
"indexer_enabled",
"=",
"indexer_enabled",
"if",
"indexer_enabled",
"is",
"not",
"None",
"else",
"blockstack_opts",
"[",
"'enabled'",
"]",
"api_enabled",
"=",
"api_enabled",
"if",
"api_enabled",
"is",
"not",
"None",
"else",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
"indexer_url",
"=",
"indexer_url",
"if",
"indexer_url",
"is",
"not",
"None",
"else",
"blockstack_api_opts",
".",
"get",
"(",
"'indexer_url'",
",",
"None",
")",
"# sanity check ",
"if",
"api_enabled",
"and",
"not",
"indexer_url",
":",
"print",
"(",
"\"FATAL: no 'indexer_url' in the config file, and no --indexer_url given in the arguments\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"port",
"is",
"None",
":",
"port",
"=",
"blockstack_opts",
"[",
"'rpc_port'",
"]",
"if",
"api_port",
"is",
"None",
":",
"api_port",
"=",
"blockstack_api_opts",
"[",
"'api_port'",
"]",
"# set up signals",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"blockstack_signal_handler",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGQUIT",
",",
"blockstack_signal_handler",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"blockstack_signal_handler",
")",
"# put pid file",
"put_pidfile",
"(",
"pid_file",
",",
"os",
".",
"getpid",
"(",
")",
")",
"# clear indexing state",
"set_indexing",
"(",
"working_dir",
",",
"False",
")",
"# process overrides",
"if",
"blockstack_opts",
"[",
"'enabled'",
"]",
"!=",
"indexer_enabled",
":",
"log",
".",
"debug",
"(",
"\"Override blockstack.enabled to {}\"",
".",
"format",
"(",
"indexer_enabled",
")",
")",
"blockstack_opts",
"[",
"'enabled'",
"]",
"=",
"indexer_enabled",
"set_blockstack_opts",
"(",
"blockstack_opts",
")",
"if",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
"!=",
"api_enabled",
":",
"log",
".",
"debug",
"(",
"\"Override blockstack-api.enabled to {}\"",
".",
"format",
"(",
"indexer_enabled",
")",
")",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
"=",
"api_enabled",
"set_blockstack_api_opts",
"(",
"blockstack_api_opts",
")",
"if",
"blockstack_api_opts",
"[",
"'indexer_url'",
"]",
"!=",
"indexer_url",
":",
"log",
".",
"debug",
"(",
"\"Override blockstack-api.indexer_url to {}\"",
".",
"format",
"(",
"indexer_url",
")",
")",
"blockstack_api_opts",
"[",
"'indexer_url'",
"]",
"=",
"indexer_url",
"set_blockstack_api_opts",
"(",
"blockstack_api_opts",
")",
"# start API servers",
"rpc_srv",
"=",
"None",
"api_srv",
"=",
"None",
"atlas_state",
"=",
"None",
"subdomain_state",
"=",
"None",
"if",
"blockstack_opts",
"[",
"'enabled'",
"]",
":",
"# get db state",
"db",
"=",
"get_or_instantiate_db_state",
"(",
"working_dir",
")",
"# set up atlas state, if we're an indexer",
"atlas_state",
"=",
"atlas_init",
"(",
"blockstack_opts",
",",
"db",
",",
"port",
"=",
"port",
",",
"recover",
"=",
"recover",
")",
"db",
".",
"close",
"(",
")",
"# set up subdomains state",
"subdomain_state",
"=",
"subdomains_init",
"(",
"blockstack_opts",
",",
"working_dir",
",",
"atlas_state",
")",
"# start atlas node",
"if",
"atlas_state",
":",
"atlas_node_start",
"(",
"atlas_state",
")",
"# start back-plane API server",
"rpc_srv",
"=",
"rpc_start",
"(",
"working_dir",
",",
"port",
",",
"subdomain_index",
"=",
"subdomain_state",
",",
"thread",
"=",
"False",
")",
"if",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
":",
"# start public RESTful API server",
"api_srv",
"=",
"api_start",
"(",
"working_dir",
",",
"blockstack_api_opts",
"[",
"'api_host'",
"]",
",",
"api_port",
",",
"thread",
"=",
"False",
")",
"if",
"rpc_srv",
":",
"rpc_srv",
".",
"start",
"(",
")",
"if",
"api_srv",
":",
"api_srv",
".",
"start",
"(",
")",
"# start GC",
"gc_start",
"(",
")",
"set_running",
"(",
"True",
")",
"# clear any stale indexing state",
"set_indexing",
"(",
"working_dir",
",",
"False",
")",
"log",
".",
"debug",
"(",
"\"Server setup: API = {}, Indexer = {}, Indexer URL = {}\"",
".",
"format",
"(",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
",",
"blockstack_opts",
"[",
"'enabled'",
"]",
",",
"blockstack_api_opts",
"[",
"'indexer_url'",
"]",
")",
")",
"ret",
"=",
"{",
"'working_dir'",
":",
"working_dir",
",",
"'atlas'",
":",
"atlas_state",
",",
"'subdomains'",
":",
"subdomain_state",
",",
"'subdomains_initialized'",
":",
"False",
",",
"'rpc'",
":",
"rpc_srv",
",",
"'api'",
":",
"api_srv",
",",
"'pid_file'",
":",
"pid_file",
",",
"'port'",
":",
"port",
",",
"'api_port'",
":",
"api_port",
"}",
"return",
"ret"
] | Set up the server.
Start all subsystems, write pid file, set up signal handlers, set up DB.
Returns a server instance. | [
"Set",
"up",
"the",
"server",
".",
"Start",
"all",
"subsystems",
"write",
"pid",
"file",
"set",
"up",
"signal",
"handlers",
"set",
"up",
"DB",
".",
"Returns",
"a",
"server",
"instance",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2487-L2599 |
230,514 | blockstack/blockstack-core | blockstack/blockstackd.py | server_shutdown | 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 file
try:
if os.path.exists(server_state['pid_file']):
os.unlink(server_state['pid_file'])
except:
pass
return True | python | 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 file
try:
if os.path.exists(server_state['pid_file']):
os.unlink(server_state['pid_file'])
except:
pass
return True | [
"def",
"server_shutdown",
"(",
"server_state",
")",
":",
"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 file",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"server_state",
"[",
"'pid_file'",
"]",
")",
":",
"os",
".",
"unlink",
"(",
"server_state",
"[",
"'pid_file'",
"]",
")",
"except",
":",
"pass",
"return",
"True"
] | Shut down server subsystems.
Remove PID file. | [
"Shut",
"down",
"server",
"subsystems",
".",
"Remove",
"PID",
"file",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2614-L2638 |
230,515 | blockstack/blockstack-core | blockstack/blockstackd.py | run_server | 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 api_server
indexer_log_path = get_logfile_path(working_dir)
logfile = None
if not foreground:
if os.path.exists(indexer_log_path):
logfile = open(indexer_log_path, 'a')
else:
logfile = open(indexer_log_path, 'a+')
child_pid = daemonize(logfile)
if child_pid < 0:
log.error("Failed to daemonize: {}".format(child_pid))
return -1
if child_pid > 0:
# we're the parent
log.debug("Running in the background as PID {}".format(child_pid))
sys.exit(0)
server_state = server_setup(working_dir, port=port, api_port=api_port, indexer_enabled=use_indexer, indexer_url=indexer_url, api_enabled=use_api, recover=recover)
atexit.register(server_shutdown, server_state)
rpc_server = server_state['rpc']
blockstack_opts = get_blockstack_opts()
blockstack_api_opts = get_blockstack_api_opts()
if blockstack_opts['enabled']:
log.debug("Begin Indexing")
while is_running():
try:
running = index_blockchain(server_state, expected_snapshots=expected_snapshots)
except Exception, e:
log.exception(e)
log.error("FATAL: caught exception while indexing")
os.abort()
# wait for the next block
deadline = time.time() + REINDEX_FREQUENCY
while time.time() < deadline and is_running():
try:
time.sleep(1.0)
except:
# interrupt
break
log.debug("End Indexing")
elif blockstack_api_opts['enabled']:
log.debug("Begin serving REST requests")
while is_running():
try:
time.sleep(1.0)
except:
# interrupt
break
log.debug("End serving REST requests")
server_shutdown(server_state)
# close logfile
if logfile is not None:
logfile.flush()
logfile.close()
return 0 | python | 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 api_server
indexer_log_path = get_logfile_path(working_dir)
logfile = None
if not foreground:
if os.path.exists(indexer_log_path):
logfile = open(indexer_log_path, 'a')
else:
logfile = open(indexer_log_path, 'a+')
child_pid = daemonize(logfile)
if child_pid < 0:
log.error("Failed to daemonize: {}".format(child_pid))
return -1
if child_pid > 0:
# we're the parent
log.debug("Running in the background as PID {}".format(child_pid))
sys.exit(0)
server_state = server_setup(working_dir, port=port, api_port=api_port, indexer_enabled=use_indexer, indexer_url=indexer_url, api_enabled=use_api, recover=recover)
atexit.register(server_shutdown, server_state)
rpc_server = server_state['rpc']
blockstack_opts = get_blockstack_opts()
blockstack_api_opts = get_blockstack_api_opts()
if blockstack_opts['enabled']:
log.debug("Begin Indexing")
while is_running():
try:
running = index_blockchain(server_state, expected_snapshots=expected_snapshots)
except Exception, e:
log.exception(e)
log.error("FATAL: caught exception while indexing")
os.abort()
# wait for the next block
deadline = time.time() + REINDEX_FREQUENCY
while time.time() < deadline and is_running():
try:
time.sleep(1.0)
except:
# interrupt
break
log.debug("End Indexing")
elif blockstack_api_opts['enabled']:
log.debug("Begin serving REST requests")
while is_running():
try:
time.sleep(1.0)
except:
# interrupt
break
log.debug("End serving REST requests")
server_shutdown(server_state)
# close logfile
if logfile is not None:
logfile.flush()
logfile.close()
return 0 | [
"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",
")",
":",
"global",
"rpc_server",
"global",
"api_server",
"indexer_log_path",
"=",
"get_logfile_path",
"(",
"working_dir",
")",
"logfile",
"=",
"None",
"if",
"not",
"foreground",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"indexer_log_path",
")",
":",
"logfile",
"=",
"open",
"(",
"indexer_log_path",
",",
"'a'",
")",
"else",
":",
"logfile",
"=",
"open",
"(",
"indexer_log_path",
",",
"'a+'",
")",
"child_pid",
"=",
"daemonize",
"(",
"logfile",
")",
"if",
"child_pid",
"<",
"0",
":",
"log",
".",
"error",
"(",
"\"Failed to daemonize: {}\"",
".",
"format",
"(",
"child_pid",
")",
")",
"return",
"-",
"1",
"if",
"child_pid",
">",
"0",
":",
"# we're the parent",
"log",
".",
"debug",
"(",
"\"Running in the background as PID {}\"",
".",
"format",
"(",
"child_pid",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"server_state",
"=",
"server_setup",
"(",
"working_dir",
",",
"port",
"=",
"port",
",",
"api_port",
"=",
"api_port",
",",
"indexer_enabled",
"=",
"use_indexer",
",",
"indexer_url",
"=",
"indexer_url",
",",
"api_enabled",
"=",
"use_api",
",",
"recover",
"=",
"recover",
")",
"atexit",
".",
"register",
"(",
"server_shutdown",
",",
"server_state",
")",
"rpc_server",
"=",
"server_state",
"[",
"'rpc'",
"]",
"blockstack_opts",
"=",
"get_blockstack_opts",
"(",
")",
"blockstack_api_opts",
"=",
"get_blockstack_api_opts",
"(",
")",
"if",
"blockstack_opts",
"[",
"'enabled'",
"]",
":",
"log",
".",
"debug",
"(",
"\"Begin Indexing\"",
")",
"while",
"is_running",
"(",
")",
":",
"try",
":",
"running",
"=",
"index_blockchain",
"(",
"server_state",
",",
"expected_snapshots",
"=",
"expected_snapshots",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: caught exception while indexing\"",
")",
"os",
".",
"abort",
"(",
")",
"# wait for the next block",
"deadline",
"=",
"time",
".",
"time",
"(",
")",
"+",
"REINDEX_FREQUENCY",
"while",
"time",
".",
"time",
"(",
")",
"<",
"deadline",
"and",
"is_running",
"(",
")",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"1.0",
")",
"except",
":",
"# interrupt",
"break",
"log",
".",
"debug",
"(",
"\"End Indexing\"",
")",
"elif",
"blockstack_api_opts",
"[",
"'enabled'",
"]",
":",
"log",
".",
"debug",
"(",
"\"Begin serving REST requests\"",
")",
"while",
"is_running",
"(",
")",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"1.0",
")",
"except",
":",
"# interrupt",
"break",
"log",
".",
"debug",
"(",
"\"End serving REST requests\"",
")",
"server_shutdown",
"(",
"server_state",
")",
"# close logfile",
"if",
"logfile",
"is",
"not",
"None",
":",
"logfile",
".",
"flush",
"(",
")",
"logfile",
".",
"close",
"(",
")",
"return",
"0"
] | Run blockstackd. Optionally daemonize.
Return 0 on success
Return negative on error | [
"Run",
"blockstackd",
".",
"Optionally",
"daemonize",
".",
"Return",
"0",
"on",
"success",
"Return",
"negative",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2641-L2716 |
230,516 | blockstack/blockstack-core | blockstack/blockstackd.py | setup | 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_configuration(working_dir)
if node_config is None:
sys.exit(1)
log.debug("config\n{}".format(json.dumps(node_config, indent=4, sort_keys=True)))
return node_config | python | 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_configuration(working_dir)
if node_config is None:
sys.exit(1)
log.debug("config\n{}".format(json.dumps(node_config, indent=4, sort_keys=True)))
return node_config | [
"def",
"setup",
"(",
"working_dir",
",",
"interactive",
"=",
"False",
")",
":",
"# 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_configuration",
"(",
"working_dir",
")",
"if",
"node_config",
"is",
"None",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"log",
".",
"debug",
"(",
"\"config\\n{}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"node_config",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
")",
")",
"return",
"node_config"
] | Do one-time initialization.
Call this to set up global state. | [
"Do",
"one",
"-",
"time",
"initialization",
".",
"Call",
"this",
"to",
"set",
"up",
"global",
"state",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2719-L2734 |
230,517 | blockstack/blockstack-core | blockstack/blockstackd.py | reconfigure | def reconfigure(working_dir):
"""
Reconfigure blockstackd.
"""
configure(working_dir, force=True, interactive=True)
print "Blockstack successfully reconfigured."
sys.exit(0) | python | def reconfigure(working_dir):
"""
Reconfigure blockstackd.
"""
configure(working_dir, force=True, interactive=True)
print "Blockstack successfully reconfigured."
sys.exit(0) | [
"def",
"reconfigure",
"(",
"working_dir",
")",
":",
"configure",
"(",
"working_dir",
",",
"force",
"=",
"True",
",",
"interactive",
"=",
"True",
")",
"print",
"\"Blockstack successfully reconfigured.\"",
"sys",
".",
"exit",
"(",
"0",
")"
] | Reconfigure blockstackd. | [
"Reconfigure",
"blockstackd",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2737-L2743 |
230,518 | blockstack/blockstack-core | blockstack/blockstackd.py | verify_database | 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.get_readwrite_instance(trusted_working_dir)
consensus_impl = virtualchain_hooks
return virtualchain.state_engine_verify(trusted_consensus_hash, consensus_block_height, consensus_impl, untrusted_working_dir, db, start_block=start_block, expected_snapshots=expected_snapshots) | python | 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.get_readwrite_instance(trusted_working_dir)
consensus_impl = virtualchain_hooks
return virtualchain.state_engine_verify(trusted_consensus_hash, consensus_block_height, consensus_impl, untrusted_working_dir, db, start_block=start_block, expected_snapshots=expected_snapshots) | [
"def",
"verify_database",
"(",
"trusted_consensus_hash",
",",
"consensus_block_height",
",",
"untrusted_working_dir",
",",
"trusted_working_dir",
",",
"start_block",
"=",
"None",
",",
"expected_snapshots",
"=",
"{",
"}",
")",
":",
"db",
"=",
"BlockstackDB",
".",
"get_readwrite_instance",
"(",
"trusted_working_dir",
")",
"consensus_impl",
"=",
"virtualchain_hooks",
"return",
"virtualchain",
".",
"state_engine_verify",
"(",
"trusted_consensus_hash",
",",
"consensus_block_height",
",",
"consensus_impl",
",",
"untrusted_working_dir",
",",
"db",
",",
"start_block",
"=",
"start_block",
",",
"expected_snapshots",
"=",
"expected_snapshots",
")"
] | Verify that a database is consistent with a
known-good consensus hash.
Return True if valid.
Return False if not | [
"Verify",
"that",
"a",
"database",
"is",
"consistent",
"with",
"a",
"known",
"-",
"good",
"consensus",
"hash",
".",
"Return",
"True",
"if",
"valid",
".",
"Return",
"False",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2746-L2755 |
230,519 | blockstack/blockstack-core | blockstack/blockstackd.py | check_and_set_envars | 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 sys.argv: argv[0] is the binary
Does not return on re-exec.
Returns {args} on success
Returns False on error.
"""
special_flags = {
'--debug': {
'arg': False,
'envar': 'BLOCKSTACK_DEBUG',
'exec': True,
},
'--verbose': {
'arg': False,
'envar': 'BLOCKSTACK_DEBUG',
'exec': True,
},
'--testnet-id': {
'arg': True,
'envar': 'BLOCKSTACK_TESTNET_ID',
'exec': True,
},
'--testnet-start-block': {
'arg': True,
'envar': 'BLOCKSTACK_TESTNET_START_BLOCK',
'exec': True,
},
'--working_dir': {
'arg': True,
'argname': 'working_dir',
'exec': False,
},
'--working-dir': {
'arg': True,
'argname': 'working_dir',
'exec': False,
},
}
cli_envs = {}
cli_args = {}
new_argv = []
stripped_argv = []
do_exec = False
i = 0
while i < len(argv):
arg = argv[i]
value = None
for special_flag in special_flags.keys():
if not arg.startswith(special_flag):
continue
if special_flags[special_flag]['arg']:
if '=' in arg:
argparts = arg.split("=")
value_parts = argparts[1:]
arg = argparts[0]
value = '='.join(value_parts)
elif i + 1 < len(argv):
value = argv[i+1]
i += 1
else:
print >> sys.stderr, "%s requires an argument" % special_flag
return False
else:
# just set
value = "1"
break
i += 1
if value is not None:
if 'envar' in special_flags[special_flag]:
# recognized
cli_envs[ special_flags[special_flag]['envar'] ] = value
if 'argname' in special_flags[special_flag]:
# recognized as special argument
cli_args[ special_flags[special_flag]['argname'] ] = value
new_argv.append(arg)
new_argv.append(value)
if special_flags[special_flag]['exec']:
do_exec = True
else:
# not recognized
new_argv.append(arg)
stripped_argv.append(arg)
if do_exec:
# re-exec
for cli_env, cli_env_value in cli_envs.items():
os.environ[cli_env] = cli_env_value
if os.environ.get("BLOCKSTACK_DEBUG") is not None:
print "Re-exec as {}".format(" ".join(new_argv))
os.execv(new_argv[0], new_argv)
log.debug("Stripped argv: {}".format(' '.join(stripped_argv)))
return cli_args, stripped_argv | python | 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 sys.argv: argv[0] is the binary
Does not return on re-exec.
Returns {args} on success
Returns False on error.
"""
special_flags = {
'--debug': {
'arg': False,
'envar': 'BLOCKSTACK_DEBUG',
'exec': True,
},
'--verbose': {
'arg': False,
'envar': 'BLOCKSTACK_DEBUG',
'exec': True,
},
'--testnet-id': {
'arg': True,
'envar': 'BLOCKSTACK_TESTNET_ID',
'exec': True,
},
'--testnet-start-block': {
'arg': True,
'envar': 'BLOCKSTACK_TESTNET_START_BLOCK',
'exec': True,
},
'--working_dir': {
'arg': True,
'argname': 'working_dir',
'exec': False,
},
'--working-dir': {
'arg': True,
'argname': 'working_dir',
'exec': False,
},
}
cli_envs = {}
cli_args = {}
new_argv = []
stripped_argv = []
do_exec = False
i = 0
while i < len(argv):
arg = argv[i]
value = None
for special_flag in special_flags.keys():
if not arg.startswith(special_flag):
continue
if special_flags[special_flag]['arg']:
if '=' in arg:
argparts = arg.split("=")
value_parts = argparts[1:]
arg = argparts[0]
value = '='.join(value_parts)
elif i + 1 < len(argv):
value = argv[i+1]
i += 1
else:
print >> sys.stderr, "%s requires an argument" % special_flag
return False
else:
# just set
value = "1"
break
i += 1
if value is not None:
if 'envar' in special_flags[special_flag]:
# recognized
cli_envs[ special_flags[special_flag]['envar'] ] = value
if 'argname' in special_flags[special_flag]:
# recognized as special argument
cli_args[ special_flags[special_flag]['argname'] ] = value
new_argv.append(arg)
new_argv.append(value)
if special_flags[special_flag]['exec']:
do_exec = True
else:
# not recognized
new_argv.append(arg)
stripped_argv.append(arg)
if do_exec:
# re-exec
for cli_env, cli_env_value in cli_envs.items():
os.environ[cli_env] = cli_env_value
if os.environ.get("BLOCKSTACK_DEBUG") is not None:
print "Re-exec as {}".format(" ".join(new_argv))
os.execv(new_argv[0], new_argv)
log.debug("Stripped argv: {}".format(' '.join(stripped_argv)))
return cli_args, stripped_argv | [
"def",
"check_and_set_envars",
"(",
"argv",
")",
":",
"special_flags",
"=",
"{",
"'--debug'",
":",
"{",
"'arg'",
":",
"False",
",",
"'envar'",
":",
"'BLOCKSTACK_DEBUG'",
",",
"'exec'",
":",
"True",
",",
"}",
",",
"'--verbose'",
":",
"{",
"'arg'",
":",
"False",
",",
"'envar'",
":",
"'BLOCKSTACK_DEBUG'",
",",
"'exec'",
":",
"True",
",",
"}",
",",
"'--testnet-id'",
":",
"{",
"'arg'",
":",
"True",
",",
"'envar'",
":",
"'BLOCKSTACK_TESTNET_ID'",
",",
"'exec'",
":",
"True",
",",
"}",
",",
"'--testnet-start-block'",
":",
"{",
"'arg'",
":",
"True",
",",
"'envar'",
":",
"'BLOCKSTACK_TESTNET_START_BLOCK'",
",",
"'exec'",
":",
"True",
",",
"}",
",",
"'--working_dir'",
":",
"{",
"'arg'",
":",
"True",
",",
"'argname'",
":",
"'working_dir'",
",",
"'exec'",
":",
"False",
",",
"}",
",",
"'--working-dir'",
":",
"{",
"'arg'",
":",
"True",
",",
"'argname'",
":",
"'working_dir'",
",",
"'exec'",
":",
"False",
",",
"}",
",",
"}",
"cli_envs",
"=",
"{",
"}",
"cli_args",
"=",
"{",
"}",
"new_argv",
"=",
"[",
"]",
"stripped_argv",
"=",
"[",
"]",
"do_exec",
"=",
"False",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"argv",
")",
":",
"arg",
"=",
"argv",
"[",
"i",
"]",
"value",
"=",
"None",
"for",
"special_flag",
"in",
"special_flags",
".",
"keys",
"(",
")",
":",
"if",
"not",
"arg",
".",
"startswith",
"(",
"special_flag",
")",
":",
"continue",
"if",
"special_flags",
"[",
"special_flag",
"]",
"[",
"'arg'",
"]",
":",
"if",
"'='",
"in",
"arg",
":",
"argparts",
"=",
"arg",
".",
"split",
"(",
"\"=\"",
")",
"value_parts",
"=",
"argparts",
"[",
"1",
":",
"]",
"arg",
"=",
"argparts",
"[",
"0",
"]",
"value",
"=",
"'='",
".",
"join",
"(",
"value_parts",
")",
"elif",
"i",
"+",
"1",
"<",
"len",
"(",
"argv",
")",
":",
"value",
"=",
"argv",
"[",
"i",
"+",
"1",
"]",
"i",
"+=",
"1",
"else",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"%s requires an argument\"",
"%",
"special_flag",
"return",
"False",
"else",
":",
"# just set",
"value",
"=",
"\"1\"",
"break",
"i",
"+=",
"1",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"'envar'",
"in",
"special_flags",
"[",
"special_flag",
"]",
":",
"# recognized",
"cli_envs",
"[",
"special_flags",
"[",
"special_flag",
"]",
"[",
"'envar'",
"]",
"]",
"=",
"value",
"if",
"'argname'",
"in",
"special_flags",
"[",
"special_flag",
"]",
":",
"# recognized as special argument",
"cli_args",
"[",
"special_flags",
"[",
"special_flag",
"]",
"[",
"'argname'",
"]",
"]",
"=",
"value",
"new_argv",
".",
"append",
"(",
"arg",
")",
"new_argv",
".",
"append",
"(",
"value",
")",
"if",
"special_flags",
"[",
"special_flag",
"]",
"[",
"'exec'",
"]",
":",
"do_exec",
"=",
"True",
"else",
":",
"# not recognized",
"new_argv",
".",
"append",
"(",
"arg",
")",
"stripped_argv",
".",
"append",
"(",
"arg",
")",
"if",
"do_exec",
":",
"# re-exec",
"for",
"cli_env",
",",
"cli_env_value",
"in",
"cli_envs",
".",
"items",
"(",
")",
":",
"os",
".",
"environ",
"[",
"cli_env",
"]",
"=",
"cli_env_value",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"BLOCKSTACK_DEBUG\"",
")",
"is",
"not",
"None",
":",
"print",
"\"Re-exec as {}\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"new_argv",
")",
")",
"os",
".",
"execv",
"(",
"new_argv",
"[",
"0",
"]",
",",
"new_argv",
")",
"log",
".",
"debug",
"(",
"\"Stripped argv: {}\"",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"stripped_argv",
")",
")",
")",
"return",
"cli_args",
",",
"stripped_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 sys.argv: argv[0] is the binary
Does not return on re-exec.
Returns {args} on success
Returns False on error. | [
"Go",
"through",
"argv",
"and",
"find",
"any",
"special",
"command",
"-",
"line",
"flags",
"that",
"set",
"environment",
"variables",
"that",
"affect",
"multiple",
"modules",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2758-L2875 |
230,520 | blockstack/blockstack-core | blockstack/blockstackd.py | load_expected_snapshots | 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 chainstate?
try:
with open(snapshots_path, "r") as f:
snapshots_json = f.read()
snapshots_data = json.loads(snapshots_json)
assert 'snapshots' in snapshots_data.keys(), "Not a valid snapshots file"
# extract snapshots: map int to consensus hash
for (block_id_str, consensus_hash) in snapshots_data['snapshots'].items():
expected_snapshots[ int(block_id_str) ] = str(consensus_hash)
log.debug("Loaded expected snapshots from legacy JSON {}; {} entries".format(snapshots_path, len(expected_snapshots)))
return expected_snapshots
except ValueError as ve:
log.debug("Snapshots file {} is not JSON".format(snapshots_path))
except Exception as e:
if os.environ.get('BLOCKSTACK_DEBUG') == '1':
log.exception(e)
log.debug("Failed to read expected snapshots from '{}'".format(snapshots_path))
return None
try:
# sqlite3 db?
db_con = virtualchain.StateEngine.db_connect(snapshots_path)
expected_snapshots = virtualchain.StateEngine.get_consensus_hashes(None, None, db_con=db_con, completeness_check=False)
log.debug("Loaded expected snapshots from chainstate DB {}, {} entries".format(snapshots_path, len(expected_snapshots)))
return expected_snapshots
except:
log.debug("{} does not appear to be a chainstate DB".format(snapshots_path))
return None | python | 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 chainstate?
try:
with open(snapshots_path, "r") as f:
snapshots_json = f.read()
snapshots_data = json.loads(snapshots_json)
assert 'snapshots' in snapshots_data.keys(), "Not a valid snapshots file"
# extract snapshots: map int to consensus hash
for (block_id_str, consensus_hash) in snapshots_data['snapshots'].items():
expected_snapshots[ int(block_id_str) ] = str(consensus_hash)
log.debug("Loaded expected snapshots from legacy JSON {}; {} entries".format(snapshots_path, len(expected_snapshots)))
return expected_snapshots
except ValueError as ve:
log.debug("Snapshots file {} is not JSON".format(snapshots_path))
except Exception as e:
if os.environ.get('BLOCKSTACK_DEBUG') == '1':
log.exception(e)
log.debug("Failed to read expected snapshots from '{}'".format(snapshots_path))
return None
try:
# sqlite3 db?
db_con = virtualchain.StateEngine.db_connect(snapshots_path)
expected_snapshots = virtualchain.StateEngine.get_consensus_hashes(None, None, db_con=db_con, completeness_check=False)
log.debug("Loaded expected snapshots from chainstate DB {}, {} entries".format(snapshots_path, len(expected_snapshots)))
return expected_snapshots
except:
log.debug("{} does not appear to be a chainstate DB".format(snapshots_path))
return None | [
"def",
"load_expected_snapshots",
"(",
"snapshots_path",
")",
":",
"# use snapshots?",
"snapshots_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"snapshots_path",
")",
"expected_snapshots",
"=",
"{",
"}",
"# legacy chainstate?",
"try",
":",
"with",
"open",
"(",
"snapshots_path",
",",
"\"r\"",
")",
"as",
"f",
":",
"snapshots_json",
"=",
"f",
".",
"read",
"(",
")",
"snapshots_data",
"=",
"json",
".",
"loads",
"(",
"snapshots_json",
")",
"assert",
"'snapshots'",
"in",
"snapshots_data",
".",
"keys",
"(",
")",
",",
"\"Not a valid snapshots file\"",
"# extract snapshots: map int to consensus hash",
"for",
"(",
"block_id_str",
",",
"consensus_hash",
")",
"in",
"snapshots_data",
"[",
"'snapshots'",
"]",
".",
"items",
"(",
")",
":",
"expected_snapshots",
"[",
"int",
"(",
"block_id_str",
")",
"]",
"=",
"str",
"(",
"consensus_hash",
")",
"log",
".",
"debug",
"(",
"\"Loaded expected snapshots from legacy JSON {}; {} entries\"",
".",
"format",
"(",
"snapshots_path",
",",
"len",
"(",
"expected_snapshots",
")",
")",
")",
"return",
"expected_snapshots",
"except",
"ValueError",
"as",
"ve",
":",
"log",
".",
"debug",
"(",
"\"Snapshots file {} is not JSON\"",
".",
"format",
"(",
"snapshots_path",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'BLOCKSTACK_DEBUG'",
")",
"==",
"'1'",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"debug",
"(",
"\"Failed to read expected snapshots from '{}'\"",
".",
"format",
"(",
"snapshots_path",
")",
")",
"return",
"None",
"try",
":",
"# sqlite3 db?",
"db_con",
"=",
"virtualchain",
".",
"StateEngine",
".",
"db_connect",
"(",
"snapshots_path",
")",
"expected_snapshots",
"=",
"virtualchain",
".",
"StateEngine",
".",
"get_consensus_hashes",
"(",
"None",
",",
"None",
",",
"db_con",
"=",
"db_con",
",",
"completeness_check",
"=",
"False",
")",
"log",
".",
"debug",
"(",
"\"Loaded expected snapshots from chainstate DB {}, {} entries\"",
".",
"format",
"(",
"snapshots_path",
",",
"len",
"(",
"expected_snapshots",
")",
")",
")",
"return",
"expected_snapshots",
"except",
":",
"log",
".",
"debug",
"(",
"\"{} does not appear to be a chainstate DB\"",
".",
"format",
"(",
"snapshots_path",
")",
")",
"return",
"None"
] | Load expected consensus hashes from a .snapshots file.
Return the snapshots as a dict on success
Return None on error | [
"Load",
"expected",
"consensus",
"hashes",
"from",
"a",
".",
"snapshots",
"file",
".",
"Return",
"the",
"snapshots",
"as",
"a",
"dict",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2878-L2923 |
230,521 | blockstack/blockstack-core | blockstack/blockstackd.py | do_genesis_block_audit | 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_path)
if key_id is not None:
# alternative signing key
gpg2_path = find_gpg2()
assert gpg2_path, 'You need to install gpg2'
p = subprocess.Popen([gpg2_path, '-a', '--export', key_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
log.error('Failed to load key {}\n{}'.format(key_id, err))
return False
signing_keys = { key_id: out.strip() }
res = genesis_block_audit(get_genesis_block_stages(), key_bundle=signing_keys)
if not res:
log.error('Genesis block is NOT signed by {}'.format(', '.join(signing_keys.keys())))
return False
return True | python | 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_path)
if key_id is not None:
# alternative signing key
gpg2_path = find_gpg2()
assert gpg2_path, 'You need to install gpg2'
p = subprocess.Popen([gpg2_path, '-a', '--export', key_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
log.error('Failed to load key {}\n{}'.format(key_id, err))
return False
signing_keys = { key_id: out.strip() }
res = genesis_block_audit(get_genesis_block_stages(), key_bundle=signing_keys)
if not res:
log.error('Genesis block is NOT signed by {}'.format(', '.join(signing_keys.keys())))
return False
return True | [
"def",
"do_genesis_block_audit",
"(",
"genesis_block_path",
"=",
"None",
",",
"key_id",
"=",
"None",
")",
":",
"signing_keys",
"=",
"GENESIS_BLOCK_SIGNING_KEYS",
"if",
"genesis_block_path",
"is",
"not",
"None",
":",
"# alternative genesis block",
"genesis_block_load",
"(",
"genesis_block_path",
")",
"if",
"key_id",
"is",
"not",
"None",
":",
"# alternative signing key",
"gpg2_path",
"=",
"find_gpg2",
"(",
")",
"assert",
"gpg2_path",
",",
"'You need to install gpg2'",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"gpg2_path",
",",
"'-a'",
",",
"'--export'",
",",
"key_id",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"!=",
"0",
":",
"log",
".",
"error",
"(",
"'Failed to load key {}\\n{}'",
".",
"format",
"(",
"key_id",
",",
"err",
")",
")",
"return",
"False",
"signing_keys",
"=",
"{",
"key_id",
":",
"out",
".",
"strip",
"(",
")",
"}",
"res",
"=",
"genesis_block_audit",
"(",
"get_genesis_block_stages",
"(",
")",
",",
"key_bundle",
"=",
"signing_keys",
")",
"if",
"not",
"res",
":",
"log",
".",
"error",
"(",
"'Genesis block is NOT signed by {}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"signing_keys",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"False",
"return",
"True"
] | Loads and audits the genesis block, optionally using an alternative key | [
"Loads",
"and",
"audits",
"the",
"genesis",
"block",
"optionally",
"using",
"an",
"alternative",
"key"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2926-L2952 |
230,522 | blockstack/blockstack-core | blockstack/blockstackd.py | setup_recovery | 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('bitcoin', bitcoind_session, virtualchain_hooks, working_dir)
assert current_block, 'Failed to connect to bitcoind'
set_recovery_range(working_dir, db.lastblock, current_block - NUM_CONFIRMATIONS)
return True | python | 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('bitcoin', bitcoind_session, virtualchain_hooks, working_dir)
assert current_block, 'Failed to connect to bitcoind'
set_recovery_range(working_dir, db.lastblock, current_block - NUM_CONFIRMATIONS)
return True | [
"def",
"setup_recovery",
"(",
"working_dir",
")",
":",
"db",
"=",
"get_db_state",
"(",
"working_dir",
")",
"bitcoind_session",
"=",
"get_bitcoind",
"(",
"new",
"=",
"True",
")",
"assert",
"bitcoind_session",
"is",
"not",
"None",
"_",
",",
"current_block",
"=",
"virtualchain",
".",
"get_index_range",
"(",
"'bitcoin'",
",",
"bitcoind_session",
",",
"virtualchain_hooks",
",",
"working_dir",
")",
"assert",
"current_block",
",",
"'Failed to connect to bitcoind'",
"set_recovery_range",
"(",
"working_dir",
",",
"db",
".",
"lastblock",
",",
"current_block",
"-",
"NUM_CONFIRMATIONS",
")",
"return",
"True"
] | Set up the recovery metadata so we can fully recover secondary state,
like subdomains. | [
"Set",
"up",
"the",
"recovery",
"metadata",
"so",
"we",
"can",
"fully",
"recover",
"secondary",
"state",
"like",
"subdomains",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2954-L2967 |
230,523 | blockstack/blockstack-core | blockstack/blockstackd.py | check_recovery | 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)
if local_current_block <= recovery_end_block:
return True
# otherwise, we're outside the recovery range and we can clear it
log.debug('Chain state is at block {}, and is outside the recovery window {}-{}'.format(local_current_block, recovery_start_block, recovery_end_block))
clear_recovery_range(working_dir)
return False
else:
# not recovering
return False | python | 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)
if local_current_block <= recovery_end_block:
return True
# otherwise, we're outside the recovery range and we can clear it
log.debug('Chain state is at block {}, and is outside the recovery window {}-{}'.format(local_current_block, recovery_start_block, recovery_end_block))
clear_recovery_range(working_dir)
return False
else:
# not recovering
return False | [
"def",
"check_recovery",
"(",
"working_dir",
")",
":",
"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",
")",
"if",
"local_current_block",
"<=",
"recovery_end_block",
":",
"return",
"True",
"# otherwise, we're outside the recovery range and we can clear it",
"log",
".",
"debug",
"(",
"'Chain state is at block {}, and is outside the recovery window {}-{}'",
".",
"format",
"(",
"local_current_block",
",",
"recovery_start_block",
",",
"recovery_end_block",
")",
")",
"clear_recovery_range",
"(",
"working_dir",
")",
"return",
"False",
"else",
":",
"# not recovering",
"return",
"False"
] | Do we need to recover on start-up? | [
"Do",
"we",
"need",
"to",
"recover",
"on",
"start",
"-",
"up?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2970-L2987 |
230,524 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.success_response | 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 = {
'status': True,
'indexing': config.is_indexing(self.working_dir),
'lastblock': virtualchain_hooks.get_last_block(self.working_dir),
}
resp.update(kw)
resp.update(method_resp)
if self.is_stale():
# our state is stale
resp['stale'] = True
resp['warning'] = 'Daemon has not reindexed since {}'.format(self.last_indexing_time)
return resp | python | 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 = {
'status': True,
'indexing': config.is_indexing(self.working_dir),
'lastblock': virtualchain_hooks.get_last_block(self.working_dir),
}
resp.update(kw)
resp.update(method_resp)
if self.is_stale():
# our state is stale
resp['stale'] = True
resp['warning'] = 'Daemon has not reindexed since {}'.format(self.last_indexing_time)
return resp | [
"def",
"success_response",
"(",
"self",
",",
"method_resp",
",",
"*",
"*",
"kw",
")",
":",
"resp",
"=",
"{",
"'status'",
":",
"True",
",",
"'indexing'",
":",
"config",
".",
"is_indexing",
"(",
"self",
".",
"working_dir",
")",
",",
"'lastblock'",
":",
"virtualchain_hooks",
".",
"get_last_block",
"(",
"self",
".",
"working_dir",
")",
",",
"}",
"resp",
".",
"update",
"(",
"kw",
")",
"resp",
".",
"update",
"(",
"method_resp",
")",
"if",
"self",
".",
"is_stale",
"(",
")",
":",
"# our state is stale",
"resp",
"[",
"'stale'",
"]",
"=",
"True",
"resp",
"[",
"'warning'",
"]",
"=",
"'Daemon has not reindexed since {}'",
".",
"format",
"(",
"self",
".",
"last_indexing_time",
")",
"return",
"resp"
] | 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. | [
"Make",
"a",
"standard",
"success",
"response",
"which",
"contains",
"some",
"ancilliary",
"data",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L515-L537 |
230,525 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.load_name_info | 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(name)
namespace_record = db.get_namespace(namespace_id, include_history=False)
if namespace_record is None:
namespace_record = db.get_namespace_reveal(namespace_id, include_history=False)
if namespace_record is None:
# name can't exist (this can be arrived at if we're resolving a DID)
return None
# when does this name expire (if it expires)?
if namespace_record['lifetime'] != NAMESPACE_LIFE_INFINITE:
deadlines = BlockstackDB.get_name_deadlines(name_record, namespace_record, db.lastblock)
if deadlines is not None:
name_record['expire_block'] = deadlines['expire_block']
name_record['renewal_deadline'] = deadlines['renewal_deadline']
else:
# only possible if namespace is not yet ready
name_record['expire_block'] = -1
name_record['renewal_deadline'] = -1
else:
name_record['expire_block'] = -1
name_record['renewal_deadline'] = -1
if name_record['expire_block'] > 0 and name_record['expire_block'] <= db.lastblock:
name_record['expired'] = True
else:
name_record['expired'] = False
# try to get the zonefile as well
if 'value_hash' in name_record and name_record['value_hash'] is not None:
conf = get_blockstack_opts()
if is_atlas_enabled(conf):
zfdata = self.get_zonefile_data(name_record['value_hash'], conf['zonefiles'])
if zfdata is not None:
zfdata = base64.b64encode(zfdata)
name_record['zonefile'] = zfdata
return name_record | python | 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(name)
namespace_record = db.get_namespace(namespace_id, include_history=False)
if namespace_record is None:
namespace_record = db.get_namespace_reveal(namespace_id, include_history=False)
if namespace_record is None:
# name can't exist (this can be arrived at if we're resolving a DID)
return None
# when does this name expire (if it expires)?
if namespace_record['lifetime'] != NAMESPACE_LIFE_INFINITE:
deadlines = BlockstackDB.get_name_deadlines(name_record, namespace_record, db.lastblock)
if deadlines is not None:
name_record['expire_block'] = deadlines['expire_block']
name_record['renewal_deadline'] = deadlines['renewal_deadline']
else:
# only possible if namespace is not yet ready
name_record['expire_block'] = -1
name_record['renewal_deadline'] = -1
else:
name_record['expire_block'] = -1
name_record['renewal_deadline'] = -1
if name_record['expire_block'] > 0 and name_record['expire_block'] <= db.lastblock:
name_record['expired'] = True
else:
name_record['expired'] = False
# try to get the zonefile as well
if 'value_hash' in name_record and name_record['value_hash'] is not None:
conf = get_blockstack_opts()
if is_atlas_enabled(conf):
zfdata = self.get_zonefile_data(name_record['value_hash'], conf['zonefiles'])
if zfdata is not None:
zfdata = base64.b64encode(zfdata)
name_record['zonefile'] = zfdata
return name_record | [
"def",
"load_name_info",
"(",
"self",
",",
"db",
",",
"name_record",
")",
":",
"name",
"=",
"str",
"(",
"name_record",
"[",
"'name'",
"]",
")",
"name_record",
"=",
"self",
".",
"sanitize_rec",
"(",
"name_record",
")",
"namespace_id",
"=",
"get_namespace_from_name",
"(",
"name",
")",
"namespace_record",
"=",
"db",
".",
"get_namespace",
"(",
"namespace_id",
",",
"include_history",
"=",
"False",
")",
"if",
"namespace_record",
"is",
"None",
":",
"namespace_record",
"=",
"db",
".",
"get_namespace_reveal",
"(",
"namespace_id",
",",
"include_history",
"=",
"False",
")",
"if",
"namespace_record",
"is",
"None",
":",
"# name can't exist (this can be arrived at if we're resolving a DID)",
"return",
"None",
"# when does this name expire (if it expires)?",
"if",
"namespace_record",
"[",
"'lifetime'",
"]",
"!=",
"NAMESPACE_LIFE_INFINITE",
":",
"deadlines",
"=",
"BlockstackDB",
".",
"get_name_deadlines",
"(",
"name_record",
",",
"namespace_record",
",",
"db",
".",
"lastblock",
")",
"if",
"deadlines",
"is",
"not",
"None",
":",
"name_record",
"[",
"'expire_block'",
"]",
"=",
"deadlines",
"[",
"'expire_block'",
"]",
"name_record",
"[",
"'renewal_deadline'",
"]",
"=",
"deadlines",
"[",
"'renewal_deadline'",
"]",
"else",
":",
"# only possible if namespace is not yet ready",
"name_record",
"[",
"'expire_block'",
"]",
"=",
"-",
"1",
"name_record",
"[",
"'renewal_deadline'",
"]",
"=",
"-",
"1",
"else",
":",
"name_record",
"[",
"'expire_block'",
"]",
"=",
"-",
"1",
"name_record",
"[",
"'renewal_deadline'",
"]",
"=",
"-",
"1",
"if",
"name_record",
"[",
"'expire_block'",
"]",
">",
"0",
"and",
"name_record",
"[",
"'expire_block'",
"]",
"<=",
"db",
".",
"lastblock",
":",
"name_record",
"[",
"'expired'",
"]",
"=",
"True",
"else",
":",
"name_record",
"[",
"'expired'",
"]",
"=",
"False",
"# try to get the zonefile as well ",
"if",
"'value_hash'",
"in",
"name_record",
"and",
"name_record",
"[",
"'value_hash'",
"]",
"is",
"not",
"None",
":",
"conf",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"is_atlas_enabled",
"(",
"conf",
")",
":",
"zfdata",
"=",
"self",
".",
"get_zonefile_data",
"(",
"name_record",
"[",
"'value_hash'",
"]",
",",
"conf",
"[",
"'zonefiles'",
"]",
")",
"if",
"zfdata",
"is",
"not",
"None",
":",
"zfdata",
"=",
"base64",
".",
"b64encode",
"(",
"zfdata",
")",
"name_record",
"[",
"'zonefile'",
"]",
"=",
"zfdata",
"return",
"name_record"
] | Get some extra name information, given a db-loaded name record.
Return the updated name_record | [
"Get",
"some",
"extra",
"name",
"information",
"given",
"a",
"db",
"-",
"loaded",
"name",
"record",
".",
"Return",
"the",
"updated",
"name_record"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L574-L620 |
230,526 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.get_name_DID_info | 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}
return did_info | python | 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}
return did_info | [
"def",
"get_name_DID_info",
"(",
"self",
",",
"name",
")",
":",
"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",
"}",
"return",
"did_info"
] | Get a name's DID info
Returns None if not found | [
"Get",
"a",
"name",
"s",
"DID",
"info",
"Returns",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L712-L722 |
230,527 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_name_DID | 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)
else:
return {'error': 'Invalid name or subdomain', 'http_status': 400}
if did_info is None:
return {'error': 'No DID for this name', 'http_status': 404}
did = make_DID(did_info['name_type'], did_info['address'], did_info['index'])
return self.success_response({'did': did}) | python | 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)
else:
return {'error': 'Invalid name or subdomain', 'http_status': 400}
if did_info is None:
return {'error': 'No DID for this name', 'http_status': 404}
did = make_DID(did_info['name_type'], did_info['address'], did_info['index'])
return self.success_response({'did': did}) | [
"def",
"rpc_get_name_DID",
"(",
"self",
",",
"name",
",",
"*",
"*",
"con_info",
")",
":",
"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",
")",
"else",
":",
"return",
"{",
"'error'",
":",
"'Invalid name or subdomain'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"did_info",
"is",
"None",
":",
"return",
"{",
"'error'",
":",
"'No DID for this name'",
",",
"'http_status'",
":",
"404",
"}",
"did",
"=",
"make_DID",
"(",
"did_info",
"[",
"'name_type'",
"]",
",",
"did_info",
"[",
"'address'",
"]",
",",
"did_info",
"[",
"'index'",
"]",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'did'",
":",
"did",
"}",
")"
] | Given a name or subdomain, return its DID. | [
"Given",
"a",
"name",
"or",
"subdomain",
"return",
"its",
"DID",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L734-L750 |
230,528 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_DID_record | 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)
except:
return {'error': 'Invalid DID', 'http_status': 400}
res = None
if did_info['name_type'] == 'name':
res = self.get_name_DID_record(did)
elif did_info['name_type'] == 'subdomain':
res = self.get_subdomain_DID_record(did)
if 'error' in res:
return {'error': res['error'], 'http_status': res.get('http_status', 404)}
return self.success_response({'record': res['record']}) | python | 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)
except:
return {'error': 'Invalid DID', 'http_status': 400}
res = None
if did_info['name_type'] == 'name':
res = self.get_name_DID_record(did)
elif did_info['name_type'] == 'subdomain':
res = self.get_subdomain_DID_record(did)
if 'error' in res:
return {'error': res['error'], 'http_status': res.get('http_status', 404)}
return self.success_response({'record': res['record']}) | [
"def",
"rpc_get_DID_record",
"(",
"self",
",",
"did",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"isinstance",
"(",
"did",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid DID: not a string'",
",",
"'http_status'",
":",
"400",
"}",
"try",
":",
"did_info",
"=",
"parse_DID",
"(",
"did",
")",
"except",
":",
"return",
"{",
"'error'",
":",
"'Invalid DID'",
",",
"'http_status'",
":",
"400",
"}",
"res",
"=",
"None",
"if",
"did_info",
"[",
"'name_type'",
"]",
"==",
"'name'",
":",
"res",
"=",
"self",
".",
"get_name_DID_record",
"(",
"did",
")",
"elif",
"did_info",
"[",
"'name_type'",
"]",
"==",
"'subdomain'",
":",
"res",
"=",
"self",
".",
"get_subdomain_DID_record",
"(",
"did",
")",
"if",
"'error'",
"in",
"res",
":",
"return",
"{",
"'error'",
":",
"res",
"[",
"'error'",
"]",
",",
"'http_status'",
":",
"res",
".",
"get",
"(",
"'http_status'",
",",
"404",
")",
"}",
"return",
"self",
".",
"success_response",
"(",
"{",
"'record'",
":",
"res",
"[",
"'record'",
"]",
"}",
")"
] | Given a DID, return the name or subdomain it corresponds to | [
"Given",
"a",
"DID",
"return",
"the",
"name",
"or",
"subdomain",
"it",
"corresponds",
"to"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L805-L826 |
230,529 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_blockstack_ops_at | 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_block(block_id):
return {'error': 'Invalid block height', 'http_status': 400}
if not check_offset(offset):
return {'error': 'Invalid offset', 'http_status': 400}
if not check_count(count, 10):
return {'error': 'Invalid count', 'http_status': 400}
db = get_db_state(self.working_dir)
nameops = db.get_all_blockstack_ops_at(block_id, offset=offset, count=count)
db.close()
log.debug("{} name operations at block {}, offset {}, count {}".format(len(nameops), block_id, offset, count))
ret = []
for nameop in nameops:
assert 'opcode' in nameop, 'BUG: missing opcode in {}'.format(json.dumps(nameop, sort_keys=True))
canonical_op = self.sanitize_rec(nameop)
ret.append(canonical_op)
return self.success_response({'nameops': ret}) | python | 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_block(block_id):
return {'error': 'Invalid block height', 'http_status': 400}
if not check_offset(offset):
return {'error': 'Invalid offset', 'http_status': 400}
if not check_count(count, 10):
return {'error': 'Invalid count', 'http_status': 400}
db = get_db_state(self.working_dir)
nameops = db.get_all_blockstack_ops_at(block_id, offset=offset, count=count)
db.close()
log.debug("{} name operations at block {}, offset {}, count {}".format(len(nameops), block_id, offset, count))
ret = []
for nameop in nameops:
assert 'opcode' in nameop, 'BUG: missing opcode in {}'.format(json.dumps(nameop, sort_keys=True))
canonical_op = self.sanitize_rec(nameop)
ret.append(canonical_op)
return self.success_response({'nameops': ret}) | [
"def",
"rpc_get_blockstack_ops_at",
"(",
"self",
",",
"block_id",
",",
"offset",
",",
"count",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_block",
"(",
"block_id",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid block height'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_offset",
"(",
"offset",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid offset'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_count",
"(",
"count",
",",
"10",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid count'",
",",
"'http_status'",
":",
"400",
"}",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"nameops",
"=",
"db",
".",
"get_all_blockstack_ops_at",
"(",
"block_id",
",",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
")",
"db",
".",
"close",
"(",
")",
"log",
".",
"debug",
"(",
"\"{} name operations at block {}, offset {}, count {}\"",
".",
"format",
"(",
"len",
"(",
"nameops",
")",
",",
"block_id",
",",
"offset",
",",
"count",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"nameop",
"in",
"nameops",
":",
"assert",
"'opcode'",
"in",
"nameop",
",",
"'BUG: missing opcode in {}'",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"nameop",
",",
"sort_keys",
"=",
"True",
")",
")",
"canonical_op",
"=",
"self",
".",
"sanitize_rec",
"(",
"nameop",
")",
"ret",
".",
"append",
"(",
"canonical_op",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'nameops'",
":",
"ret",
"}",
")"
] | Get the name operations that occured in the given block.
Does not include account operations.
Returns {'nameops': [...]} on success.
Returns {'error': ...} on error | [
"Get",
"the",
"name",
"operations",
"that",
"occured",
"in",
"the",
"given",
"block",
".",
"Does",
"not",
"include",
"account",
"operations",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L976-L1005 |
230,530 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_blockstack_ops_hash_at | 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
"""
if not check_block(block_id):
return {'error': 'Invalid block height', 'http_status': 400}
db = get_db_state(self.working_dir)
ops_hash = db.get_block_ops_hash( block_id )
db.close()
return self.success_response( {'ops_hash': ops_hash} ) | python | 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
"""
if not check_block(block_id):
return {'error': 'Invalid block height', 'http_status': 400}
db = get_db_state(self.working_dir)
ops_hash = db.get_block_ops_hash( block_id )
db.close()
return self.success_response( {'ops_hash': ops_hash} ) | [
"def",
"rpc_get_blockstack_ops_hash_at",
"(",
"self",
",",
"block_id",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_block",
"(",
"block_id",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid block height'",
",",
"'http_status'",
":",
"400",
"}",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"ops_hash",
"=",
"db",
".",
"get_block_ops_hash",
"(",
"block_id",
")",
"db",
".",
"close",
"(",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'ops_hash'",
":",
"ops_hash",
"}",
")"
] | 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 | [
"Get",
"the",
"hash",
"over",
"the",
"sequence",
"of",
"names",
"and",
"namespaces",
"altered",
"at",
"the",
"given",
"block",
".",
"Used",
"by",
"SNV",
"clients",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1008-L1023 |
230,531 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.get_bitcoind_info | 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 = default_bitcoind_opts( virtualchain.get_config_filename(virtualchain_hooks, self.working_dir), prefix=True )
bitcoind = get_bitcoind( new_bitcoind_opts=bitcoind_opts, new=True )
if bitcoind is None:
return {'error': 'Internal server error: failed to connect to bitcoind'}
try:
info = bitcoind.getinfo()
assert 'error' not in info
assert 'blocks' in info
self.set_cached_bitcoind_info(info)
return info
except Exception as e:
raise | python | 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 = default_bitcoind_opts( virtualchain.get_config_filename(virtualchain_hooks, self.working_dir), prefix=True )
bitcoind = get_bitcoind( new_bitcoind_opts=bitcoind_opts, new=True )
if bitcoind is None:
return {'error': 'Internal server error: failed to connect to bitcoind'}
try:
info = bitcoind.getinfo()
assert 'error' not in info
assert 'blocks' in info
self.set_cached_bitcoind_info(info)
return info
except Exception as e:
raise | [
"def",
"get_bitcoind_info",
"(",
"self",
")",
":",
"cached_bitcoind_info",
"=",
"self",
".",
"get_cached_bitcoind_info",
"(",
")",
"if",
"cached_bitcoind_info",
":",
"return",
"cached_bitcoind_info",
"bitcoind_opts",
"=",
"default_bitcoind_opts",
"(",
"virtualchain",
".",
"get_config_filename",
"(",
"virtualchain_hooks",
",",
"self",
".",
"working_dir",
")",
",",
"prefix",
"=",
"True",
")",
"bitcoind",
"=",
"get_bitcoind",
"(",
"new_bitcoind_opts",
"=",
"bitcoind_opts",
",",
"new",
"=",
"True",
")",
"if",
"bitcoind",
"is",
"None",
":",
"return",
"{",
"'error'",
":",
"'Internal server error: failed to connect to bitcoind'",
"}",
"try",
":",
"info",
"=",
"bitcoind",
".",
"getinfo",
"(",
")",
"assert",
"'error'",
"not",
"in",
"info",
"assert",
"'blocks'",
"in",
"info",
"self",
".",
"set_cached_bitcoind_info",
"(",
"info",
")",
"return",
"info",
"except",
"Exception",
"as",
"e",
":",
"raise"
] | Get bitcoind info. Try the cache, and on cache miss,
fetch from bitcoind and cache. | [
"Get",
"bitcoind",
"info",
".",
"Try",
"the",
"cache",
"and",
"on",
"cache",
"miss",
"fetch",
"from",
"bitcoind",
"and",
"cache",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1078-L1102 |
230,532 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.get_consensus_info | 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_state(self.working_dir)
ch = db.get_current_consensus()
block = db.get_current_block()
db.close()
cinfo = {'consensus_hash': ch, 'block_height': block}
self.set_cached_consensus_info(cinfo)
return cinfo | python | 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_state(self.working_dir)
ch = db.get_current_consensus()
block = db.get_current_block()
db.close()
cinfo = {'consensus_hash': ch, 'block_height': block}
self.set_cached_consensus_info(cinfo)
return cinfo | [
"def",
"get_consensus_info",
"(",
"self",
")",
":",
"cached_consensus_info",
"=",
"self",
".",
"get_cached_consensus_info",
"(",
")",
"if",
"cached_consensus_info",
":",
"return",
"cached_consensus_info",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"ch",
"=",
"db",
".",
"get_current_consensus",
"(",
")",
"block",
"=",
"db",
".",
"get_current_block",
"(",
")",
"db",
".",
"close",
"(",
")",
"cinfo",
"=",
"{",
"'consensus_hash'",
":",
"ch",
",",
"'block_height'",
":",
"block",
"}",
"self",
".",
"set_cached_consensus_info",
"(",
"cinfo",
")",
"return",
"cinfo"
] | Get block height and consensus hash. Try the cache, and
on cache miss, fetch from the db | [
"Get",
"block",
"height",
"and",
"consensus",
"hash",
".",
"Try",
"the",
"cache",
"and",
"on",
"cache",
"miss",
"fetch",
"from",
"the",
"db"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1105-L1121 |
230,533 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_account_tokens | 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_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
token_list = db.get_account_tokens(address)
db.close()
return self.success_response({'token_types': token_list}) | python | 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_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
token_list = db.get_account_tokens(address)
db.close()
return self.success_response({'token_types': token_list}) | [
"def",
"rpc_get_account_tokens",
"(",
"self",
",",
"address",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_account_address",
"(",
"address",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid address'",
",",
"'http_status'",
":",
"400",
"}",
"# must be b58",
"if",
"is_c32_address",
"(",
"address",
")",
":",
"address",
"=",
"c32ToB58",
"(",
"address",
")",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"token_list",
"=",
"db",
".",
"get_account_tokens",
"(",
"address",
")",
"db",
".",
"close",
"(",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'token_types'",
":",
"token_list",
"}",
")"
] | Get the types of tokens that an account owns
Returns the list on success | [
"Get",
"the",
"types",
"of",
"tokens",
"that",
"an",
"account",
"owns",
"Returns",
"the",
"list",
"on",
"success"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1300-L1315 |
230,534 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_account_balance | 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):
return {'error': 'Invalid address', 'http_status': 400}
if not check_token_type(token_type):
return {'error': 'Invalid token type', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account = db.get_account(address, token_type)
if account is None:
return self.success_response({'balance': 0})
balance = db.get_account_balance(account)
if balance is None:
balance = 0
db.close()
return self.success_response({'balance': balance}) | python | 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):
return {'error': 'Invalid address', 'http_status': 400}
if not check_token_type(token_type):
return {'error': 'Invalid token type', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account = db.get_account(address, token_type)
if account is None:
return self.success_response({'balance': 0})
balance = db.get_account_balance(account)
if balance is None:
balance = 0
db.close()
return self.success_response({'balance': balance}) | [
"def",
"rpc_get_account_balance",
"(",
"self",
",",
"address",
",",
"token_type",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_account_address",
"(",
"address",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid address'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_token_type",
"(",
"token_type",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid token type'",
",",
"'http_status'",
":",
"400",
"}",
"# must be b58",
"if",
"is_c32_address",
"(",
"address",
")",
":",
"address",
"=",
"c32ToB58",
"(",
"address",
")",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"account",
"=",
"db",
".",
"get_account",
"(",
"address",
",",
"token_type",
")",
"if",
"account",
"is",
"None",
":",
"return",
"self",
".",
"success_response",
"(",
"{",
"'balance'",
":",
"0",
"}",
")",
"balance",
"=",
"db",
".",
"get_account_balance",
"(",
"account",
")",
"if",
"balance",
"is",
"None",
":",
"balance",
"=",
"0",
"db",
".",
"close",
"(",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'balance'",
":",
"balance",
"}",
")"
] | 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 | [
"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"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1318-L1344 |
230,535 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.export_account_state | 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']),
'debit_value': '{}'.format(account_state['debit_value']),
'lock_transfer_block_id': account_state['lock_transfer_block_id'],
'block_id': account_state['block_id'],
'vtxindex': account_state['vtxindex'],
'txid': account_state['txid'],
} | python | 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']),
'debit_value': '{}'.format(account_state['debit_value']),
'lock_transfer_block_id': account_state['lock_transfer_block_id'],
'block_id': account_state['block_id'],
'vtxindex': account_state['vtxindex'],
'txid': account_state['txid'],
} | [
"def",
"export_account_state",
"(",
"self",
",",
"account_state",
")",
":",
"return",
"{",
"'address'",
":",
"account_state",
"[",
"'address'",
"]",
",",
"'type'",
":",
"account_state",
"[",
"'type'",
"]",
",",
"'credit_value'",
":",
"'{}'",
".",
"format",
"(",
"account_state",
"[",
"'credit_value'",
"]",
")",
",",
"'debit_value'",
":",
"'{}'",
".",
"format",
"(",
"account_state",
"[",
"'debit_value'",
"]",
")",
",",
"'lock_transfer_block_id'",
":",
"account_state",
"[",
"'lock_transfer_block_id'",
"]",
",",
"'block_id'",
":",
"account_state",
"[",
"'block_id'",
"]",
",",
"'vtxindex'",
":",
"account_state",
"[",
"'vtxindex'",
"]",
",",
"'txid'",
":",
"account_state",
"[",
"'txid'",
"]",
",",
"}"
] | Make an account state presentable to external consumers | [
"Make",
"an",
"account",
"state",
"presentable",
"to",
"external",
"consumers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1347-L1360 |
230,536 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_account_record | 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 {'error': 'Invalid token type', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account = db.get_account(address, token_type)
db.close()
if account is None:
return {'error': 'No such account', 'http_status': 404}
state = self.export_account_state(account)
return self.success_response({'account': state}) | python | 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 {'error': 'Invalid token type', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account = db.get_account(address, token_type)
db.close()
if account is None:
return {'error': 'No such account', 'http_status': 404}
state = self.export_account_state(account)
return self.success_response({'account': state}) | [
"def",
"rpc_get_account_record",
"(",
"self",
",",
"address",
",",
"token_type",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_account_address",
"(",
"address",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid address'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_token_type",
"(",
"token_type",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid token type'",
",",
"'http_status'",
":",
"400",
"}",
"# must be b58",
"if",
"is_c32_address",
"(",
"address",
")",
":",
"address",
"=",
"c32ToB58",
"(",
"address",
")",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"account",
"=",
"db",
".",
"get_account",
"(",
"address",
",",
"token_type",
")",
"db",
".",
"close",
"(",
")",
"if",
"account",
"is",
"None",
":",
"return",
"{",
"'error'",
":",
"'No such account'",
",",
"'http_status'",
":",
"404",
"}",
"state",
"=",
"self",
".",
"export_account_state",
"(",
"account",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'account'",
":",
"state",
"}",
")"
] | Get the current state of an account | [
"Get",
"the",
"current",
"state",
"of",
"an",
"account"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1363-L1385 |
230,537 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_account_at | 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': 400}
if not check_block(block_height):
return {'error': 'Invalid start block', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account_states = db.get_account_at(address, block_height)
db.close()
# return credit_value and debit_value as strings, so the unwitting JS developer doesn't get confused
# as to why large balances get mysteriously converted to doubles.
ret = [self.export_account_state(hist) for hist in account_states]
return self.success_response({'history': ret}) | python | 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': 400}
if not check_block(block_height):
return {'error': 'Invalid start block', 'http_status': 400}
# must be b58
if is_c32_address(address):
address = c32ToB58(address)
db = get_db_state(self.working_dir)
account_states = db.get_account_at(address, block_height)
db.close()
# return credit_value and debit_value as strings, so the unwitting JS developer doesn't get confused
# as to why large balances get mysteriously converted to doubles.
ret = [self.export_account_state(hist) for hist in account_states]
return self.success_response({'history': ret}) | [
"def",
"rpc_get_account_at",
"(",
"self",
",",
"address",
",",
"block_height",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_account_address",
"(",
"address",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid address'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_block",
"(",
"block_height",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid start block'",
",",
"'http_status'",
":",
"400",
"}",
"# must be b58",
"if",
"is_c32_address",
"(",
"address",
")",
":",
"address",
"=",
"c32ToB58",
"(",
"address",
")",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"account_states",
"=",
"db",
".",
"get_account_at",
"(",
"address",
",",
"block_height",
")",
"db",
".",
"close",
"(",
")",
"# return credit_value and debit_value as strings, so the unwitting JS developer doesn't get confused",
"# as to why large balances get mysteriously converted to doubles.",
"ret",
"=",
"[",
"self",
".",
"export_account_state",
"(",
"hist",
")",
"for",
"hist",
"in",
"account_states",
"]",
"return",
"self",
".",
"success_response",
"(",
"{",
"'history'",
":",
"ret",
"}",
")"
] | Get the account's statuses at a particular block height.
Returns the sequence of history states on success | [
"Get",
"the",
"account",
"s",
"statuses",
"at",
"a",
"particular",
"block",
"height",
".",
"Returns",
"the",
"sequence",
"of",
"history",
"states",
"on",
"success"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1414-L1436 |
230,538 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_consensus_hashes | 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
"""
if type(block_id_list) != list:
return {'error': 'Invalid block heights', 'http_status': 400}
if len(block_id_list) > 32:
return {'error': 'Too many block heights', 'http_status': 400}
for bid in block_id_list:
if not check_block(bid):
return {'error': 'Invalid block height', 'http_status': 400}
db = get_db_state(self.working_dir)
ret = {}
for block_id in block_id_list:
ret[block_id] = db.get_consensus_at(block_id)
db.close()
return self.success_response( {'consensus_hashes': ret} ) | python | 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
"""
if type(block_id_list) != list:
return {'error': 'Invalid block heights', 'http_status': 400}
if len(block_id_list) > 32:
return {'error': 'Too many block heights', 'http_status': 400}
for bid in block_id_list:
if not check_block(bid):
return {'error': 'Invalid block height', 'http_status': 400}
db = get_db_state(self.working_dir)
ret = {}
for block_id in block_id_list:
ret[block_id] = db.get_consensus_at(block_id)
db.close()
return self.success_response( {'consensus_hashes': ret} ) | [
"def",
"rpc_get_consensus_hashes",
"(",
"self",
",",
"block_id_list",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"type",
"(",
"block_id_list",
")",
"!=",
"list",
":",
"return",
"{",
"'error'",
":",
"'Invalid block heights'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"len",
"(",
"block_id_list",
")",
">",
"32",
":",
"return",
"{",
"'error'",
":",
"'Too many block heights'",
",",
"'http_status'",
":",
"400",
"}",
"for",
"bid",
"in",
"block_id_list",
":",
"if",
"not",
"check_block",
"(",
"bid",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid block height'",
",",
"'http_status'",
":",
"400",
"}",
"db",
"=",
"get_db_state",
"(",
"self",
".",
"working_dir",
")",
"ret",
"=",
"{",
"}",
"for",
"block_id",
"in",
"block_id_list",
":",
"ret",
"[",
"block_id",
"]",
"=",
"db",
".",
"get_consensus_at",
"(",
"block_id",
")",
"db",
".",
"close",
"(",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'consensus_hashes'",
":",
"ret",
"}",
")"
] | 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 | [
"Return",
"the",
"consensus",
"hashes",
"at",
"multiple",
"block",
"numbers",
"Return",
"a",
"dict",
"mapping",
"each",
"block",
"ID",
"to",
"its",
"consensus",
"hash",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1653-L1678 |
230,539 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.get_zonefile_data | 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 )
if atlas_zonefile_data is not None:
# check hash
zfh = get_zonefile_data_hash( atlas_zonefile_data )
if zfh != zonefile_hash:
log.debug("Invalid local zonefile %s" % zonefile_hash )
remove_atlas_zonefile_data( zonefile_hash, zonefile_dir )
else:
log.debug("Zonefile %s is local" % zonefile_hash)
return atlas_zonefile_data
return None | python | 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 )
if atlas_zonefile_data is not None:
# check hash
zfh = get_zonefile_data_hash( atlas_zonefile_data )
if zfh != zonefile_hash:
log.debug("Invalid local zonefile %s" % zonefile_hash )
remove_atlas_zonefile_data( zonefile_hash, zonefile_dir )
else:
log.debug("Zonefile %s is local" % zonefile_hash)
return atlas_zonefile_data
return None | [
"def",
"get_zonefile_data",
"(",
"self",
",",
"zonefile_hash",
",",
"zonefile_dir",
")",
":",
"# check cache",
"atlas_zonefile_data",
"=",
"get_atlas_zonefile_data",
"(",
"zonefile_hash",
",",
"zonefile_dir",
",",
"check",
"=",
"False",
")",
"if",
"atlas_zonefile_data",
"is",
"not",
"None",
":",
"# check hash",
"zfh",
"=",
"get_zonefile_data_hash",
"(",
"atlas_zonefile_data",
")",
"if",
"zfh",
"!=",
"zonefile_hash",
":",
"log",
".",
"debug",
"(",
"\"Invalid local zonefile %s\"",
"%",
"zonefile_hash",
")",
"remove_atlas_zonefile_data",
"(",
"zonefile_hash",
",",
"zonefile_dir",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"Zonefile %s is local\"",
"%",
"zonefile_hash",
")",
"return",
"atlas_zonefile_data",
"return",
"None"
] | Get a zonefile by hash
Return the serialized zonefile on success
Return None on error | [
"Get",
"a",
"zonefile",
"by",
"hash",
"Return",
"the",
"serialized",
"zonefile",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1694-L1713 |
230,540 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_get_zonefiles_by_block | 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, 'lastblock' : blockNumber,
'zonefile_info' : [ { 'block_height' : 470000,
'txid' : '0000000',
'zonefile_hash' : '0000000' } ] }
"""
conf = get_blockstack_opts()
if not is_atlas_enabled(conf):
return {'error': 'Not an atlas node', 'http_status': 400}
if not check_block(from_block):
return {'error': 'Invalid from_block height', 'http_status': 400}
if not check_block(to_block):
return {'error': 'Invalid to_block height', 'http_status': 400}
if not check_offset(offset):
return {'error': 'invalid offset', 'http_status': 400}
if not check_count(count, 100):
return {'error': 'invalid count', 'http_status': 400}
zonefile_info = atlasdb_get_zonefiles_by_block(from_block, to_block, offset, count, path=conf['atlasdb_path'])
if 'error' in zonefile_info:
return zonefile_info
return self.success_response( {'zonefile_info': zonefile_info } ) | python | 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, 'lastblock' : blockNumber,
'zonefile_info' : [ { 'block_height' : 470000,
'txid' : '0000000',
'zonefile_hash' : '0000000' } ] }
"""
conf = get_blockstack_opts()
if not is_atlas_enabled(conf):
return {'error': 'Not an atlas node', 'http_status': 400}
if not check_block(from_block):
return {'error': 'Invalid from_block height', 'http_status': 400}
if not check_block(to_block):
return {'error': 'Invalid to_block height', 'http_status': 400}
if not check_offset(offset):
return {'error': 'invalid offset', 'http_status': 400}
if not check_count(count, 100):
return {'error': 'invalid count', 'http_status': 400}
zonefile_info = atlasdb_get_zonefiles_by_block(from_block, to_block, offset, count, path=conf['atlasdb_path'])
if 'error' in zonefile_info:
return zonefile_info
return self.success_response( {'zonefile_info': zonefile_info } ) | [
"def",
"rpc_get_zonefiles_by_block",
"(",
"self",
",",
"from_block",
",",
"to_block",
",",
"offset",
",",
"count",
",",
"*",
"*",
"con_info",
")",
":",
"conf",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_atlas_enabled",
"(",
"conf",
")",
":",
"return",
"{",
"'error'",
":",
"'Not an atlas node'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_block",
"(",
"from_block",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid from_block height'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_block",
"(",
"to_block",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid to_block height'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_offset",
"(",
"offset",
")",
":",
"return",
"{",
"'error'",
":",
"'invalid offset'",
",",
"'http_status'",
":",
"400",
"}",
"if",
"not",
"check_count",
"(",
"count",
",",
"100",
")",
":",
"return",
"{",
"'error'",
":",
"'invalid count'",
",",
"'http_status'",
":",
"400",
"}",
"zonefile_info",
"=",
"atlasdb_get_zonefiles_by_block",
"(",
"from_block",
",",
"to_block",
",",
"offset",
",",
"count",
",",
"path",
"=",
"conf",
"[",
"'atlasdb_path'",
"]",
")",
"if",
"'error'",
"in",
"zonefile_info",
":",
"return",
"zonefile_info",
"return",
"self",
".",
"success_response",
"(",
"{",
"'zonefile_info'",
":",
"zonefile_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, 'lastblock' : blockNumber,
'zonefile_info' : [ { 'block_height' : 470000,
'txid' : '0000000',
'zonefile_hash' : '0000000' } ] } | [
"Get",
"information",
"about",
"zonefiles",
"announced",
"in",
"blocks",
"["
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1845-L1875 |
230,541 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.peer_exchange | 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(peer_list) > atlas_max_neighbors():
random.shuffle(peer_list)
peer_list = peer_list[:atlas_max_neighbors()]
log.info("Enqueue remote peer {}:{}".format(peer_host, peer_port))
atlas_peer_enqueue( "%s:%s" % (peer_host, peer_port))
log.debug("Live peers reply to %s:%s: %s" % (peer_host, peer_port, peer_list))
return peer_list | python | 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(peer_list) > atlas_max_neighbors():
random.shuffle(peer_list)
peer_list = peer_list[:atlas_max_neighbors()]
log.info("Enqueue remote peer {}:{}".format(peer_host, peer_port))
atlas_peer_enqueue( "%s:%s" % (peer_host, peer_port))
log.debug("Live peers reply to %s:%s: %s" % (peer_host, peer_port, peer_list))
return peer_list | [
"def",
"peer_exchange",
"(",
"self",
",",
"peer_host",
",",
"peer_port",
")",
":",
"# get peers",
"peer_list",
"=",
"atlas_get_live_neighbors",
"(",
"\"%s:%s\"",
"%",
"(",
"peer_host",
",",
"peer_port",
")",
")",
"if",
"len",
"(",
"peer_list",
")",
">",
"atlas_max_neighbors",
"(",
")",
":",
"random",
".",
"shuffle",
"(",
"peer_list",
")",
"peer_list",
"=",
"peer_list",
"[",
":",
"atlas_max_neighbors",
"(",
")",
"]",
"log",
".",
"info",
"(",
"\"Enqueue remote peer {}:{}\"",
".",
"format",
"(",
"peer_host",
",",
"peer_port",
")",
")",
"atlas_peer_enqueue",
"(",
"\"%s:%s\"",
"%",
"(",
"peer_host",
",",
"peer_port",
")",
")",
"log",
".",
"debug",
"(",
"\"Live peers reply to %s:%s: %s\"",
"%",
"(",
"peer_host",
",",
"peer_port",
",",
"peer_list",
")",
")",
"return",
"peer_list"
] | Exchange peers.
Add the given peer to the list of new peers to consider.
Return the list of healthy peers | [
"Exchange",
"peers",
".",
"Add",
"the",
"given",
"peer",
"to",
"the",
"list",
"of",
"new",
"peers",
"to",
"consider",
".",
"Return",
"the",
"list",
"of",
"healthy",
"peers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1878-L1894 |
230,542 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPC.rpc_atlas_peer_exchange | 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 used. This is to prevent
a malicious node from filling up this node's peer table with
junk.
Returns at most atlas_max_neighbors() peers
Returns {'status': True, 'peers': ...} on success
Returns {'error': ...} on failure
"""
conf = get_blockstack_opts()
if not conf.get('atlas', False):
return {'error': 'Not an atlas node', 'http_status': 404}
# take the socket-given information if this is not localhost
client_host = con_info['client_host']
client_port = con_info['client_port']
peer_host = None
peer_port = None
LOCALHOST = ['127.0.0.1', '::1', 'localhost']
if client_host not in LOCALHOST:
# we don't allow a non-localhost peer to insert an arbitrary host
peer_host = client_host
peer_port = client_port
else:
try:
peer_host, peer_port = url_to_host_port(remote_peer)
assert peer_host
assert peer_port
except:
# invalid
return {'error': 'Invalid remote peer address', 'http_status': 400}
peers = self.peer_exchange(peer_host, peer_port)
return self.success_response({'peers': peers}) | python | 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 used. This is to prevent
a malicious node from filling up this node's peer table with
junk.
Returns at most atlas_max_neighbors() peers
Returns {'status': True, 'peers': ...} on success
Returns {'error': ...} on failure
"""
conf = get_blockstack_opts()
if not conf.get('atlas', False):
return {'error': 'Not an atlas node', 'http_status': 404}
# take the socket-given information if this is not localhost
client_host = con_info['client_host']
client_port = con_info['client_port']
peer_host = None
peer_port = None
LOCALHOST = ['127.0.0.1', '::1', 'localhost']
if client_host not in LOCALHOST:
# we don't allow a non-localhost peer to insert an arbitrary host
peer_host = client_host
peer_port = client_port
else:
try:
peer_host, peer_port = url_to_host_port(remote_peer)
assert peer_host
assert peer_port
except:
# invalid
return {'error': 'Invalid remote peer address', 'http_status': 400}
peers = self.peer_exchange(peer_host, peer_port)
return self.success_response({'peers': peers}) | [
"def",
"rpc_atlas_peer_exchange",
"(",
"self",
",",
"remote_peer",
",",
"*",
"*",
"con_info",
")",
":",
"conf",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"conf",
".",
"get",
"(",
"'atlas'",
",",
"False",
")",
":",
"return",
"{",
"'error'",
":",
"'Not an atlas node'",
",",
"'http_status'",
":",
"404",
"}",
"# take the socket-given information if this is not localhost",
"client_host",
"=",
"con_info",
"[",
"'client_host'",
"]",
"client_port",
"=",
"con_info",
"[",
"'client_port'",
"]",
"peer_host",
"=",
"None",
"peer_port",
"=",
"None",
"LOCALHOST",
"=",
"[",
"'127.0.0.1'",
",",
"'::1'",
",",
"'localhost'",
"]",
"if",
"client_host",
"not",
"in",
"LOCALHOST",
":",
"# we don't allow a non-localhost peer to insert an arbitrary host",
"peer_host",
"=",
"client_host",
"peer_port",
"=",
"client_port",
"else",
":",
"try",
":",
"peer_host",
",",
"peer_port",
"=",
"url_to_host_port",
"(",
"remote_peer",
")",
"assert",
"peer_host",
"assert",
"peer_port",
"except",
":",
"# invalid",
"return",
"{",
"'error'",
":",
"'Invalid remote peer address'",
",",
"'http_status'",
":",
"400",
"}",
"peers",
"=",
"self",
".",
"peer_exchange",
"(",
"peer_host",
",",
"peer_port",
")",
"return",
"self",
".",
"success_response",
"(",
"{",
"'peers'",
":",
"peers",
"}",
")"
] | 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 peer table with
junk.
Returns at most atlas_max_neighbors() peers
Returns {'status': True, 'peers': ...} on success
Returns {'error': ...} on failure | [
"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",
"peer",
"table",
"with",
"junk",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1917-L1957 |
230,543 | blockstack/blockstack-core | blockstack/blockstackd.py | BlockstackdRPCServer.stop_server | 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.rpc_server.shutdown() | python | 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.rpc_server.shutdown() | [
"def",
"stop_server",
"(",
"self",
")",
":",
"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",
".",
"rpc_server",
".",
"shutdown",
"(",
")"
] | Stop serving. Also stops the thread. | [
"Stop",
"serving",
".",
"Also",
"stops",
"the",
"thread",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2017-L2027 |
230,544 | blockstack/blockstack-core | blockstack/lib/nameset/virtualchain_hooks.py | get_last_block | 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 | 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) | [
"def",
"get_last_block",
"(",
"working_dir",
")",
":",
"# make this usable even if we haven't explicitly configured virtualchain ",
"impl",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"return",
"BlockstackDB",
".",
"get_lastblock",
"(",
"impl",
",",
"working_dir",
")"
] | Get the last block processed
Return the integer on success
Return None on error | [
"Get",
"the",
"last",
"block",
"processed",
"Return",
"the",
"integer",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/virtualchain_hooks.py#L119-L128 |
230,545 | blockstack/blockstack-core | blockstack/lib/nameset/virtualchain_hooks.py | get_or_instantiate_db_state | 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)
BlockstackDB.release_readwrite_instance(new_db, -1)
return get_db_state(working_dir) | python | 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)
BlockstackDB.release_readwrite_instance(new_db, -1)
return get_db_state(working_dir) | [
"def",
"get_or_instantiate_db_state",
"(",
"working_dir",
")",
":",
"# instantiates",
"new_db",
"=",
"BlockstackDB",
".",
"borrow_readwrite_instance",
"(",
"working_dir",
",",
"-",
"1",
")",
"BlockstackDB",
".",
"release_readwrite_instance",
"(",
"new_db",
",",
"-",
"1",
")",
"return",
"get_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 | [
"Get",
"a",
"read",
"-",
"only",
"handle",
"to",
"the",
"DB",
".",
"Instantiate",
"it",
"first",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/virtualchain_hooks.py#L162-L177 |
230,546 | blockstack/blockstack-core | blockstack/lib/nameset/virtualchain_hooks.py | check_quirks | 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:
assert 'last_creation_op' in block_op, 'QUIRK BUG: missing last_creation_op in {}'.format(op_get_opcode_name(block_op['op']))
if block_op['last_creation_op'] == NAME_IMPORT:
# the op_fee will be a float if the name record was created with a NAME_IMPORT
assert isinstance(block_op['op_fee'], float), 'QUIRK BUG: op_fee is not a float when it should be'
return | python | 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:
assert 'last_creation_op' in block_op, 'QUIRK BUG: missing last_creation_op in {}'.format(op_get_opcode_name(block_op['op']))
if block_op['last_creation_op'] == NAME_IMPORT:
# the op_fee will be a float if the name record was created with a NAME_IMPORT
assert isinstance(block_op['op_fee'], float), 'QUIRK BUG: op_fee is not a float when it should be'
return | [
"def",
"check_quirks",
"(",
"block_id",
",",
"block_op",
",",
"db_state",
")",
":",
"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",
":",
"assert",
"'last_creation_op'",
"in",
"block_op",
",",
"'QUIRK BUG: missing last_creation_op in {}'",
".",
"format",
"(",
"op_get_opcode_name",
"(",
"block_op",
"[",
"'op'",
"]",
")",
")",
"if",
"block_op",
"[",
"'last_creation_op'",
"]",
"==",
"NAME_IMPORT",
":",
"# the op_fee will be a float if the name record was created with a NAME_IMPORT",
"assert",
"isinstance",
"(",
"block_op",
"[",
"'op_fee'",
"]",
",",
"float",
")",
",",
"'QUIRK BUG: op_fee is not a float when it should be'",
"return"
] | Check that all serialization compatibility quirks have been preserved.
Used primarily for testing. | [
"Check",
"that",
"all",
"serialization",
"compatibility",
"quirks",
"have",
"been",
"preserved",
".",
"Used",
"primarily",
"for",
"testing",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/virtualchain_hooks.py#L381-L393 |
230,547 | blockstack/blockstack-core | blockstack/lib/nameset/virtualchain_hooks.py | sync_blockchain | 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['subdomains']
atlas_state = server_state['atlas']
# make this usable even if we haven't explicitly configured virtualchain
impl = sys.modules[__name__]
log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))
# NOTE: this is the only place where a read-write handle should be created,
# since this is the only place where the db should be modified.
new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)
# propagate runtime state to virtualchain callbacks
new_db.subdomain_index = subdomain_index
new_db.atlas_state = atlas_state
rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)
BlockstackDB.release_readwrite_instance(new_db, last_block)
return rc | python | 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['subdomains']
atlas_state = server_state['atlas']
# make this usable even if we haven't explicitly configured virtualchain
impl = sys.modules[__name__]
log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))
# NOTE: this is the only place where a read-write handle should be created,
# since this is the only place where the db should be modified.
new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)
# propagate runtime state to virtualchain callbacks
new_db.subdomain_index = subdomain_index
new_db.atlas_state = atlas_state
rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)
BlockstackDB.release_readwrite_instance(new_db, last_block)
return rc | [
"def",
"sync_blockchain",
"(",
"working_dir",
",",
"bt_opts",
",",
"last_block",
",",
"server_state",
",",
"expected_snapshots",
"=",
"{",
"}",
",",
"*",
"*",
"virtualchain_args",
")",
":",
"subdomain_index",
"=",
"server_state",
"[",
"'subdomains'",
"]",
"atlas_state",
"=",
"server_state",
"[",
"'atlas'",
"]",
"# make this usable even if we haven't explicitly configured virtualchain ",
"impl",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"log",
".",
"info",
"(",
"\"Synchronizing database {} up to block {}\"",
".",
"format",
"(",
"working_dir",
",",
"last_block",
")",
")",
"# NOTE: this is the only place where a read-write handle should be created,",
"# since this is the only place where the db should be modified.",
"new_db",
"=",
"BlockstackDB",
".",
"borrow_readwrite_instance",
"(",
"working_dir",
",",
"last_block",
",",
"expected_snapshots",
"=",
"expected_snapshots",
")",
"# propagate runtime state to virtualchain callbacks",
"new_db",
".",
"subdomain_index",
"=",
"subdomain_index",
"new_db",
".",
"atlas_state",
"=",
"atlas_state",
"rc",
"=",
"virtualchain",
".",
"sync_virtualchain",
"(",
"bt_opts",
",",
"last_block",
",",
"new_db",
",",
"expected_snapshots",
"=",
"expected_snapshots",
",",
"*",
"*",
"virtualchain_args",
")",
"BlockstackDB",
".",
"release_readwrite_instance",
"(",
"new_db",
",",
"last_block",
")",
"return",
"rc"
] | synchronize state with the blockchain.
Return True on success
Return False if we're supposed to stop indexing
Abort on error | [
"synchronize",
"state",
"with",
"the",
"blockchain",
".",
"Return",
"True",
"on",
"success",
"Return",
"False",
"if",
"we",
"re",
"supposed",
"to",
"stop",
"indexing",
"Abort",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/virtualchain_hooks.py#L576-L603 |
230,548 | blockstack/blockstack-core | blockstack/lib/util.py | url_protocol | 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'], 'Invalid URL scheme in {}'.format(url)
return urlinfo.scheme | python | 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'], 'Invalid URL scheme in {}'.format(url)
return urlinfo.scheme | [
"def",
"url_protocol",
"(",
"url",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'http://'",
")",
"and",
"not",
"url",
".",
"startswith",
"(",
"'https://'",
")",
":",
"return",
"None",
"urlinfo",
"=",
"urllib2",
".",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"assert",
"urlinfo",
".",
"scheme",
"in",
"[",
"'http'",
",",
"'https'",
"]",
",",
"'Invalid URL scheme in {}'",
".",
"format",
"(",
"url",
")",
"return",
"urlinfo",
".",
"scheme"
] | Get the protocol to use for a URL.
return 'http' or 'https' or None | [
"Get",
"the",
"protocol",
"to",
"use",
"for",
"a",
"URL",
".",
"return",
"http",
"or",
"https",
"or",
"None"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/util.py#L242-L252 |
230,549 | blockstack/blockstack-core | blockstack/lib/util.py | make_DID | 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_reencode(address)
else:
# what's the current version byte?
vb = keylib.b58check.b58check_version_byte(address)
if vb == bitcoin_blockchain.version_byte:
# singlesig
vb = SUBDOMAIN_ADDRESS_VERSION_BYTE
else:
vb = SUBDOMAIN_ADDRESS_MULTISIG_VERSION_BYTE
address = virtualchain.address_reencode(address, version_byte=vb)
return 'did:stack:v0:{}-{}'.format(address, index) | python | 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_reencode(address)
else:
# what's the current version byte?
vb = keylib.b58check.b58check_version_byte(address)
if vb == bitcoin_blockchain.version_byte:
# singlesig
vb = SUBDOMAIN_ADDRESS_VERSION_BYTE
else:
vb = SUBDOMAIN_ADDRESS_MULTISIG_VERSION_BYTE
address = virtualchain.address_reencode(address, version_byte=vb)
return 'did:stack:v0:{}-{}'.format(address, index) | [
"def",
"make_DID",
"(",
"name_type",
",",
"address",
",",
"index",
")",
":",
"if",
"name_type",
"not",
"in",
"[",
"'name'",
",",
"'subdomain'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Require 'name' or 'subdomain' for name_type\"",
")",
"if",
"name_type",
"==",
"'name'",
":",
"address",
"=",
"virtualchain",
".",
"address_reencode",
"(",
"address",
")",
"else",
":",
"# what's the current version byte?",
"vb",
"=",
"keylib",
".",
"b58check",
".",
"b58check_version_byte",
"(",
"address",
")",
"if",
"vb",
"==",
"bitcoin_blockchain",
".",
"version_byte",
":",
"# singlesig",
"vb",
"=",
"SUBDOMAIN_ADDRESS_VERSION_BYTE",
"else",
":",
"vb",
"=",
"SUBDOMAIN_ADDRESS_MULTISIG_VERSION_BYTE",
"address",
"=",
"virtualchain",
".",
"address_reencode",
"(",
"address",
",",
"version_byte",
"=",
"vb",
")",
"return",
"'did:stack:v0:{}-{}'",
".",
"format",
"(",
"address",
",",
"index",
")"
] | Standard way of making a DID.
name_type is "name" or "subdomain" | [
"Standard",
"way",
"of",
"making",
"a",
"DID",
".",
"name_type",
"is",
"name",
"or",
"subdomain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/util.py#L315-L336 |
230,550 | blockstack/blockstack-core | blockstack/lib/util.py | BoundedThreadingMixIn.process_request_thread | 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 Exception:
self.handle_error(request, client_address)
finally:
self.shutdown_request(request)
shutdown_thread = False
with self._thread_guard:
if threading.current_thread().ident in self._threads:
del self._threads[threading.current_thread().ident]
shutdown_thread = True
if BLOCKSTACK_TEST:
log.debug('{} active threads (removed {})'.format(len(self._threads), threading.current_thread().ident))
if shutdown_thread:
gc_thread = get_gc_thread()
if gc_thread:
# count this towards our preemptive garbage collection
gc_thread.gc_event() | python | 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 Exception:
self.handle_error(request, client_address)
finally:
self.shutdown_request(request)
shutdown_thread = False
with self._thread_guard:
if threading.current_thread().ident in self._threads:
del self._threads[threading.current_thread().ident]
shutdown_thread = True
if BLOCKSTACK_TEST:
log.debug('{} active threads (removed {})'.format(len(self._threads), threading.current_thread().ident))
if shutdown_thread:
gc_thread = get_gc_thread()
if gc_thread:
# count this towards our preemptive garbage collection
gc_thread.gc_event() | [
"def",
"process_request_thread",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"from",
".",
".",
"blockstackd",
"import",
"get_gc_thread",
"try",
":",
"self",
".",
"finish_request",
"(",
"request",
",",
"client_address",
")",
"except",
"Exception",
":",
"self",
".",
"handle_error",
"(",
"request",
",",
"client_address",
")",
"finally",
":",
"self",
".",
"shutdown_request",
"(",
"request",
")",
"shutdown_thread",
"=",
"False",
"with",
"self",
".",
"_thread_guard",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"ident",
"in",
"self",
".",
"_threads",
":",
"del",
"self",
".",
"_threads",
"[",
"threading",
".",
"current_thread",
"(",
")",
".",
"ident",
"]",
"shutdown_thread",
"=",
"True",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"debug",
"(",
"'{} active threads (removed {})'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_threads",
")",
",",
"threading",
".",
"current_thread",
"(",
")",
".",
"ident",
")",
")",
"if",
"shutdown_thread",
":",
"gc_thread",
"=",
"get_gc_thread",
"(",
")",
"if",
"gc_thread",
":",
"# count this towards our preemptive garbage collection",
"gc_thread",
".",
"gc_event",
"(",
")"
] | Same as in BaseServer but as a thread.
In addition, exception handling is done here. | [
"Same",
"as",
"in",
"BaseServer",
"but",
"as",
"a",
"thread",
".",
"In",
"addition",
"exception",
"handling",
"is",
"done",
"here",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/util.py#L91-L118 |
230,551 | blockstack/blockstack-core | blockstack/lib/util.py | BoundedThreadingMixIn.get_request | 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 = super(BoundedThreadingMixIn, self).get_request()
overload = False
with self._thread_guard:
if self._threads is not None and len(self._threads) + 1 > MAX_RPC_THREADS:
overload = True
if overload:
res = self.overloaded(client_addr)
request.sendall(res)
sys.stderr.write('{} - - [{}] "Overloaded"\n'.format(client_addr[0], time_str(time.time())))
self.shutdown_request(request)
return None, None
return request, client_addr | python | 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 = super(BoundedThreadingMixIn, self).get_request()
overload = False
with self._thread_guard:
if self._threads is not None and len(self._threads) + 1 > MAX_RPC_THREADS:
overload = True
if overload:
res = self.overloaded(client_addr)
request.sendall(res)
sys.stderr.write('{} - - [{}] "Overloaded"\n'.format(client_addr[0], time_str(time.time())))
self.shutdown_request(request)
return None, None
return request, client_addr | [
"def",
"get_request",
"(",
"self",
")",
":",
"# Note that this class must be mixed with another class that implements get_request()",
"request",
",",
"client_addr",
"=",
"super",
"(",
"BoundedThreadingMixIn",
",",
"self",
")",
".",
"get_request",
"(",
")",
"overload",
"=",
"False",
"with",
"self",
".",
"_thread_guard",
":",
"if",
"self",
".",
"_threads",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"_threads",
")",
"+",
"1",
">",
"MAX_RPC_THREADS",
":",
"overload",
"=",
"True",
"if",
"overload",
":",
"res",
"=",
"self",
".",
"overloaded",
"(",
"client_addr",
")",
"request",
".",
"sendall",
"(",
"res",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'{} - - [{}] \"Overloaded\"\\n'",
".",
"format",
"(",
"client_addr",
"[",
"0",
"]",
",",
"time_str",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
")",
"self",
".",
"shutdown_request",
"(",
"request",
")",
"return",
"None",
",",
"None",
"return",
"request",
",",
"client_addr"
] | Accept a request, up to the given number of allowed threads.
Defer to self.overloaded if there are already too many pending requests. | [
"Accept",
"a",
"request",
"up",
"to",
"the",
"given",
"number",
"of",
"allowed",
"threads",
".",
"Defer",
"to",
"self",
".",
"overloaded",
"if",
"there",
"are",
"already",
"too",
"many",
"pending",
"requests",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/util.py#L126-L146 |
230,552 | blockstack/blockstack-core | blockstack/lib/config.py | get_epoch_config | 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()
return EPOCHS[epoch_number] | python | 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()
return EPOCHS[epoch_number] | [
"def",
"get_epoch_config",
"(",
"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",
"(",
")",
"return",
"EPOCHS",
"[",
"epoch_number",
"]"
] | Get the epoch constants for the given block height | [
"Get",
"the",
"epoch",
"constants",
"for",
"the",
"given",
"block",
"height"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L949-L960 |
230,553 | blockstack/blockstack-core | blockstack/lib/config.py | get_epoch_namespace_lifetime_multiplier | 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]['NAMESPACE_LIFETIME_MULTIPLIER']
else:
return epoch_config['namespaces']['*']['NAMESPACE_LIFETIME_MULTIPLIER'] | python | 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]['NAMESPACE_LIFETIME_MULTIPLIER']
else:
return epoch_config['namespaces']['*']['NAMESPACE_LIFETIME_MULTIPLIER'] | [
"def",
"get_epoch_namespace_lifetime_multiplier",
"(",
"block_height",
",",
"namespace_id",
")",
":",
"epoch_config",
"=",
"get_epoch_config",
"(",
"block_height",
")",
"if",
"epoch_config",
"[",
"'namespaces'",
"]",
".",
"has_key",
"(",
"namespace_id",
")",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"namespace_id",
"]",
"[",
"'NAMESPACE_LIFETIME_MULTIPLIER'",
"]",
"else",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"'*'",
"]",
"[",
"'NAMESPACE_LIFETIME_MULTIPLIER'",
"]"
] | what's the namespace lifetime multipler for this epoch? | [
"what",
"s",
"the",
"namespace",
"lifetime",
"multipler",
"for",
"this",
"epoch?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L963-L971 |
230,554 | blockstack/blockstack-core | blockstack/lib/config.py | get_epoch_namespace_lifetime_grace_period | 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]['NAMESPACE_LIFETIME_GRACE_PERIOD']
else:
return epoch_config['namespaces']['*']['NAMESPACE_LIFETIME_GRACE_PERIOD'] | python | 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]['NAMESPACE_LIFETIME_GRACE_PERIOD']
else:
return epoch_config['namespaces']['*']['NAMESPACE_LIFETIME_GRACE_PERIOD'] | [
"def",
"get_epoch_namespace_lifetime_grace_period",
"(",
"block_height",
",",
"namespace_id",
")",
":",
"epoch_config",
"=",
"get_epoch_config",
"(",
"block_height",
")",
"if",
"epoch_config",
"[",
"'namespaces'",
"]",
".",
"has_key",
"(",
"namespace_id",
")",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"namespace_id",
"]",
"[",
"'NAMESPACE_LIFETIME_GRACE_PERIOD'",
"]",
"else",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"'*'",
"]",
"[",
"'NAMESPACE_LIFETIME_GRACE_PERIOD'",
"]"
] | what's the namespace lifetime grace period for this epoch? | [
"what",
"s",
"the",
"namespace",
"lifetime",
"grace",
"period",
"for",
"this",
"epoch?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L974-L982 |
230,555 | blockstack/blockstack-core | blockstack/lib/config.py | get_epoch_namespace_prices | 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_prices']
else:
return epoch_config['namespace_prices_stacks'] | python | 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_prices']
else:
return epoch_config['namespace_prices_stacks'] | [
"def",
"get_epoch_namespace_prices",
"(",
"block_height",
",",
"units",
")",
":",
"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_prices'",
"]",
"else",
":",
"return",
"epoch_config",
"[",
"'namespace_prices_stacks'",
"]"
] | get the list of namespace prices by block height | [
"get",
"the",
"list",
"of",
"namespace",
"prices",
"by",
"block",
"height"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1062-L1073 |
230,556 | blockstack/blockstack-core | blockstack/lib/config.py | op_get_opcode_name | 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:
raise Exception('No such operation "{}"'.format(op))
return OPCODE_NAMES[op] | python | 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:
raise Exception('No such operation "{}"'.format(op))
return OPCODE_NAMES[op] | [
"def",
"op_get_opcode_name",
"(",
"op_string",
")",
":",
"global",
"OPCODE_NAMES",
"# special case...",
"if",
"op_string",
"==",
"'{}:'",
".",
"format",
"(",
"NAME_REGISTRATION",
")",
":",
"return",
"'NAME_RENEWAL'",
"op",
"=",
"op_string",
"[",
"0",
"]",
"if",
"op",
"not",
"in",
"OPCODE_NAMES",
":",
"raise",
"Exception",
"(",
"'No such operation \"{}\"'",
".",
"format",
"(",
"op",
")",
")",
"return",
"OPCODE_NAMES",
"[",
"op",
"]"
] | Get the name of an opcode, given the 'op' byte sequence of the operation. | [
"Get",
"the",
"name",
"of",
"an",
"opcode",
"given",
"the",
"op",
"byte",
"sequence",
"of",
"the",
"operation",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1138-L1152 |
230,557 | blockstack/blockstack-core | blockstack/lib/config.py | get_announce_filename | 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 | 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 | [
"def",
"get_announce_filename",
"(",
"working_dir",
")",
":",
"announce_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"get_default_virtualchain_impl",
"(",
")",
".",
"get_virtual_chain_name",
"(",
")",
")",
"+",
"'.announce'",
"return",
"announce_filepath"
] | Get the path to the file that stores all of the announcements. | [
"Get",
"the",
"path",
"to",
"the",
"file",
"that",
"stores",
"all",
"of",
"the",
"announcements",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1168-L1173 |
230,558 | blockstack/blockstack-core | blockstack/lib/config.py | is_indexing | 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 | 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 | [
"def",
"is_indexing",
"(",
"working_dir",
")",
":",
"indexing_path",
"=",
"get_indexing_lockfile",
"(",
"working_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"indexing_path",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Is the blockstack daemon synchronizing with the blockchain? | [
"Is",
"the",
"blockstack",
"daemon",
"synchronizing",
"with",
"the",
"blockchain?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1231-L1239 |
230,559 | blockstack/blockstack-core | blockstack/lib/config.py | set_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:
return False
else:
try:
os.unlink( indexing_path )
return True
except:
return False | python | 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:
return False
else:
try:
os.unlink( indexing_path )
return True
except:
return False | [
"def",
"set_indexing",
"(",
"working_dir",
",",
"flag",
")",
":",
"indexing_path",
"=",
"get_indexing_lockfile",
"(",
"working_dir",
")",
"if",
"flag",
":",
"try",
":",
"fd",
"=",
"open",
"(",
"indexing_path",
",",
"\"w+\"",
")",
"fd",
".",
"close",
"(",
")",
"return",
"True",
"except",
":",
"return",
"False",
"else",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"indexing_path",
")",
"return",
"True",
"except",
":",
"return",
"False"
] | Set a flag in the filesystem as to whether or not we're indexing. | [
"Set",
"a",
"flag",
"in",
"the",
"filesystem",
"as",
"to",
"whether",
"or",
"not",
"we",
"re",
"indexing",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1242-L1260 |
230,560 | blockstack/blockstack-core | blockstack/lib/config.py | set_recovery_range | 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.path.join(working_dir, '.recovery')
with open(recovery_range_path, 'w') as f:
f.write('{}\n{}\n'.format(start_block, end_block))
f.flush()
os.fsync(f.fileno()) | python | 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.path.join(working_dir, '.recovery')
with open(recovery_range_path, 'w') as f:
f.write('{}\n{}\n'.format(start_block, end_block))
f.flush()
os.fsync(f.fileno()) | [
"def",
"set_recovery_range",
"(",
"working_dir",
",",
"start_block",
",",
"end_block",
")",
":",
"recovery_range_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"'.recovery'",
")",
"with",
"open",
"(",
"recovery_range_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'{}\\n{}\\n'",
".",
"format",
"(",
"start_block",
",",
"end_block",
")",
")",
"f",
".",
"flush",
"(",
")",
"os",
".",
"fsync",
"(",
"f",
".",
"fileno",
"(",
")",
")"
] | 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 | [
"Set",
"the",
"recovery",
"block",
"range",
"if",
"we",
"re",
"restoring",
"and",
"reporcessing",
"transactions",
"from",
"a",
"backup",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1304-L1315 |
230,561 | blockstack/blockstack-core | blockstack/lib/config.py | clear_recovery_range | 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) | python | 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) | [
"def",
"clear_recovery_range",
"(",
"working_dir",
")",
":",
"recovery_range_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"'.recovery'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"recovery_range_path",
")",
":",
"os",
".",
"unlink",
"(",
"recovery_range_path",
")"
] | Clear out our recovery hint | [
"Clear",
"out",
"our",
"recovery",
"hint"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1318-L1324 |
230,562 | blockstack/blockstack-core | blockstack/lib/config.py | is_atlas_enabled | 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 'atlasdb_path' not in blockstack_opts:
log.debug("Atlas is disabled: no 'atlasdb_path' path set")
return False
return True | python | 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 'atlasdb_path' not in blockstack_opts:
log.debug("Atlas is disabled: no 'atlasdb_path' path set")
return False
return True | [
"def",
"is_atlas_enabled",
"(",
"blockstack_opts",
")",
":",
"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",
"'atlasdb_path'",
"not",
"in",
"blockstack_opts",
":",
"log",
".",
"debug",
"(",
"\"Atlas is disabled: no 'atlasdb_path' path set\"",
")",
"return",
"False",
"return",
"True"
] | Can we do atlas operations? | [
"Can",
"we",
"do",
"atlas",
"operations?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1327-L1343 |
230,563 | blockstack/blockstack-core | blockstack/lib/config.py | is_subdomains_enabled | 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_path' path set")
return False
return True | python | 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_path' path set")
return False
return True | [
"def",
"is_subdomains_enabled",
"(",
"blockstack_opts",
")",
":",
"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_path' path set\"",
")",
"return",
"False",
"return",
"True"
] | Can we do subdomain operations? | [
"Can",
"we",
"do",
"subdomain",
"operations?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1346-L1358 |
230,564 | blockstack/blockstack-core | blockstack/lib/config.py | store_announcement | 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_announce_filename( working_dir )
announce_filename_tmp = announce_filename + ".tmp"
announce_text = ""
announce_cleanup_list = []
# did we try (and fail) to store a previous announcement? If so, merge them all
if os.path.exists( announce_filename_tmp ):
log.debug("Merge announcement list %s" % announce_filename_tmp )
with open(announce_filename, "r") as f:
announce_text += f.read()
i = 1
failed_path = announce_filename_tmp + (".%s" % i)
while os.path.exists( failed_path ):
log.debug("Merge announcement list %s" % failed_path )
with open(failed_path, "r") as f:
announce_text += f.read()
announce_cleanup_list.append( failed_path )
i += 1
failed_path = announce_filename_tmp + (".%s" % i)
announce_filename_tmp = failed_path
if os.path.exists( announce_filename ):
with open(announce_filename, "r" ) as f:
announce_text += f.read()
announce_text += ("\n%s\n" % announcement_hash)
# filter
if not force:
announcement_list = announce_text.split("\n")
unseen_announcements = filter( lambda a: a not in ANNOUNCEMENTS, announcement_list )
announce_text = "\n".join( unseen_announcements ).strip() + "\n"
log.debug("Store announcement hash to %s" % announce_filename )
with open(announce_filename_tmp, "w" ) as f:
f.write( announce_text )
f.flush()
# NOTE: rename doesn't remove the old file on Windows
if sys.platform == 'win32' and os.path.exists( announce_filename_tmp ):
try:
os.unlink( announce_filename_tmp )
except:
pass
try:
os.rename( announce_filename_tmp, announce_filename )
except:
log.error("Failed to save announcement %s to %s" % (announcement_hash, announce_filename ))
raise
# clean up
for tmp_path in announce_cleanup_list:
try:
os.unlink( tmp_path )
except:
pass
# put the announcement text
announcement_text_dir = os.path.join( working_dir, "announcements" )
if not os.path.exists( announcement_text_dir ):
try:
os.makedirs( announcement_text_dir )
except:
log.error("Failed to make directory %s" % announcement_text_dir )
raise
announcement_text_path = os.path.join( announcement_text_dir, "%s.txt" % announcement_hash )
try:
with open( announcement_text_path, "w" ) as f:
f.write( announcement_text )
except:
log.error("Failed to save announcement text to %s" % announcement_text_path )
raise
log.debug("Stored announcement to %s" % (announcement_text_path)) | python | 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_announce_filename( working_dir )
announce_filename_tmp = announce_filename + ".tmp"
announce_text = ""
announce_cleanup_list = []
# did we try (and fail) to store a previous announcement? If so, merge them all
if os.path.exists( announce_filename_tmp ):
log.debug("Merge announcement list %s" % announce_filename_tmp )
with open(announce_filename, "r") as f:
announce_text += f.read()
i = 1
failed_path = announce_filename_tmp + (".%s" % i)
while os.path.exists( failed_path ):
log.debug("Merge announcement list %s" % failed_path )
with open(failed_path, "r") as f:
announce_text += f.read()
announce_cleanup_list.append( failed_path )
i += 1
failed_path = announce_filename_tmp + (".%s" % i)
announce_filename_tmp = failed_path
if os.path.exists( announce_filename ):
with open(announce_filename, "r" ) as f:
announce_text += f.read()
announce_text += ("\n%s\n" % announcement_hash)
# filter
if not force:
announcement_list = announce_text.split("\n")
unseen_announcements = filter( lambda a: a not in ANNOUNCEMENTS, announcement_list )
announce_text = "\n".join( unseen_announcements ).strip() + "\n"
log.debug("Store announcement hash to %s" % announce_filename )
with open(announce_filename_tmp, "w" ) as f:
f.write( announce_text )
f.flush()
# NOTE: rename doesn't remove the old file on Windows
if sys.platform == 'win32' and os.path.exists( announce_filename_tmp ):
try:
os.unlink( announce_filename_tmp )
except:
pass
try:
os.rename( announce_filename_tmp, announce_filename )
except:
log.error("Failed to save announcement %s to %s" % (announcement_hash, announce_filename ))
raise
# clean up
for tmp_path in announce_cleanup_list:
try:
os.unlink( tmp_path )
except:
pass
# put the announcement text
announcement_text_dir = os.path.join( working_dir, "announcements" )
if not os.path.exists( announcement_text_dir ):
try:
os.makedirs( announcement_text_dir )
except:
log.error("Failed to make directory %s" % announcement_text_dir )
raise
announcement_text_path = os.path.join( announcement_text_dir, "%s.txt" % announcement_hash )
try:
with open( announcement_text_path, "w" ) as f:
f.write( announcement_text )
except:
log.error("Failed to save announcement text to %s" % announcement_text_path )
raise
log.debug("Stored announcement to %s" % (announcement_text_path)) | [
"def",
"store_announcement",
"(",
"working_dir",
",",
"announcement_hash",
",",
"announcement_text",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"# don't store unless we haven't seen it before",
"if",
"announcement_hash",
"in",
"ANNOUNCEMENTS",
":",
"return",
"announce_filename",
"=",
"get_announce_filename",
"(",
"working_dir",
")",
"announce_filename_tmp",
"=",
"announce_filename",
"+",
"\".tmp\"",
"announce_text",
"=",
"\"\"",
"announce_cleanup_list",
"=",
"[",
"]",
"# did we try (and fail) to store a previous announcement? If so, merge them all",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"announce_filename_tmp",
")",
":",
"log",
".",
"debug",
"(",
"\"Merge announcement list %s\"",
"%",
"announce_filename_tmp",
")",
"with",
"open",
"(",
"announce_filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"announce_text",
"+=",
"f",
".",
"read",
"(",
")",
"i",
"=",
"1",
"failed_path",
"=",
"announce_filename_tmp",
"+",
"(",
"\".%s\"",
"%",
"i",
")",
"while",
"os",
".",
"path",
".",
"exists",
"(",
"failed_path",
")",
":",
"log",
".",
"debug",
"(",
"\"Merge announcement list %s\"",
"%",
"failed_path",
")",
"with",
"open",
"(",
"failed_path",
",",
"\"r\"",
")",
"as",
"f",
":",
"announce_text",
"+=",
"f",
".",
"read",
"(",
")",
"announce_cleanup_list",
".",
"append",
"(",
"failed_path",
")",
"i",
"+=",
"1",
"failed_path",
"=",
"announce_filename_tmp",
"+",
"(",
"\".%s\"",
"%",
"i",
")",
"announce_filename_tmp",
"=",
"failed_path",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"announce_filename",
")",
":",
"with",
"open",
"(",
"announce_filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"announce_text",
"+=",
"f",
".",
"read",
"(",
")",
"announce_text",
"+=",
"(",
"\"\\n%s\\n\"",
"%",
"announcement_hash",
")",
"# filter",
"if",
"not",
"force",
":",
"announcement_list",
"=",
"announce_text",
".",
"split",
"(",
"\"\\n\"",
")",
"unseen_announcements",
"=",
"filter",
"(",
"lambda",
"a",
":",
"a",
"not",
"in",
"ANNOUNCEMENTS",
",",
"announcement_list",
")",
"announce_text",
"=",
"\"\\n\"",
".",
"join",
"(",
"unseen_announcements",
")",
".",
"strip",
"(",
")",
"+",
"\"\\n\"",
"log",
".",
"debug",
"(",
"\"Store announcement hash to %s\"",
"%",
"announce_filename",
")",
"with",
"open",
"(",
"announce_filename_tmp",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"announce_text",
")",
"f",
".",
"flush",
"(",
")",
"# NOTE: rename doesn't remove the old file on Windows",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"announce_filename_tmp",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"announce_filename_tmp",
")",
"except",
":",
"pass",
"try",
":",
"os",
".",
"rename",
"(",
"announce_filename_tmp",
",",
"announce_filename",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Failed to save announcement %s to %s\"",
"%",
"(",
"announcement_hash",
",",
"announce_filename",
")",
")",
"raise",
"# clean up",
"for",
"tmp_path",
"in",
"announce_cleanup_list",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"tmp_path",
")",
"except",
":",
"pass",
"# put the announcement text",
"announcement_text_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"\"announcements\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"announcement_text_dir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"announcement_text_dir",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Failed to make directory %s\"",
"%",
"announcement_text_dir",
")",
"raise",
"announcement_text_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"announcement_text_dir",
",",
"\"%s.txt\"",
"%",
"announcement_hash",
")",
"try",
":",
"with",
"open",
"(",
"announcement_text_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"announcement_text",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Failed to save announcement text to %s\"",
"%",
"announcement_text_path",
")",
"raise",
"log",
".",
"debug",
"(",
"\"Stored announcement to %s\"",
"%",
"(",
"announcement_text_path",
")",
")"
] | Store a new announcement locally, atomically. | [
"Store",
"a",
"new",
"announcement",
"locally",
"atomically",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1361-L1456 |
230,565 | blockstack/blockstack-core | blockstack/lib/config.py | default_blockstack_api_opts | 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_virtualchain_impl(), working_dir)
parser = SafeConfigParser()
parser.read(config_file)
blockstack_api_opts = {}
indexer_url = None
api_port = DEFAULT_API_PORT
api_host = DEFAULT_API_HOST
run_api = True
if parser.has_section('blockstack-api'):
if parser.has_option('blockstack-api', 'enabled'):
run_api = parser.get('blockstack-api', 'enabled').lower() in ['true', '1', 'on']
if parser.has_option('blockstack-api', 'api_port'):
api_port = int(parser.get('blockstack-api', 'api_port'))
if parser.has_option('blockstack-api', 'api_host'):
api_host = parser.get('blockstack-api', 'api_host')
if parser.has_option('blockstack-api', 'indexer_url'):
indexer_host, indexer_port = url_to_host_port(parser.get('blockstack-api', 'indexer_url'))
indexer_protocol = url_protocol(parser.get('blockstack-api', 'indexer_url'))
if indexer_protocol is None:
indexer_protocol = 'http'
indexer_url = parser.get('blockstack-api', 'indexer_url')
if indexer_url is None:
# try defaults
indexer_url = 'http://localhost:{}'.format(RPC_SERVER_PORT)
blockstack_api_opts = {
'indexer_url': indexer_url,
'api_host': api_host,
'api_port': api_port,
'enabled': run_api
}
# strip Nones
for (k, v) in blockstack_api_opts.items():
if v is None:
del blockstack_api_opts[k]
return blockstack_api_opts | python | 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_virtualchain_impl(), working_dir)
parser = SafeConfigParser()
parser.read(config_file)
blockstack_api_opts = {}
indexer_url = None
api_port = DEFAULT_API_PORT
api_host = DEFAULT_API_HOST
run_api = True
if parser.has_section('blockstack-api'):
if parser.has_option('blockstack-api', 'enabled'):
run_api = parser.get('blockstack-api', 'enabled').lower() in ['true', '1', 'on']
if parser.has_option('blockstack-api', 'api_port'):
api_port = int(parser.get('blockstack-api', 'api_port'))
if parser.has_option('blockstack-api', 'api_host'):
api_host = parser.get('blockstack-api', 'api_host')
if parser.has_option('blockstack-api', 'indexer_url'):
indexer_host, indexer_port = url_to_host_port(parser.get('blockstack-api', 'indexer_url'))
indexer_protocol = url_protocol(parser.get('blockstack-api', 'indexer_url'))
if indexer_protocol is None:
indexer_protocol = 'http'
indexer_url = parser.get('blockstack-api', 'indexer_url')
if indexer_url is None:
# try defaults
indexer_url = 'http://localhost:{}'.format(RPC_SERVER_PORT)
blockstack_api_opts = {
'indexer_url': indexer_url,
'api_host': api_host,
'api_port': api_port,
'enabled': run_api
}
# strip Nones
for (k, v) in blockstack_api_opts.items():
if v is None:
del blockstack_api_opts[k]
return blockstack_api_opts | [
"def",
"default_blockstack_api_opts",
"(",
"working_dir",
",",
"config_file",
"=",
"None",
")",
":",
"from",
".",
"util",
"import",
"url_to_host_port",
",",
"url_protocol",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"virtualchain",
".",
"get_config_filename",
"(",
"get_default_virtualchain_impl",
"(",
")",
",",
"working_dir",
")",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"config_file",
")",
"blockstack_api_opts",
"=",
"{",
"}",
"indexer_url",
"=",
"None",
"api_port",
"=",
"DEFAULT_API_PORT",
"api_host",
"=",
"DEFAULT_API_HOST",
"run_api",
"=",
"True",
"if",
"parser",
".",
"has_section",
"(",
"'blockstack-api'",
")",
":",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'enabled'",
")",
":",
"run_api",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'enabled'",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'true'",
",",
"'1'",
",",
"'on'",
"]",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'api_port'",
")",
":",
"api_port",
"=",
"int",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'api_port'",
")",
")",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'api_host'",
")",
":",
"api_host",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'api_host'",
")",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
":",
"indexer_host",
",",
"indexer_port",
"=",
"url_to_host_port",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
")",
"indexer_protocol",
"=",
"url_protocol",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
")",
"if",
"indexer_protocol",
"is",
"None",
":",
"indexer_protocol",
"=",
"'http'",
"indexer_url",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
"if",
"indexer_url",
"is",
"None",
":",
"# try defaults",
"indexer_url",
"=",
"'http://localhost:{}'",
".",
"format",
"(",
"RPC_SERVER_PORT",
")",
"blockstack_api_opts",
"=",
"{",
"'indexer_url'",
":",
"indexer_url",
",",
"'api_host'",
":",
"api_host",
",",
"'api_port'",
":",
"api_port",
",",
"'enabled'",
":",
"run_api",
"}",
"# strip Nones",
"for",
"(",
"k",
",",
"v",
")",
"in",
"blockstack_api_opts",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"del",
"blockstack_api_opts",
"[",
"k",
"]",
"return",
"blockstack_api_opts"
] | Get our default blockstack RESTful API opts from a config file,
or from sane defaults. | [
"Get",
"our",
"default",
"blockstack",
"RESTful",
"API",
"opts",
"from",
"a",
"config",
"file",
"or",
"from",
"sane",
"defaults",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1679-L1733 |
230,566 | blockstack/blockstack-core | blockstack/lib/config.py | interactive_prompt | 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('-' * max_line_len)
print(message)
print('-' * max_line_len)
ret = {}
for param in parameters:
formatted_param = param
prompt_str = '{}: '.format(formatted_param)
if param in default_opts:
prompt_str = '{} (default: "{}"): '.format(formatted_param, default_opts[param])
try:
value = raw_input(prompt_str)
except KeyboardInterrupt:
log.debug('Exiting on keyboard interrupt')
sys.exit(0)
if len(value) > 0:
ret[param] = value
elif param in default_opts:
ret[param] = default_opts[param]
else:
ret[param] = None
return ret | python | 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('-' * max_line_len)
print(message)
print('-' * max_line_len)
ret = {}
for param in parameters:
formatted_param = param
prompt_str = '{}: '.format(formatted_param)
if param in default_opts:
prompt_str = '{} (default: "{}"): '.format(formatted_param, default_opts[param])
try:
value = raw_input(prompt_str)
except KeyboardInterrupt:
log.debug('Exiting on keyboard interrupt')
sys.exit(0)
if len(value) > 0:
ret[param] = value
elif param in default_opts:
ret[param] = default_opts[param]
else:
ret[param] = None
return ret | [
"def",
"interactive_prompt",
"(",
"message",
",",
"parameters",
",",
"default_opts",
")",
":",
"# pretty-print the message",
"lines",
"=",
"message",
".",
"split",
"(",
"'\\n'",
")",
"max_line_len",
"=",
"max",
"(",
"[",
"len",
"(",
"l",
")",
"for",
"l",
"in",
"lines",
"]",
")",
"print",
"(",
"'-'",
"*",
"max_line_len",
")",
"print",
"(",
"message",
")",
"print",
"(",
"'-'",
"*",
"max_line_len",
")",
"ret",
"=",
"{",
"}",
"for",
"param",
"in",
"parameters",
":",
"formatted_param",
"=",
"param",
"prompt_str",
"=",
"'{}: '",
".",
"format",
"(",
"formatted_param",
")",
"if",
"param",
"in",
"default_opts",
":",
"prompt_str",
"=",
"'{} (default: \"{}\"): '",
".",
"format",
"(",
"formatted_param",
",",
"default_opts",
"[",
"param",
"]",
")",
"try",
":",
"value",
"=",
"raw_input",
"(",
"prompt_str",
")",
"except",
"KeyboardInterrupt",
":",
"log",
".",
"debug",
"(",
"'Exiting on keyboard interrupt'",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"len",
"(",
"value",
")",
">",
"0",
":",
"ret",
"[",
"param",
"]",
"=",
"value",
"elif",
"param",
"in",
"default_opts",
":",
"ret",
"[",
"param",
"]",
"=",
"default_opts",
"[",
"param",
"]",
"else",
":",
"ret",
"[",
"param",
"]",
"=",
"None",
"return",
"ret"
] | Prompt the user for a series of parameters
Return a dict mapping the parameter name to the
user-given value. | [
"Prompt",
"the",
"user",
"for",
"a",
"series",
"of",
"parameters",
"Return",
"a",
"dict",
"mapping",
"the",
"parameter",
"name",
"to",
"the",
"user",
"-",
"given",
"value",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1736-L1771 |
230,567 | blockstack/blockstack-core | blockstack/lib/config.py | find_missing | 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), with the user's input.
"""
# are we missing anything?
missing_params = list(set(all_params) - set(given_opts))
num_prompted = 0
if not missing_params:
return given_opts, missing_params, num_prompted
if not prompt_missing:
# count the number missing, and go with defaults
missing_values = set(default_opts) - set(given_opts)
num_prompted = len(missing_values)
given_opts.update(default_opts)
else:
if header is not None:
print('-' * len(header))
print(header)
missing_values = interactive_prompt(message, missing_params, default_opts)
num_prompted = len(missing_values)
given_opts.update(missing_values)
return given_opts, missing_params, num_prompted | python | 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), with the user's input.
"""
# are we missing anything?
missing_params = list(set(all_params) - set(given_opts))
num_prompted = 0
if not missing_params:
return given_opts, missing_params, num_prompted
if not prompt_missing:
# count the number missing, and go with defaults
missing_values = set(default_opts) - set(given_opts)
num_prompted = len(missing_values)
given_opts.update(default_opts)
else:
if header is not None:
print('-' * len(header))
print(header)
missing_values = interactive_prompt(message, missing_params, default_opts)
num_prompted = len(missing_values)
given_opts.update(missing_values)
return given_opts, missing_params, num_prompted | [
"def",
"find_missing",
"(",
"message",
",",
"all_params",
",",
"given_opts",
",",
"default_opts",
",",
"header",
"=",
"None",
",",
"prompt_missing",
"=",
"True",
")",
":",
"# are we missing anything?",
"missing_params",
"=",
"list",
"(",
"set",
"(",
"all_params",
")",
"-",
"set",
"(",
"given_opts",
")",
")",
"num_prompted",
"=",
"0",
"if",
"not",
"missing_params",
":",
"return",
"given_opts",
",",
"missing_params",
",",
"num_prompted",
"if",
"not",
"prompt_missing",
":",
"# count the number missing, and go with defaults",
"missing_values",
"=",
"set",
"(",
"default_opts",
")",
"-",
"set",
"(",
"given_opts",
")",
"num_prompted",
"=",
"len",
"(",
"missing_values",
")",
"given_opts",
".",
"update",
"(",
"default_opts",
")",
"else",
":",
"if",
"header",
"is",
"not",
"None",
":",
"print",
"(",
"'-'",
"*",
"len",
"(",
"header",
")",
")",
"print",
"(",
"header",
")",
"missing_values",
"=",
"interactive_prompt",
"(",
"message",
",",
"missing_params",
",",
"default_opts",
")",
"num_prompted",
"=",
"len",
"(",
"missing_values",
")",
"given_opts",
".",
"update",
"(",
"missing_values",
")",
"return",
"given_opts",
",",
"missing_params",
",",
"num_prompted"
] | 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. | [
"Find",
"and",
"interactively",
"prompt",
"the",
"user",
"for",
"missing",
"parameters",
"given",
"the",
"list",
"of",
"all",
"valid",
"parameters",
"and",
"a",
"dict",
"of",
"known",
"options",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1774-L1805 |
230,568 | blockstack/blockstack-core | blockstack/lib/config.py | opt_strip | 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_name] = opt_value
return ret | python | 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_name] = opt_value
return ret | [
"def",
"opt_strip",
"(",
"prefix",
",",
"opts",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"opt_name",
",",
"opt_value",
"in",
"opts",
".",
"items",
"(",
")",
":",
"# remove prefix",
"if",
"opt_name",
".",
"startswith",
"(",
"prefix",
")",
":",
"opt_name",
"=",
"opt_name",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"ret",
"[",
"opt_name",
"]",
"=",
"opt_value",
"return",
"ret"
] | Given a dict of opts that start with prefix,
remove the prefix from each of them. | [
"Given",
"a",
"dict",
"of",
"opts",
"that",
"start",
"with",
"prefix",
"remove",
"the",
"prefix",
"from",
"each",
"of",
"them",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1808-L1822 |
230,569 | blockstack/blockstack-core | blockstack/lib/config.py | opt_restore | 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()} | python | 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()} | [
"def",
"opt_restore",
"(",
"prefix",
",",
"opts",
")",
":",
"return",
"{",
"prefix",
"+",
"name",
":",
"value",
"for",
"name",
",",
"value",
"in",
"opts",
".",
"items",
"(",
")",
"}"
] | Given a dict of opts, add the given prefix to each key | [
"Given",
"a",
"dict",
"of",
"opts",
"add",
"the",
"given",
"prefix",
"to",
"each",
"key"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1831-L1836 |
230,570 | blockstack/blockstack-core | blockstack/lib/config.py | default_bitcoind_opts | 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: v for k, v in default_bitcoin_opts.items() if v is not None}
# strip 'bitcoind_'
if not prefix:
default_bitcoin_opts = opt_strip('bitcoind_', default_bitcoin_opts)
return default_bitcoin_opts | python | 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: v for k, v in default_bitcoin_opts.items() if v is not None}
# strip 'bitcoind_'
if not prefix:
default_bitcoin_opts = opt_strip('bitcoind_', default_bitcoin_opts)
return default_bitcoin_opts | [
"def",
"default_bitcoind_opts",
"(",
"config_file",
"=",
"None",
",",
"prefix",
"=",
"False",
")",
":",
"default_bitcoin_opts",
"=",
"virtualchain",
".",
"get_bitcoind_config",
"(",
"config_file",
"=",
"config_file",
")",
"# drop dict values that are None",
"default_bitcoin_opts",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"default_bitcoin_opts",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"# strip 'bitcoind_'",
"if",
"not",
"prefix",
":",
"default_bitcoin_opts",
"=",
"opt_strip",
"(",
"'bitcoind_'",
",",
"default_bitcoin_opts",
")",
"return",
"default_bitcoin_opts"
] | Get our default bitcoind options, such as from a config file,
or from sane defaults | [
"Get",
"our",
"default",
"bitcoind",
"options",
"such",
"as",
"from",
"a",
"config",
"file",
"or",
"from",
"sane",
"defaults"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1839-L1854 |
230,571 | blockstack/blockstack-core | blockstack/lib/config.py | default_working_dir | 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())) | python | 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())) | [
"def",
"default_working_dir",
"(",
")",
":",
"import",
"nameset",
".",
"virtualchain_hooks",
"as",
"virtualchain_hooks",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.{}'",
".",
"format",
"(",
"virtualchain_hooks",
".",
"get_virtual_chain_name",
"(",
")",
")",
")"
] | Get the default configuration directory for blockstackd | [
"Get",
"the",
"default",
"configuration",
"directory",
"for",
"blockstackd"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1857-L1862 |
230,572 | blockstack/blockstack-core | blockstack/lib/config.py | write_config_file | 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
Raise on error
"""
parser = SafeConfigParser()
if os.path.exists(config_file):
parser.read(config_file)
for sec_name in opts:
sec_opts = opts[sec_name]
if parser.has_section(sec_name):
parser.remove_section(sec_name)
parser.add_section(sec_name)
for opt_name, opt_value in sec_opts.items():
if opt_value is None:
opt_value = ''
parser.set(sec_name, opt_name, '{}'.format(opt_value))
with open(config_file, 'w') as fout:
os.fchmod(fout.fileno(), 0600)
parser.write(fout)
return True | python | 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
Raise on error
"""
parser = SafeConfigParser()
if os.path.exists(config_file):
parser.read(config_file)
for sec_name in opts:
sec_opts = opts[sec_name]
if parser.has_section(sec_name):
parser.remove_section(sec_name)
parser.add_section(sec_name)
for opt_name, opt_value in sec_opts.items():
if opt_value is None:
opt_value = ''
parser.set(sec_name, opt_name, '{}'.format(opt_value))
with open(config_file, 'w') as fout:
os.fchmod(fout.fileno(), 0600)
parser.write(fout)
return True | [
"def",
"write_config_file",
"(",
"opts",
",",
"config_file",
")",
":",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"parser",
".",
"read",
"(",
"config_file",
")",
"for",
"sec_name",
"in",
"opts",
":",
"sec_opts",
"=",
"opts",
"[",
"sec_name",
"]",
"if",
"parser",
".",
"has_section",
"(",
"sec_name",
")",
":",
"parser",
".",
"remove_section",
"(",
"sec_name",
")",
"parser",
".",
"add_section",
"(",
"sec_name",
")",
"for",
"opt_name",
",",
"opt_value",
"in",
"sec_opts",
".",
"items",
"(",
")",
":",
"if",
"opt_value",
"is",
"None",
":",
"opt_value",
"=",
"''",
"parser",
".",
"set",
"(",
"sec_name",
",",
"opt_name",
",",
"'{}'",
".",
"format",
"(",
"opt_value",
")",
")",
"with",
"open",
"(",
"config_file",
",",
"'w'",
")",
"as",
"fout",
":",
"os",
".",
"fchmod",
"(",
"fout",
".",
"fileno",
"(",
")",
",",
"0600",
")",
"parser",
".",
"write",
"(",
"fout",
")",
"return",
"True"
] | 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 | [
"Write",
"our",
"config",
"file",
"with",
"the",
"given",
"options",
"dict",
".",
"Each",
"key",
"is",
"a",
"section",
"name",
"and",
"each",
"value",
"is",
"the",
"list",
"of",
"options",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L1976-L2009 |
230,573 | blockstack/blockstack-core | blockstack/lib/config.py | load_configuration | 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 = configure(working_dir)
blockstack_opts = opts.get('blockstack', None)
blockstack_api_opts = opts.get('blockstack-api', None)
bitcoin_opts = opts['bitcoind']
# config file version check
config_server_version = blockstack_opts.get('server_version', None)
if (config_server_version is None or versions_need_upgrade(config_server_version, VERSION)):
print >> sys.stderr, "Obsolete or unrecognizable config file ({}): '{}' != '{}'".format(virtualchain.get_config_filename(virtualchain_hooks, working_dir), config_server_version, VERSION)
print >> sys.stderr, 'Please see the release notes for version {} for instructions to upgrade (in the release-notes/ folder).'.format(VERSION)
return None
# store options
set_bitcoin_opts( bitcoin_opts )
set_blockstack_opts( blockstack_opts )
set_blockstack_api_opts( blockstack_api_opts )
return {
'bitcoind': bitcoin_opts,
'blockstack': blockstack_opts,
'blockstack-api': blockstack_api_opts
} | python | 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 = configure(working_dir)
blockstack_opts = opts.get('blockstack', None)
blockstack_api_opts = opts.get('blockstack-api', None)
bitcoin_opts = opts['bitcoind']
# config file version check
config_server_version = blockstack_opts.get('server_version', None)
if (config_server_version is None or versions_need_upgrade(config_server_version, VERSION)):
print >> sys.stderr, "Obsolete or unrecognizable config file ({}): '{}' != '{}'".format(virtualchain.get_config_filename(virtualchain_hooks, working_dir), config_server_version, VERSION)
print >> sys.stderr, 'Please see the release notes for version {} for instructions to upgrade (in the release-notes/ folder).'.format(VERSION)
return None
# store options
set_bitcoin_opts( bitcoin_opts )
set_blockstack_opts( blockstack_opts )
set_blockstack_api_opts( blockstack_api_opts )
return {
'bitcoind': bitcoin_opts,
'blockstack': blockstack_opts,
'blockstack-api': blockstack_api_opts
} | [
"def",
"load_configuration",
"(",
"working_dir",
")",
":",
"import",
"nameset",
".",
"virtualchain_hooks",
"as",
"virtualchain_hooks",
"# acquire configuration, and store it globally",
"opts",
"=",
"configure",
"(",
"working_dir",
")",
"blockstack_opts",
"=",
"opts",
".",
"get",
"(",
"'blockstack'",
",",
"None",
")",
"blockstack_api_opts",
"=",
"opts",
".",
"get",
"(",
"'blockstack-api'",
",",
"None",
")",
"bitcoin_opts",
"=",
"opts",
"[",
"'bitcoind'",
"]",
"# config file version check",
"config_server_version",
"=",
"blockstack_opts",
".",
"get",
"(",
"'server_version'",
",",
"None",
")",
"if",
"(",
"config_server_version",
"is",
"None",
"or",
"versions_need_upgrade",
"(",
"config_server_version",
",",
"VERSION",
")",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Obsolete or unrecognizable config file ({}): '{}' != '{}'\"",
".",
"format",
"(",
"virtualchain",
".",
"get_config_filename",
"(",
"virtualchain_hooks",
",",
"working_dir",
")",
",",
"config_server_version",
",",
"VERSION",
")",
"print",
">>",
"sys",
".",
"stderr",
",",
"'Please see the release notes for version {} for instructions to upgrade (in the release-notes/ folder).'",
".",
"format",
"(",
"VERSION",
")",
"return",
"None",
"# store options",
"set_bitcoin_opts",
"(",
"bitcoin_opts",
")",
"set_blockstack_opts",
"(",
"blockstack_opts",
")",
"set_blockstack_api_opts",
"(",
"blockstack_api_opts",
")",
"return",
"{",
"'bitcoind'",
":",
"bitcoin_opts",
",",
"'blockstack'",
":",
"blockstack_opts",
",",
"'blockstack-api'",
":",
"blockstack_api_opts",
"}"
] | Load the system configuration and set global variables
Return the configuration of the node on success.
Return None on failure | [
"Load",
"the",
"system",
"configuration",
"and",
"set",
"global",
"variables",
"Return",
"the",
"configuration",
"of",
"the",
"node",
"on",
"success",
".",
"Return",
"None",
"on",
"failure"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/config.py#L2075-L2106 |
230,574 | blockstack/blockstack-core | blockstack/lib/operations/namespaceready.py | check | 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 = nameop['namespace_id']
sender = nameop['sender']
# must have been revealed
if not state_engine.is_namespace_revealed( namespace_id ):
log.warning("Namespace '%s' is not revealed" % namespace_id )
return False
# must have been sent by the same person who revealed it
revealed_namespace = state_engine.get_namespace_reveal( namespace_id )
if revealed_namespace['recipient'] != sender:
log.warning("Namespace '%s' is not owned by '%s' (but by %s)" % (namespace_id, sender, revealed_namespace['recipient']))
return False
# can't be ready yet
if state_engine.is_namespace_ready( namespace_id ):
# namespace already exists
log.warning("Namespace '%s' is already registered" % namespace_id )
return False
# preserve from revealed
nameop['sender_pubkey'] = revealed_namespace['sender_pubkey']
nameop['address'] = revealed_namespace['address']
# can commit imported nameops
return True | python | 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 = nameop['namespace_id']
sender = nameop['sender']
# must have been revealed
if not state_engine.is_namespace_revealed( namespace_id ):
log.warning("Namespace '%s' is not revealed" % namespace_id )
return False
# must have been sent by the same person who revealed it
revealed_namespace = state_engine.get_namespace_reveal( namespace_id )
if revealed_namespace['recipient'] != sender:
log.warning("Namespace '%s' is not owned by '%s' (but by %s)" % (namespace_id, sender, revealed_namespace['recipient']))
return False
# can't be ready yet
if state_engine.is_namespace_ready( namespace_id ):
# namespace already exists
log.warning("Namespace '%s' is already registered" % namespace_id )
return False
# preserve from revealed
nameop['sender_pubkey'] = revealed_namespace['sender_pubkey']
nameop['address'] = revealed_namespace['address']
# can commit imported nameops
return True | [
"def",
"check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"namespace_id",
"=",
"nameop",
"[",
"'namespace_id'",
"]",
"sender",
"=",
"nameop",
"[",
"'sender'",
"]",
"# must have been revealed",
"if",
"not",
"state_engine",
".",
"is_namespace_revealed",
"(",
"namespace_id",
")",
":",
"log",
".",
"warning",
"(",
"\"Namespace '%s' is not revealed\"",
"%",
"namespace_id",
")",
"return",
"False",
"# must have been sent by the same person who revealed it",
"revealed_namespace",
"=",
"state_engine",
".",
"get_namespace_reveal",
"(",
"namespace_id",
")",
"if",
"revealed_namespace",
"[",
"'recipient'",
"]",
"!=",
"sender",
":",
"log",
".",
"warning",
"(",
"\"Namespace '%s' is not owned by '%s' (but by %s)\"",
"%",
"(",
"namespace_id",
",",
"sender",
",",
"revealed_namespace",
"[",
"'recipient'",
"]",
")",
")",
"return",
"False",
"# can't be ready yet",
"if",
"state_engine",
".",
"is_namespace_ready",
"(",
"namespace_id",
")",
":",
"# namespace already exists",
"log",
".",
"warning",
"(",
"\"Namespace '%s' is already registered\"",
"%",
"namespace_id",
")",
"return",
"False",
"# preserve from revealed ",
"nameop",
"[",
"'sender_pubkey'",
"]",
"=",
"revealed_namespace",
"[",
"'sender_pubkey'",
"]",
"nameop",
"[",
"'address'",
"]",
"=",
"revealed_namespace",
"[",
"'address'",
"]",
"# can commit imported nameops",
"return",
"True"
] | 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. | [
"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",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/namespaceready.py#L52-L85 |
230,575 | blockstack/blockstack-core | blockstack/lib/b40.py | int_to_charset | 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(-1, B40_CHARS)
Traceback (most recent call last):
...
ValueError: "val" must be a non-negative integer.
"""
if val < 0:
raise ValueError('"val" must be a non-negative integer.')
if val == 0:
return charset[0]
output = ""
while val > 0:
val, digit = divmod(val, len(charset))
output += charset[digit]
# reverse the characters in the output and return
return output[::-1] | python | 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(-1, B40_CHARS)
Traceback (most recent call last):
...
ValueError: "val" must be a non-negative integer.
"""
if val < 0:
raise ValueError('"val" must be a non-negative integer.')
if val == 0:
return charset[0]
output = ""
while val > 0:
val, digit = divmod(val, len(charset))
output += charset[digit]
# reverse the characters in the output and return
return output[::-1] | [
"def",
"int_to_charset",
"(",
"val",
",",
"charset",
")",
":",
"if",
"val",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'\"val\" must be a non-negative integer.'",
")",
"if",
"val",
"==",
"0",
":",
"return",
"charset",
"[",
"0",
"]",
"output",
"=",
"\"\"",
"while",
"val",
">",
"0",
":",
"val",
",",
"digit",
"=",
"divmod",
"(",
"val",
",",
"len",
"(",
"charset",
")",
")",
"output",
"+=",
"charset",
"[",
"digit",
"]",
"# reverse the characters in the output and return",
"return",
"output",
"[",
":",
":",
"-",
"1",
"]"
] | 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 call last):
...
ValueError: "val" must be a non-negative integer. | [
"Turn",
"a",
"non",
"-",
"negative",
"integer",
"into",
"a",
"string",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/b40.py#L37-L65 |
230,576 | blockstack/blockstack-core | blockstack/lib/b40.py | charset_to_int | 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)
149190078205533
>>> charset_to_int('A', B40_CHARS)
Traceback (most recent call last):
...
ValueError: substring not found
"""
output = 0
for char in s:
output = output * len(charset) + charset.index(char)
return output | python | 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)
149190078205533
>>> charset_to_int('A', B40_CHARS)
Traceback (most recent call last):
...
ValueError: substring not found
"""
output = 0
for char in s:
output = output * len(charset) + charset.index(char)
return output | [
"def",
"charset_to_int",
"(",
"s",
",",
"charset",
")",
":",
"output",
"=",
"0",
"for",
"char",
"in",
"s",
":",
"output",
"=",
"output",
"*",
"len",
"(",
"charset",
")",
"+",
"charset",
".",
"index",
"(",
"char",
")",
"return",
"output"
] | 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_int('A', B40_CHARS)
Traceback (most recent call last):
...
ValueError: substring not found | [
"Turn",
"a",
"string",
"into",
"a",
"non",
"-",
"negative",
"integer",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/b40.py#L68-L90 |
230,577 | blockstack/blockstack-core | blockstack/lib/b40.py | change_charset | 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, target_charset)
return output_string | python | 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, target_charset)
return output_string | [
"def",
"change_charset",
"(",
"s",
",",
"original_charset",
",",
"target_charset",
")",
":",
"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",
",",
"target_charset",
")",
"return",
"output_string"
] | Convert a string from one charset to another. | [
"Convert",
"a",
"string",
"from",
"one",
"charset",
"to",
"another",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/b40.py#L93-L101 |
230,578 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | autofill | 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_fields:
if field == "opcode" and 'opcode' not in rec.keys():
assert 'op' in rec.keys(), "BUG: record is missing 'op'"
rec['opcode'] = op_get_opcode_name(rec['op'])
else:
raise Exception("Unknown autofill field '%s'" % field)
return rec
return wrapped_reader
return wrap | python | 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_fields:
if field == "opcode" and 'opcode' not in rec.keys():
assert 'op' in rec.keys(), "BUG: record is missing 'op'"
rec['opcode'] = op_get_opcode_name(rec['op'])
else:
raise Exception("Unknown autofill field '%s'" % field)
return rec
return wrapped_reader
return wrap | [
"def",
"autofill",
"(",
"*",
"autofill_fields",
")",
":",
"def",
"wrap",
"(",
"reader",
")",
":",
"def",
"wrapped_reader",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"rec",
"=",
"reader",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"if",
"rec",
"is",
"not",
"None",
":",
"for",
"field",
"in",
"autofill_fields",
":",
"if",
"field",
"==",
"\"opcode\"",
"and",
"'opcode'",
"not",
"in",
"rec",
".",
"keys",
"(",
")",
":",
"assert",
"'op'",
"in",
"rec",
".",
"keys",
"(",
")",
",",
"\"BUG: record is missing 'op'\"",
"rec",
"[",
"'opcode'",
"]",
"=",
"op_get_opcode_name",
"(",
"rec",
"[",
"'op'",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown autofill field '%s'\"",
"%",
"field",
")",
"return",
"rec",
"return",
"wrapped_reader",
"return",
"wrap"
] | Decorator to automatically fill in extra useful fields
that aren't stored in the db. | [
"Decorator",
"to",
"automatically",
"fill",
"in",
"extra",
"useful",
"fields",
"that",
"aren",
"t",
"stored",
"in",
"the",
"db",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L53-L71 |
230,579 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_readonly_instance | 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_path = virtualchain.get_db_filename(virtualchain_hooks, working_dir)
db = BlockstackDB(db_path, DISPOSITION_RO, working_dir, get_genesis_block(), expected_snapshots={})
rc = db.db_setup()
if not rc:
log.error("Failed to set up virtualchain state engine")
return None
return db | python | 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_path = virtualchain.get_db_filename(virtualchain_hooks, working_dir)
db = BlockstackDB(db_path, DISPOSITION_RO, working_dir, get_genesis_block(), expected_snapshots={})
rc = db.db_setup()
if not rc:
log.error("Failed to set up virtualchain state engine")
return None
return db | [
"def",
"get_readonly_instance",
"(",
"cls",
",",
"working_dir",
",",
"expected_snapshots",
"=",
"{",
"}",
")",
":",
"import",
"virtualchain_hooks",
"db_path",
"=",
"virtualchain",
".",
"get_db_filename",
"(",
"virtualchain_hooks",
",",
"working_dir",
")",
"db",
"=",
"BlockstackDB",
"(",
"db_path",
",",
"DISPOSITION_RO",
",",
"working_dir",
",",
"get_genesis_block",
"(",
")",
",",
"expected_snapshots",
"=",
"{",
"}",
")",
"rc",
"=",
"db",
".",
"db_setup",
"(",
")",
"if",
"not",
"rc",
":",
"log",
".",
"error",
"(",
"\"Failed to set up virtualchain state engine\"",
")",
"return",
"None",
"return",
"db"
] | 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 | [
"Get",
"a",
"read",
"-",
"only",
"handle",
"to",
"the",
"blockstack",
"-",
"specific",
"name",
"db",
".",
"Multiple",
"read",
"-",
"only",
"handles",
"may",
"exist",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L133-L149 |
230,580 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.make_opfields | 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 opfields | python | 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 opfields | [
"def",
"make_opfields",
"(",
"cls",
")",
":",
"# construct fields ",
"opfields",
"=",
"{",
"}",
"for",
"opname",
"in",
"SERIALIZE_FIELDS",
".",
"keys",
"(",
")",
":",
"opcode",
"=",
"NAME_OPCODES",
"[",
"opname",
"]",
"opfields",
"[",
"opcode",
"]",
"=",
"SERIALIZE_FIELDS",
"[",
"opname",
"]",
"return",
"opfields"
] | Calculate the virtulachain-required opfields dict. | [
"Calculate",
"the",
"virtulachain",
"-",
"required",
"opfields",
"dict",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L261-L271 |
230,581 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_state_paths | 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'),
os.path.join(working_dir, 'subdomains.db.queue')
] | python | 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'),
os.path.join(working_dir, 'subdomains.db.queue')
] | [
"def",
"get_state_paths",
"(",
"cls",
",",
"impl",
",",
"working_dir",
")",
":",
"return",
"super",
"(",
"BlockstackDB",
",",
"cls",
")",
".",
"get_state_paths",
"(",
"impl",
",",
"working_dir",
")",
"+",
"[",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"'atlas.db'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"'subdomains.db'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"'subdomains.db.queue'",
")",
"]"
] | Get the paths to the relevant db files to back up | [
"Get",
"the",
"paths",
"to",
"the",
"relevant",
"db",
"files",
"to",
"back",
"up"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L275-L283 |
230,582 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.close | 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 | python | 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 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"db",
"is",
"not",
"None",
":",
"self",
".",
"db",
".",
"commit",
"(",
")",
"self",
".",
"db",
".",
"close",
"(",
")",
"self",
".",
"db",
"=",
"None",
"return"
] | Close the db and release memory | [
"Close",
"the",
"db",
"and",
"release",
"memory"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L293-L302 |
230,583 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_import_keychain_path | 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 | python | 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 | [
"def",
"get_import_keychain_path",
"(",
"cls",
",",
"keychain_dir",
",",
"namespace_id",
")",
":",
"cached_keychain",
"=",
"os",
".",
"path",
".",
"join",
"(",
"keychain_dir",
",",
"\"{}.keychain\"",
".",
"format",
"(",
"namespace_id",
")",
")",
"return",
"cached_keychain"
] | Get the path to the import keychain | [
"Get",
"the",
"path",
"to",
"the",
"import",
"keychain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L341-L346 |
230,584 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.build_import_keychain | 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?
cached_keychain = cls.get_import_keychain_path(keychain_dir, namespace_id)
if os.path.exists( cached_keychain ):
child_addrs = []
try:
lines = []
with open(cached_keychain, "r") as f:
lines = f.readlines()
child_attrs = [l.strip() for l in lines]
log.debug("Loaded cached import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
return child_attrs
except Exception, e:
log.exception(e)
pass
pubkey_hex = str(pubkey_hex)
public_keychain = keychain.PublicKeychain.from_public_key( pubkey_hex )
child_addrs = []
for i in xrange(0, NAME_IMPORT_KEYRING_SIZE):
public_child = public_keychain.child(i)
public_child_address = public_child.address()
# if we're on testnet, then re-encode as a testnet address
if virtualchain.version_byte == 111:
old_child_address = public_child_address
public_child_address = virtualchain.hex_hash160_to_address( virtualchain.address_to_hex_hash160( public_child_address ) )
log.debug("Re-encode '%s' to '%s'" % (old_child_address, public_child_address))
child_addrs.append( public_child_address )
if i % 20 == 0 and i != 0:
log.debug("%s children..." % i)
# include this address
child_addrs.append( pubkey_addr )
log.debug("Done building import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
# cache
try:
with open(cached_keychain, "w+") as f:
for addr in child_addrs:
f.write("%s\n" % addr)
f.flush()
log.debug("Cached keychain to '%s'" % cached_keychain)
except Exception, e:
log.exception(e)
log.error("Unable to cache keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
return child_addrs | python | 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?
cached_keychain = cls.get_import_keychain_path(keychain_dir, namespace_id)
if os.path.exists( cached_keychain ):
child_addrs = []
try:
lines = []
with open(cached_keychain, "r") as f:
lines = f.readlines()
child_attrs = [l.strip() for l in lines]
log.debug("Loaded cached import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
return child_attrs
except Exception, e:
log.exception(e)
pass
pubkey_hex = str(pubkey_hex)
public_keychain = keychain.PublicKeychain.from_public_key( pubkey_hex )
child_addrs = []
for i in xrange(0, NAME_IMPORT_KEYRING_SIZE):
public_child = public_keychain.child(i)
public_child_address = public_child.address()
# if we're on testnet, then re-encode as a testnet address
if virtualchain.version_byte == 111:
old_child_address = public_child_address
public_child_address = virtualchain.hex_hash160_to_address( virtualchain.address_to_hex_hash160( public_child_address ) )
log.debug("Re-encode '%s' to '%s'" % (old_child_address, public_child_address))
child_addrs.append( public_child_address )
if i % 20 == 0 and i != 0:
log.debug("%s children..." % i)
# include this address
child_addrs.append( pubkey_addr )
log.debug("Done building import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
# cache
try:
with open(cached_keychain, "w+") as f:
for addr in child_addrs:
f.write("%s\n" % addr)
f.flush()
log.debug("Cached keychain to '%s'" % cached_keychain)
except Exception, e:
log.exception(e)
log.error("Unable to cache keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
return child_addrs | [
"def",
"build_import_keychain",
"(",
"cls",
",",
"keychain_dir",
",",
"namespace_id",
",",
"pubkey_hex",
")",
":",
"pubkey_addr",
"=",
"virtualchain",
".",
"BitcoinPublicKey",
"(",
"str",
"(",
"pubkey_hex",
")",
")",
".",
"address",
"(",
")",
"# do we have a cached one on disk?",
"cached_keychain",
"=",
"cls",
".",
"get_import_keychain_path",
"(",
"keychain_dir",
",",
"namespace_id",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cached_keychain",
")",
":",
"child_addrs",
"=",
"[",
"]",
"try",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"cached_keychain",
",",
"\"r\"",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"child_attrs",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"]",
"log",
".",
"debug",
"(",
"\"Loaded cached import keychain for '%s' (%s)\"",
"%",
"(",
"pubkey_hex",
",",
"pubkey_addr",
")",
")",
"return",
"child_attrs",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"pass",
"pubkey_hex",
"=",
"str",
"(",
"pubkey_hex",
")",
"public_keychain",
"=",
"keychain",
".",
"PublicKeychain",
".",
"from_public_key",
"(",
"pubkey_hex",
")",
"child_addrs",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"NAME_IMPORT_KEYRING_SIZE",
")",
":",
"public_child",
"=",
"public_keychain",
".",
"child",
"(",
"i",
")",
"public_child_address",
"=",
"public_child",
".",
"address",
"(",
")",
"# if we're on testnet, then re-encode as a testnet address ",
"if",
"virtualchain",
".",
"version_byte",
"==",
"111",
":",
"old_child_address",
"=",
"public_child_address",
"public_child_address",
"=",
"virtualchain",
".",
"hex_hash160_to_address",
"(",
"virtualchain",
".",
"address_to_hex_hash160",
"(",
"public_child_address",
")",
")",
"log",
".",
"debug",
"(",
"\"Re-encode '%s' to '%s'\"",
"%",
"(",
"old_child_address",
",",
"public_child_address",
")",
")",
"child_addrs",
".",
"append",
"(",
"public_child_address",
")",
"if",
"i",
"%",
"20",
"==",
"0",
"and",
"i",
"!=",
"0",
":",
"log",
".",
"debug",
"(",
"\"%s children...\"",
"%",
"i",
")",
"# include this address",
"child_addrs",
".",
"append",
"(",
"pubkey_addr",
")",
"log",
".",
"debug",
"(",
"\"Done building import keychain for '%s' (%s)\"",
"%",
"(",
"pubkey_hex",
",",
"pubkey_addr",
")",
")",
"# cache",
"try",
":",
"with",
"open",
"(",
"cached_keychain",
",",
"\"w+\"",
")",
"as",
"f",
":",
"for",
"addr",
"in",
"child_addrs",
":",
"f",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"addr",
")",
"f",
".",
"flush",
"(",
")",
"log",
".",
"debug",
"(",
"\"Cached keychain to '%s'\"",
"%",
"cached_keychain",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"Unable to cache keychain for '%s' (%s)\"",
"%",
"(",
"pubkey_hex",
",",
"pubkey_addr",
")",
")",
"return",
"child_addrs"
] | Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key | [
"Generate",
"all",
"possible",
"NAME_IMPORT",
"addresses",
"from",
"the",
"NAMESPACE_REVEAL",
"public",
"key"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L350-L413 |
230,585 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.load_import_keychain | 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.exists( cached_keychain ):
log.debug("Load import keychain '%s'" % cached_keychain)
child_addrs = []
try:
lines = []
with open(cached_keychain, "r") as f:
lines = f.readlines()
child_attrs = [l.strip() for l in lines]
log.debug("Loaded cached import keychain for '%s'" % namespace_id)
return child_attrs
except Exception, e:
log.exception(e)
log.error("FATAL: uncaught exception loading the import keychain")
os.abort()
else:
log.debug("No import keychain at '%s'" % cached_keychain)
return None | python | 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.exists( cached_keychain ):
log.debug("Load import keychain '%s'" % cached_keychain)
child_addrs = []
try:
lines = []
with open(cached_keychain, "r") as f:
lines = f.readlines()
child_attrs = [l.strip() for l in lines]
log.debug("Loaded cached import keychain for '%s'" % namespace_id)
return child_attrs
except Exception, e:
log.exception(e)
log.error("FATAL: uncaught exception loading the import keychain")
os.abort()
else:
log.debug("No import keychain at '%s'" % cached_keychain)
return None | [
"def",
"load_import_keychain",
"(",
"cls",
",",
"working_dir",
",",
"namespace_id",
")",
":",
"# do we have a cached one on disk?",
"cached_keychain",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"\"%s.keychain\"",
"%",
"namespace_id",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cached_keychain",
")",
":",
"log",
".",
"debug",
"(",
"\"Load import keychain '%s'\"",
"%",
"cached_keychain",
")",
"child_addrs",
"=",
"[",
"]",
"try",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"cached_keychain",
",",
"\"r\"",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"child_attrs",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"]",
"log",
".",
"debug",
"(",
"\"Loaded cached import keychain for '%s'\"",
"%",
"namespace_id",
")",
"return",
"child_attrs",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: uncaught exception loading the import keychain\"",
")",
"os",
".",
"abort",
"(",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"No import keychain at '%s'\"",
"%",
"cached_keychain",
")",
"return",
"None"
] | Get an import keychain from disk.
Return None if it doesn't exist. | [
"Get",
"an",
"import",
"keychain",
"from",
"disk",
".",
"Return",
"None",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L417-L447 |
230,586 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.commit_finished | 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 {}'.format(block_id)
self.clear_collisions( block_id )
self.clear_vesting(block_id+1) | python | 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 {}'.format(block_id)
self.clear_collisions( block_id )
self.clear_vesting(block_id+1) | [
"def",
"commit_finished",
"(",
"self",
",",
"block_id",
")",
":",
"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 {}'",
".",
"format",
"(",
"block_id",
")",
"self",
".",
"clear_collisions",
"(",
"block_id",
")",
"self",
".",
"clear_vesting",
"(",
"block_id",
"+",
"1",
")"
] | Called when the block is finished.
Commits all data. | [
"Called",
"when",
"the",
"block",
"is",
"finished",
".",
"Commits",
"all",
"data",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L458-L470 |
230,587 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.log_commit | def log_commit( self, block_id, vtxindex, op, opcode, op_data ):
"""
Log a committed operation
"""
debug_op = self.sanitize_op( op_data )
if 'history' in debug_op:
del debug_op['history']
log.debug("COMMIT %s (%s) at (%s, %s) data: %s", opcode, op, block_id, vtxindex,
", ".join( ["%s='%s'" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ) )
return | python | def log_commit( self, block_id, vtxindex, op, opcode, op_data ):
"""
Log a committed operation
"""
debug_op = self.sanitize_op( op_data )
if 'history' in debug_op:
del debug_op['history']
log.debug("COMMIT %s (%s) at (%s, %s) data: %s", opcode, op, block_id, vtxindex,
", ".join( ["%s='%s'" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ) )
return | [
"def",
"log_commit",
"(",
"self",
",",
"block_id",
",",
"vtxindex",
",",
"op",
",",
"opcode",
",",
"op_data",
")",
":",
"debug_op",
"=",
"self",
".",
"sanitize_op",
"(",
"op_data",
")",
"if",
"'history'",
"in",
"debug_op",
":",
"del",
"debug_op",
"[",
"'history'",
"]",
"log",
".",
"debug",
"(",
"\"COMMIT %s (%s) at (%s, %s) data: %s\"",
",",
"opcode",
",",
"op",
",",
"block_id",
",",
"vtxindex",
",",
"\", \"",
".",
"join",
"(",
"[",
"\"%s='%s'\"",
"%",
"(",
"k",
",",
"debug_op",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"sorted",
"(",
"debug_op",
".",
"keys",
"(",
")",
")",
"]",
")",
")",
"return"
] | Log a committed operation | [
"Log",
"a",
"committed",
"operation"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L489-L501 |
230,588 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.log_reject | def log_reject( self, block_id, vtxindex, op, op_data ):
"""
Log a rejected operation
"""
debug_op = self.sanitize_op( op_data )
if 'history' in debug_op:
del debug_op['history']
log.debug("REJECT %s at (%s, %s) data: %s", op_get_opcode_name( op ), block_id, vtxindex,
", ".join( ["%s='%s'" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ))
return | python | def log_reject( self, block_id, vtxindex, op, op_data ):
"""
Log a rejected operation
"""
debug_op = self.sanitize_op( op_data )
if 'history' in debug_op:
del debug_op['history']
log.debug("REJECT %s at (%s, %s) data: %s", op_get_opcode_name( op ), block_id, vtxindex,
", ".join( ["%s='%s'" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ))
return | [
"def",
"log_reject",
"(",
"self",
",",
"block_id",
",",
"vtxindex",
",",
"op",
",",
"op_data",
")",
":",
"debug_op",
"=",
"self",
".",
"sanitize_op",
"(",
"op_data",
")",
"if",
"'history'",
"in",
"debug_op",
":",
"del",
"debug_op",
"[",
"'history'",
"]",
"log",
".",
"debug",
"(",
"\"REJECT %s at (%s, %s) data: %s\"",
",",
"op_get_opcode_name",
"(",
"op",
")",
",",
"block_id",
",",
"vtxindex",
",",
"\", \"",
".",
"join",
"(",
"[",
"\"%s='%s'\"",
"%",
"(",
"k",
",",
"debug_op",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"sorted",
"(",
"debug_op",
".",
"keys",
"(",
")",
")",
"]",
")",
")",
"return"
] | Log a rejected operation | [
"Log",
"a",
"rejected",
"operation"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L504-L516 |
230,589 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.sanitize_op | def sanitize_op( self, op_data ):
"""
Remove unnecessary fields for an operation, i.e. prior to committing it.
This includes any invariant tags we've added with our invariant decorators
(such as @state_create or @state_transition).
TODO: less ad-hoc way to do this
"""
op_data = super(BlockstackDB, self).sanitize_op(op_data)
# remove invariant tags (i.e. added by our invariant state_* decorators)
to_remove = get_state_invariant_tags()
for tag in to_remove:
if tag in op_data.keys():
del op_data[tag]
# NOTE: this is called the opcode family, because
# different operation names can have the same operation code
# (such as NAME_RENEWAL and NAME_REGISTRATION). They must
# have the same mutation fields.
opcode_family = op_get_opcode_name( op_data['op'] )
# for each column in the appropriate state table,
# if the column is not identified in the operation's
# MUTATE_FIELDS list, then set it to None here.
mutate_fields = op_get_mutate_fields( opcode_family )
for mf in mutate_fields:
if not op_data.has_key( mf ):
log.debug("Adding NULL mutate field '%s.%s'" % (opcode_family, mf ))
op_data[mf] = None
# TODO: less ad-hoc
for extra_field in ['opcode']:
if extra_field in op_data:
del op_data[extra_field]
return op_data | python | def sanitize_op( self, op_data ):
"""
Remove unnecessary fields for an operation, i.e. prior to committing it.
This includes any invariant tags we've added with our invariant decorators
(such as @state_create or @state_transition).
TODO: less ad-hoc way to do this
"""
op_data = super(BlockstackDB, self).sanitize_op(op_data)
# remove invariant tags (i.e. added by our invariant state_* decorators)
to_remove = get_state_invariant_tags()
for tag in to_remove:
if tag in op_data.keys():
del op_data[tag]
# NOTE: this is called the opcode family, because
# different operation names can have the same operation code
# (such as NAME_RENEWAL and NAME_REGISTRATION). They must
# have the same mutation fields.
opcode_family = op_get_opcode_name( op_data['op'] )
# for each column in the appropriate state table,
# if the column is not identified in the operation's
# MUTATE_FIELDS list, then set it to None here.
mutate_fields = op_get_mutate_fields( opcode_family )
for mf in mutate_fields:
if not op_data.has_key( mf ):
log.debug("Adding NULL mutate field '%s.%s'" % (opcode_family, mf ))
op_data[mf] = None
# TODO: less ad-hoc
for extra_field in ['opcode']:
if extra_field in op_data:
del op_data[extra_field]
return op_data | [
"def",
"sanitize_op",
"(",
"self",
",",
"op_data",
")",
":",
"op_data",
"=",
"super",
"(",
"BlockstackDB",
",",
"self",
")",
".",
"sanitize_op",
"(",
"op_data",
")",
"# remove invariant tags (i.e. added by our invariant state_* decorators)",
"to_remove",
"=",
"get_state_invariant_tags",
"(",
")",
"for",
"tag",
"in",
"to_remove",
":",
"if",
"tag",
"in",
"op_data",
".",
"keys",
"(",
")",
":",
"del",
"op_data",
"[",
"tag",
"]",
"# NOTE: this is called the opcode family, because",
"# different operation names can have the same operation code",
"# (such as NAME_RENEWAL and NAME_REGISTRATION). They must",
"# have the same mutation fields.",
"opcode_family",
"=",
"op_get_opcode_name",
"(",
"op_data",
"[",
"'op'",
"]",
")",
"# for each column in the appropriate state table,",
"# if the column is not identified in the operation's",
"# MUTATE_FIELDS list, then set it to None here.",
"mutate_fields",
"=",
"op_get_mutate_fields",
"(",
"opcode_family",
")",
"for",
"mf",
"in",
"mutate_fields",
":",
"if",
"not",
"op_data",
".",
"has_key",
"(",
"mf",
")",
":",
"log",
".",
"debug",
"(",
"\"Adding NULL mutate field '%s.%s'\"",
"%",
"(",
"opcode_family",
",",
"mf",
")",
")",
"op_data",
"[",
"mf",
"]",
"=",
"None",
"# TODO: less ad-hoc",
"for",
"extra_field",
"in",
"[",
"'opcode'",
"]",
":",
"if",
"extra_field",
"in",
"op_data",
":",
"del",
"op_data",
"[",
"extra_field",
"]",
"return",
"op_data"
] | Remove unnecessary fields for an operation, i.e. prior to committing it.
This includes any invariant tags we've added with our invariant decorators
(such as @state_create or @state_transition).
TODO: less ad-hoc way to do this | [
"Remove",
"unnecessary",
"fields",
"for",
"an",
"operation",
"i",
".",
"e",
".",
"prior",
"to",
"committing",
"it",
".",
"This",
"includes",
"any",
"invariant",
"tags",
"we",
"ve",
"added",
"with",
"our",
"invariant",
"decorators",
"(",
"such",
"as"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L519-L556 |
230,590 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.put_collisions | def put_collisions( self, block_id, collisions ):
"""
Put collision state for a particular block.
Any operations checked at this block_id that collide
with the given collision state will be rejected.
"""
self.collisions[ block_id ] = copy.deepcopy( collisions ) | python | def put_collisions( self, block_id, collisions ):
"""
Put collision state for a particular block.
Any operations checked at this block_id that collide
with the given collision state will be rejected.
"""
self.collisions[ block_id ] = copy.deepcopy( collisions ) | [
"def",
"put_collisions",
"(",
"self",
",",
"block_id",
",",
"collisions",
")",
":",
"self",
".",
"collisions",
"[",
"block_id",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"collisions",
")"
] | Put collision state for a particular block.
Any operations checked at this block_id that collide
with the given collision state will be rejected. | [
"Put",
"collision",
"state",
"for",
"a",
"particular",
"block",
".",
"Any",
"operations",
"checked",
"at",
"this",
"block_id",
"that",
"collide",
"with",
"the",
"given",
"collision",
"state",
"will",
"be",
"rejected",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L625-L631 |
230,591 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_namespace | def get_namespace( self, namespace_id, include_history=True ):
"""
Given a namespace ID, get the ready namespace op for it.
Return the dict with the parameters on success.
Return None if the namespace has not yet been revealed.
"""
cur = self.db.cursor()
return namedb_get_namespace_ready( cur, namespace_id, include_history=include_history ) | python | def get_namespace( self, namespace_id, include_history=True ):
"""
Given a namespace ID, get the ready namespace op for it.
Return the dict with the parameters on success.
Return None if the namespace has not yet been revealed.
"""
cur = self.db.cursor()
return namedb_get_namespace_ready( cur, namespace_id, include_history=include_history ) | [
"def",
"get_namespace",
"(",
"self",
",",
"namespace_id",
",",
"include_history",
"=",
"True",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_namespace_ready",
"(",
"cur",
",",
"namespace_id",
",",
"include_history",
"=",
"include_history",
")"
] | Given a namespace ID, get the ready namespace op for it.
Return the dict with the parameters on success.
Return None if the namespace has not yet been revealed. | [
"Given",
"a",
"namespace",
"ID",
"get",
"the",
"ready",
"namespace",
"op",
"for",
"it",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L705-L714 |
230,592 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_DID_name | def get_DID_name(self, did):
"""
Given a DID, get the name
Return None if not found, or if the name was revoked
Raise if the DID is invalid
"""
did = str(did)
did_info = None
try:
did_info = parse_DID(did)
assert did_info['name_type'] == 'name'
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
raise ValueError("Invalid DID: {}".format(did))
cur = self.db.cursor()
historic_name_info = namedb_get_historic_names_by_address(cur, did_info['address'], offset=did_info['index'], count=1)
if historic_name_info is None:
# no such name
return None
name = historic_name_info[0]['name']
block_height = historic_name_info[0]['block_id']
vtxindex = historic_name_info[0]['vtxindex']
log.debug("DID {} refers to {}-{}-{}".format(did, name, block_height, vtxindex))
name_rec = self.get_name(name, include_history=True, include_expired=True)
if name_rec is None:
# dead
return None
name_rec_latest = None
found = False
for height in sorted(name_rec['history'].keys()):
if found:
break
if height < block_height:
continue
for state in name_rec['history'][height]:
if height == block_height and state['vtxindex'] < vtxindex:
# too soon
continue
if state['op'] == NAME_PREORDER:
# looped to the next iteration of this name
found = True
break
if state['revoked']:
# revoked
log.debug("DID {} refers to {}-{}-{}, which is revoked at {}-{}".format(did, name, block_height, vtxindex, height, state['vtxindex']))
return None
name_rec_latest = state
return name_rec_latest | python | def get_DID_name(self, did):
"""
Given a DID, get the name
Return None if not found, or if the name was revoked
Raise if the DID is invalid
"""
did = str(did)
did_info = None
try:
did_info = parse_DID(did)
assert did_info['name_type'] == 'name'
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
raise ValueError("Invalid DID: {}".format(did))
cur = self.db.cursor()
historic_name_info = namedb_get_historic_names_by_address(cur, did_info['address'], offset=did_info['index'], count=1)
if historic_name_info is None:
# no such name
return None
name = historic_name_info[0]['name']
block_height = historic_name_info[0]['block_id']
vtxindex = historic_name_info[0]['vtxindex']
log.debug("DID {} refers to {}-{}-{}".format(did, name, block_height, vtxindex))
name_rec = self.get_name(name, include_history=True, include_expired=True)
if name_rec is None:
# dead
return None
name_rec_latest = None
found = False
for height in sorted(name_rec['history'].keys()):
if found:
break
if height < block_height:
continue
for state in name_rec['history'][height]:
if height == block_height and state['vtxindex'] < vtxindex:
# too soon
continue
if state['op'] == NAME_PREORDER:
# looped to the next iteration of this name
found = True
break
if state['revoked']:
# revoked
log.debug("DID {} refers to {}-{}-{}, which is revoked at {}-{}".format(did, name, block_height, vtxindex, height, state['vtxindex']))
return None
name_rec_latest = state
return name_rec_latest | [
"def",
"get_DID_name",
"(",
"self",
",",
"did",
")",
":",
"did",
"=",
"str",
"(",
"did",
")",
"did_info",
"=",
"None",
"try",
":",
"did_info",
"=",
"parse_DID",
"(",
"did",
")",
"assert",
"did_info",
"[",
"'name_type'",
"]",
"==",
"'name'",
"except",
"Exception",
"as",
"e",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"e",
")",
"raise",
"ValueError",
"(",
"\"Invalid DID: {}\"",
".",
"format",
"(",
"did",
")",
")",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"historic_name_info",
"=",
"namedb_get_historic_names_by_address",
"(",
"cur",
",",
"did_info",
"[",
"'address'",
"]",
",",
"offset",
"=",
"did_info",
"[",
"'index'",
"]",
",",
"count",
"=",
"1",
")",
"if",
"historic_name_info",
"is",
"None",
":",
"# no such name",
"return",
"None",
"name",
"=",
"historic_name_info",
"[",
"0",
"]",
"[",
"'name'",
"]",
"block_height",
"=",
"historic_name_info",
"[",
"0",
"]",
"[",
"'block_id'",
"]",
"vtxindex",
"=",
"historic_name_info",
"[",
"0",
"]",
"[",
"'vtxindex'",
"]",
"log",
".",
"debug",
"(",
"\"DID {} refers to {}-{}-{}\"",
".",
"format",
"(",
"did",
",",
"name",
",",
"block_height",
",",
"vtxindex",
")",
")",
"name_rec",
"=",
"self",
".",
"get_name",
"(",
"name",
",",
"include_history",
"=",
"True",
",",
"include_expired",
"=",
"True",
")",
"if",
"name_rec",
"is",
"None",
":",
"# dead",
"return",
"None",
"name_rec_latest",
"=",
"None",
"found",
"=",
"False",
"for",
"height",
"in",
"sorted",
"(",
"name_rec",
"[",
"'history'",
"]",
".",
"keys",
"(",
")",
")",
":",
"if",
"found",
":",
"break",
"if",
"height",
"<",
"block_height",
":",
"continue",
"for",
"state",
"in",
"name_rec",
"[",
"'history'",
"]",
"[",
"height",
"]",
":",
"if",
"height",
"==",
"block_height",
"and",
"state",
"[",
"'vtxindex'",
"]",
"<",
"vtxindex",
":",
"# too soon",
"continue",
"if",
"state",
"[",
"'op'",
"]",
"==",
"NAME_PREORDER",
":",
"# looped to the next iteration of this name",
"found",
"=",
"True",
"break",
"if",
"state",
"[",
"'revoked'",
"]",
":",
"# revoked",
"log",
".",
"debug",
"(",
"\"DID {} refers to {}-{}-{}, which is revoked at {}-{}\"",
".",
"format",
"(",
"did",
",",
"name",
",",
"block_height",
",",
"vtxindex",
",",
"height",
",",
"state",
"[",
"'vtxindex'",
"]",
")",
")",
"return",
"None",
"name_rec_latest",
"=",
"state",
"return",
"name_rec_latest"
] | Given a DID, get the name
Return None if not found, or if the name was revoked
Raise if the DID is invalid | [
"Given",
"a",
"DID",
"get",
"the",
"name",
"Return",
"None",
"if",
"not",
"found",
"or",
"if",
"the",
"name",
"was",
"revoked",
"Raise",
"if",
"the",
"DID",
"is",
"invalid"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L788-L849 |
230,593 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_account_tokens | def get_account_tokens(self, address):
"""
Get the list of tokens that this address owns
"""
cur = self.db.cursor()
return namedb_get_account_tokens(cur, address) | python | def get_account_tokens(self, address):
"""
Get the list of tokens that this address owns
"""
cur = self.db.cursor()
return namedb_get_account_tokens(cur, address) | [
"def",
"get_account_tokens",
"(",
"self",
",",
"address",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_account_tokens",
"(",
"cur",
",",
"address",
")"
] | Get the list of tokens that this address owns | [
"Get",
"the",
"list",
"of",
"tokens",
"that",
"this",
"address",
"owns"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L852-L857 |
230,594 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_account | def get_account(self, address, token_type):
"""
Get the state of an account for a given token type
"""
cur = self.db.cursor()
return namedb_get_account(cur, address, token_type) | python | def get_account(self, address, token_type):
"""
Get the state of an account for a given token type
"""
cur = self.db.cursor()
return namedb_get_account(cur, address, token_type) | [
"def",
"get_account",
"(",
"self",
",",
"address",
",",
"token_type",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_account",
"(",
"cur",
",",
"address",
",",
"token_type",
")"
] | Get the state of an account for a given token type | [
"Get",
"the",
"state",
"of",
"an",
"account",
"for",
"a",
"given",
"token",
"type"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L860-L865 |
230,595 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_account_balance | def get_account_balance(self, account):
"""
What's the balance of an account?
Aborts if its negative
"""
balance = namedb_get_account_balance(account)
assert isinstance(balance, (int,long)), 'BUG: account balance of {} is {} (type {})'.format(account['address'], balance, type(balance))
return balance | python | def get_account_balance(self, account):
"""
What's the balance of an account?
Aborts if its negative
"""
balance = namedb_get_account_balance(account)
assert isinstance(balance, (int,long)), 'BUG: account balance of {} is {} (type {})'.format(account['address'], balance, type(balance))
return balance | [
"def",
"get_account_balance",
"(",
"self",
",",
"account",
")",
":",
"balance",
"=",
"namedb_get_account_balance",
"(",
"account",
")",
"assert",
"isinstance",
"(",
"balance",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'BUG: account balance of {} is {} (type {})'",
".",
"format",
"(",
"account",
"[",
"'address'",
"]",
",",
"balance",
",",
"type",
"(",
"balance",
")",
")",
"return",
"balance"
] | What's the balance of an account?
Aborts if its negative | [
"What",
"s",
"the",
"balance",
"of",
"an",
"account?",
"Aborts",
"if",
"its",
"negative"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L868-L875 |
230,596 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_account_history | def get_account_history(self, address, offset=None, count=None):
"""
Get the history of account transactions over a block range
Returns a dict keyed by blocks, which map to lists of account state transitions
"""
cur = self.db.cursor()
return namedb_get_account_history(cur, address, offset=offset, count=count) | python | def get_account_history(self, address, offset=None, count=None):
"""
Get the history of account transactions over a block range
Returns a dict keyed by blocks, which map to lists of account state transitions
"""
cur = self.db.cursor()
return namedb_get_account_history(cur, address, offset=offset, count=count) | [
"def",
"get_account_history",
"(",
"self",
",",
"address",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_account_history",
"(",
"cur",
",",
"address",
",",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
")"
] | Get the history of account transactions over a block range
Returns a dict keyed by blocks, which map to lists of account state transitions | [
"Get",
"the",
"history",
"of",
"account",
"transactions",
"over",
"a",
"block",
"range",
"Returns",
"a",
"dict",
"keyed",
"by",
"blocks",
"which",
"map",
"to",
"lists",
"of",
"account",
"state",
"transitions"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L893-L899 |
230,597 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_name_at | def get_name_at( self, name, block_number, include_expired=False ):
"""
Generate and return the sequence of of states a name record was in
at a particular block number.
"""
cur = self.db.cursor()
return namedb_get_name_at(cur, name, block_number, include_expired=include_expired) | python | def get_name_at( self, name, block_number, include_expired=False ):
"""
Generate and return the sequence of of states a name record was in
at a particular block number.
"""
cur = self.db.cursor()
return namedb_get_name_at(cur, name, block_number, include_expired=include_expired) | [
"def",
"get_name_at",
"(",
"self",
",",
"name",
",",
"block_number",
",",
"include_expired",
"=",
"False",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_name_at",
"(",
"cur",
",",
"name",
",",
"block_number",
",",
"include_expired",
"=",
"include_expired",
")"
] | Generate and return the sequence of of states a name record was in
at a particular block number. | [
"Generate",
"and",
"return",
"the",
"sequence",
"of",
"of",
"states",
"a",
"name",
"record",
"was",
"in",
"at",
"a",
"particular",
"block",
"number",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L912-L918 |
230,598 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_namespace_at | def get_namespace_at( self, namespace_id, block_number ):
"""
Generate and return the sequence of states a namespace record was in
at a particular block number.
Includes expired namespaces by default.
"""
cur = self.db.cursor()
return namedb_get_namespace_at(cur, namespace_id, block_number, include_expired=True) | python | def get_namespace_at( self, namespace_id, block_number ):
"""
Generate and return the sequence of states a namespace record was in
at a particular block number.
Includes expired namespaces by default.
"""
cur = self.db.cursor()
return namedb_get_namespace_at(cur, namespace_id, block_number, include_expired=True) | [
"def",
"get_namespace_at",
"(",
"self",
",",
"namespace_id",
",",
"block_number",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_namespace_at",
"(",
"cur",
",",
"namespace_id",
",",
"block_number",
",",
"include_expired",
"=",
"True",
")"
] | Generate and return the sequence of states a namespace record was in
at a particular block number.
Includes expired namespaces by default. | [
"Generate",
"and",
"return",
"the",
"sequence",
"of",
"states",
"a",
"namespace",
"record",
"was",
"in",
"at",
"a",
"particular",
"block",
"number",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L921-L929 |
230,599 | blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | BlockstackDB.get_account_at | def get_account_at(self, address, block_number):
"""
Get the sequence of states an account was in at a given block.
Returns a list of states
"""
cur = self.db.cursor()
return namedb_get_account_at(cur, address, block_number) | python | def get_account_at(self, address, block_number):
"""
Get the sequence of states an account was in at a given block.
Returns a list of states
"""
cur = self.db.cursor()
return namedb_get_account_at(cur, address, block_number) | [
"def",
"get_account_at",
"(",
"self",
",",
"address",
",",
"block_number",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_account_at",
"(",
"cur",
",",
"address",
",",
"block_number",
")"
] | Get the sequence of states an account was in at a given block.
Returns a list of states | [
"Get",
"the",
"sequence",
"of",
"states",
"an",
"account",
"was",
"in",
"at",
"a",
"given",
"block",
".",
"Returns",
"a",
"list",
"of",
"states"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L932-L938 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.