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
partition
stringclasses
1 value
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", "...
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
train
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...
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
train
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", ".", ...
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
train
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", "==",...
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
train
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...
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
train
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", ")", ":", "request", ",", "client_addr", "=", "super", "(", "BoundedThreadingMixIn", ",", "self", ")", ".", "get_request", "(", ")", "overload", "=", "False", "with", "self", ".", "_thread_guard", ":", "if", "self", ".", ...
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
train
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", ...
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
train
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", ")", ":", "r...
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
train
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", ")", ":", ...
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
train
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", "(", "blo...
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
train
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", "if", "op_string", "==", "'{}:'", ".", "format", "(", "NAME_REGISTRATION", ")", ":", "return", "'NAME_RENEWAL'", "op", "=", "op_string", "[", "0", "]", "if", "op", "not", "in"...
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
train
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", ...
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
train
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
train
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", "(", ...
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
train
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'", ")...
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
train
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", ".", "...
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
train
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", "...
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
train
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...
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
train
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", ":", "if", "announcement_hash", "in", "ANNOUNCEMENTS", ":", "return", "announce_filename", "=", "get_an...
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
train
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_confi...
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
train
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", ")", ":", "lines", "=", "message", ".", "split", "(", "'\\n'", ")", "max_line_len", "=", "max", "(", "[", "len", "(", "l", ")", "for", "l", "in", "lines", "]", ")", ...
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
train
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", ")", ":", "missing_params", "=", "list", "(", "set", "(", "all_params", ")", "-", "set", "(", ...
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
train
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", "(", ")", ":", "if", "opt_name", ".", "startswith", "(", "prefix", ")", ":", "opt_name", "=", "opt_name",...
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
train
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
train
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", ")", "default_bitcoin_opts", "=", "{", "k", ":"...
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
train
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
train
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", "...
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
train
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", "opts", "=", "configure", "(", "working_dir", ")", "blockstack_opts", "=", "opts", ".", "get", "(", "'blockstack'", ",", "None", ...
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
train
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'", "]", "if", "not", "state_engine", ".", "is_namespace_reveale...
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", ...
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/namespaceready.py#L52-L85
train
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", "=", "\"\"",...
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
train
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
train
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", "...
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
train
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...
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
train
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", "=...
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
train
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", ")", ":", "opfields", "=", "{", "}", "for", "opname", "in", "SERIALIZE_FIELDS", ".", "keys", "(", ")", ":", "opcode", "=", "NAME_OPCODES", "[", "opname", "]", "opfields", "[", "opcode", "]", "=", "SERIALIZE_FIELDS", "[...
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
train
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", "(", "work...
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
train
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
train
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", "cac...
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
train
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", "(", ")", "cached_keychain", ...
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
train
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", ")", ":", "cached_keychain", "=", "os", ".", "path", ".", "join", "(", "working_dir", ",", "\"%s.keychain\"", "%", "namespace_id", ")", "if", "os", ".", "path", ".", "exists"...
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
train
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", "(", ")", "assert", "block_id", "+", "1", "in", "self", ".", "vesting", ",", "'BUG: failed to vest at {}'", ".", "format", "(", "block_id", ")", "self", "...
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
train
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", "[", ...
Log a committed operation
[ "Log", "a", "committed", "operation" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L489-L501
train
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 a rejected operation
[ "Log", "a", "rejected", "operation" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L504-L516
train
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", ")", "to_remove", "=", "get_state_invariant_tags", "(", ")", "for", "tag", "in", "to_remove", "...
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
train
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
train
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", ...
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
train
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", ...
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
train
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
train
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
train
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 {}...
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
train
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", ",", ...
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
train
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", ","...
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
train
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...
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
train
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
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_name_history
def get_name_history( self, name, offset=None, count=None, reverse=False): """ Get the historic states for a name, grouped by block height. """ cur = self.db.cursor() name_hist = namedb_get_history( cur, name, offset=offset, count=count, reverse=reverse ) return name_hist
python
def get_name_history( self, name, offset=None, count=None, reverse=False): """ Get the historic states for a name, grouped by block height. """ cur = self.db.cursor() name_hist = namedb_get_history( cur, name, offset=offset, count=count, reverse=reverse ) return name_hist
[ "def", "get_name_history", "(", "self", ",", "name", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "reverse", "=", "False", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "name_hist", "=", "namedb_get_history", "(", "...
Get the historic states for a name, grouped by block height.
[ "Get", "the", "historic", "states", "for", "a", "name", "grouped", "by", "block", "height", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L941-L947
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_name_zonefile_hash
def is_name_zonefile_hash(self, name, zonefile_hash): """ Was a zone file sent by a name? """ cur = self.db.cursor() return namedb_is_name_zonefile_hash(cur, name, zonefile_hash)
python
def is_name_zonefile_hash(self, name, zonefile_hash): """ Was a zone file sent by a name? """ cur = self.db.cursor() return namedb_is_name_zonefile_hash(cur, name, zonefile_hash)
[ "def", "is_name_zonefile_hash", "(", "self", ",", "name", ",", "zonefile_hash", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_is_name_zonefile_hash", "(", "cur", ",", "name", ",", "zonefile_hash", ")" ]
Was a zone file sent by a name?
[ "Was", "a", "zone", "file", "sent", "by", "a", "name?" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L950-L955
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_blockstack_ops_at
def get_all_blockstack_ops_at( self, block_number, offset=None, count=None, include_history=None, restore_history=None ): """ Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count are given. """ if include_history is not None: log.warn("DEPRECATED use of include_history") if restore_history is not None: log.warn("DEPRECATED use of restore_history") log.debug("Get all accepted operations at %s in %s" % (block_number, self.db_filename)) recs = namedb_get_all_blockstack_ops_at( self.db, block_number, offset=offset, count=count ) # include opcode for rec in recs: assert 'op' in rec rec['opcode'] = op_get_opcode_name(rec['op']) return recs
python
def get_all_blockstack_ops_at( self, block_number, offset=None, count=None, include_history=None, restore_history=None ): """ Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count are given. """ if include_history is not None: log.warn("DEPRECATED use of include_history") if restore_history is not None: log.warn("DEPRECATED use of restore_history") log.debug("Get all accepted operations at %s in %s" % (block_number, self.db_filename)) recs = namedb_get_all_blockstack_ops_at( self.db, block_number, offset=offset, count=count ) # include opcode for rec in recs: assert 'op' in rec rec['opcode'] = op_get_opcode_name(rec['op']) return recs
[ "def", "get_all_blockstack_ops_at", "(", "self", ",", "block_number", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "include_history", "=", "None", ",", "restore_history", "=", "None", ")", ":", "if", "include_history", "is", "not", "None", ":"...
Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count are given.
[ "Get", "all", "name", "namespace", "and", "account", "records", "affected", "at", "a", "particular", "block", "in", "the", "state", "they", "were", "at", "the", "given", "block", "number", ".", "Paginate", "if", "offset", "count", "are", "given", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L958-L979
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_name_from_name_hash128
def get_name_from_name_hash128( self, name ): """ Get the name from a name hash """ cur = self.db.cursor() name = namedb_get_name_from_name_hash128( cur, name, self.lastblock ) return name
python
def get_name_from_name_hash128( self, name ): """ Get the name from a name hash """ cur = self.db.cursor() name = namedb_get_name_from_name_hash128( cur, name, self.lastblock ) return name
[ "def", "get_name_from_name_hash128", "(", "self", ",", "name", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "name", "=", "namedb_get_name_from_name_hash128", "(", "cur", ",", "name", ",", "self", ".", "lastblock", ")", "return", "name"...
Get the name from a name hash
[ "Get", "the", "name", "from", "a", "name", "hash" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L990-L996
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_num_historic_names_by_address
def get_num_historic_names_by_address( self, address ): """ Get the number of names historically owned by an address """ cur = self.db.cursor() count = namedb_get_num_historic_names_by_address( cur, address ) return count
python
def get_num_historic_names_by_address( self, address ): """ Get the number of names historically owned by an address """ cur = self.db.cursor() count = namedb_get_num_historic_names_by_address( cur, address ) return count
[ "def", "get_num_historic_names_by_address", "(", "self", ",", "address", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "count", "=", "namedb_get_num_historic_names_by_address", "(", "cur", ",", "address", ")", "return", "count" ]
Get the number of names historically owned by an address
[ "Get", "the", "number", "of", "names", "historically", "owned", "by", "an", "address" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1019-L1025
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_names_owned_by_sender
def get_names_owned_by_sender( self, sender_pubkey, lastblock=None ): """ Get the set of names owned by a particular script-pubkey. """ cur = self.db.cursor() if lastblock is None: lastblock = self.lastblock names = namedb_get_names_by_sender( cur, sender_pubkey, lastblock ) return names
python
def get_names_owned_by_sender( self, sender_pubkey, lastblock=None ): """ Get the set of names owned by a particular script-pubkey. """ cur = self.db.cursor() if lastblock is None: lastblock = self.lastblock names = namedb_get_names_by_sender( cur, sender_pubkey, lastblock ) return names
[ "def", "get_names_owned_by_sender", "(", "self", ",", "sender_pubkey", ",", "lastblock", "=", "None", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "if", "lastblock", "is", "None", ":", "lastblock", "=", "self", ".", "lastblock", "nam...
Get the set of names owned by a particular script-pubkey.
[ "Get", "the", "set", "of", "names", "owned", "by", "a", "particular", "script", "-", "pubkey", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1028-L1037
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_num_names
def get_num_names( self, include_expired=False ): """ Get the number of names that exist. """ cur = self.db.cursor() return namedb_get_num_names( cur, self.lastblock, include_expired=include_expired )
python
def get_num_names( self, include_expired=False ): """ Get the number of names that exist. """ cur = self.db.cursor() return namedb_get_num_names( cur, self.lastblock, include_expired=include_expired )
[ "def", "get_num_names", "(", "self", ",", "include_expired", "=", "False", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_num_names", "(", "cur", ",", "self", ".", "lastblock", ",", "include_expired", "=", "include_...
Get the number of names that exist.
[ "Get", "the", "number", "of", "names", "that", "exist", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1040-L1045
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_names
def get_all_names( self, offset=None, count=None, include_expired=False ): """ Get the set of all registered names, with optional pagination Returns the list of names. """ if offset is not None and offset < 0: offset = None if count is not None and count < 0: count = None cur = self.db.cursor() names = namedb_get_all_names( cur, self.lastblock, offset=offset, count=count, include_expired=include_expired ) return names
python
def get_all_names( self, offset=None, count=None, include_expired=False ): """ Get the set of all registered names, with optional pagination Returns the list of names. """ if offset is not None and offset < 0: offset = None if count is not None and count < 0: count = None cur = self.db.cursor() names = namedb_get_all_names( cur, self.lastblock, offset=offset, count=count, include_expired=include_expired ) return names
[ "def", "get_all_names", "(", "self", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "include_expired", "=", "False", ")", ":", "if", "offset", "is", "not", "None", "and", "offset", "<", "0", ":", "offset", "=", "None", "if", "count", "is...
Get the set of all registered names, with optional pagination Returns the list of names.
[ "Get", "the", "set", "of", "all", "registered", "names", "with", "optional", "pagination", "Returns", "the", "list", "of", "names", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1048-L1061
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_num_names_in_namespace
def get_num_names_in_namespace( self, namespace_id ): """ Get the number of names in a namespace """ cur = self.db.cursor() return namedb_get_num_names_in_namespace( cur, namespace_id, self.lastblock )
python
def get_num_names_in_namespace( self, namespace_id ): """ Get the number of names in a namespace """ cur = self.db.cursor() return namedb_get_num_names_in_namespace( cur, namespace_id, self.lastblock )
[ "def", "get_num_names_in_namespace", "(", "self", ",", "namespace_id", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_num_names_in_namespace", "(", "cur", ",", "namespace_id", ",", "self", ".", "lastblock", ")" ]
Get the number of names in a namespace
[ "Get", "the", "number", "of", "names", "in", "a", "namespace" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1064-L1069
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_names_in_namespace
def get_names_in_namespace( self, namespace_id, offset=None, count=None ): """ Get the set of all registered names in a particular namespace. Returns the list of names. """ if offset is not None and offset < 0: offset = None if count is not None and count < 0: count = None cur = self.db.cursor() names = namedb_get_names_in_namespace( cur, namespace_id, self.lastblock, offset=offset, count=count ) return names
python
def get_names_in_namespace( self, namespace_id, offset=None, count=None ): """ Get the set of all registered names in a particular namespace. Returns the list of names. """ if offset is not None and offset < 0: offset = None if count is not None and count < 0: count = None cur = self.db.cursor() names = namedb_get_names_in_namespace( cur, namespace_id, self.lastblock, offset=offset, count=count ) return names
[ "def", "get_names_in_namespace", "(", "self", ",", "namespace_id", ",", "offset", "=", "None", ",", "count", "=", "None", ")", ":", "if", "offset", "is", "not", "None", "and", "offset", "<", "0", ":", "offset", "=", "None", "if", "count", "is", "not", ...
Get the set of all registered names in a particular namespace. Returns the list of names.
[ "Get", "the", "set", "of", "all", "registered", "names", "in", "a", "particular", "namespace", ".", "Returns", "the", "list", "of", "names", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1072-L1085
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_namespace_ids
def get_all_namespace_ids( self ): """ Get the set of all existing, READY namespace IDs. """ cur = self.db.cursor() namespace_ids = namedb_get_all_namespace_ids( cur ) return namespace_ids
python
def get_all_namespace_ids( self ): """ Get the set of all existing, READY namespace IDs. """ cur = self.db.cursor() namespace_ids = namedb_get_all_namespace_ids( cur ) return namespace_ids
[ "def", "get_all_namespace_ids", "(", "self", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_ids", "=", "namedb_get_all_namespace_ids", "(", "cur", ")", "return", "namespace_ids" ]
Get the set of all existing, READY namespace IDs.
[ "Get", "the", "set", "of", "all", "existing", "READY", "namespace", "IDs", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1088-L1094
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_revealed_namespace_ids
def get_all_revealed_namespace_ids( self ): """ Get all revealed namespace IDs that have not expired. """ cur = self.db.cursor() namespace_ids = namedb_get_all_revealed_namespace_ids( cur, self.lastblock ) return namespace_ids
python
def get_all_revealed_namespace_ids( self ): """ Get all revealed namespace IDs that have not expired. """ cur = self.db.cursor() namespace_ids = namedb_get_all_revealed_namespace_ids( cur, self.lastblock ) return namespace_ids
[ "def", "get_all_revealed_namespace_ids", "(", "self", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_ids", "=", "namedb_get_all_revealed_namespace_ids", "(", "cur", ",", "self", ".", "lastblock", ")", "return", "namespace_ids" ]
Get all revealed namespace IDs that have not expired.
[ "Get", "all", "revealed", "namespace", "IDs", "that", "have", "not", "expired", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1097-L1103
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_preordered_namespace_hashes
def get_all_preordered_namespace_hashes( self ): """ Get all oustanding namespace preorder hashes that have not expired. Used for testing """ cur = self.db.cursor() namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock ) return namespace_hashes
python
def get_all_preordered_namespace_hashes( self ): """ Get all oustanding namespace preorder hashes that have not expired. Used for testing """ cur = self.db.cursor() namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock ) return namespace_hashes
[ "def", "get_all_preordered_namespace_hashes", "(", "self", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_hashes", "=", "namedb_get_all_preordered_namespace_hashes", "(", "cur", ",", "self", ".", "lastblock", ")", "return", "namespace...
Get all oustanding namespace preorder hashes that have not expired. Used for testing
[ "Get", "all", "oustanding", "namespace", "preorder", "hashes", "that", "have", "not", "expired", ".", "Used", "for", "testing" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1106-L1113
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_all_importing_namespace_hashes
def get_all_importing_namespace_hashes( self ): """ Get the set of all preordered and revealed namespace hashes that have not expired. """ cur = self.db.cursor() namespace_hashes = namedb_get_all_importing_namespace_hashes( cur, self.lastblock ) return namespace_hashes
python
def get_all_importing_namespace_hashes( self ): """ Get the set of all preordered and revealed namespace hashes that have not expired. """ cur = self.db.cursor() namespace_hashes = namedb_get_all_importing_namespace_hashes( cur, self.lastblock ) return namespace_hashes
[ "def", "get_all_importing_namespace_hashes", "(", "self", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_hashes", "=", "namedb_get_all_importing_namespace_hashes", "(", "cur", ",", "self", ".", "lastblock", ")", "return", "namespace_h...
Get the set of all preordered and revealed namespace hashes that have not expired.
[ "Get", "the", "set", "of", "all", "preordered", "and", "revealed", "namespace", "hashes", "that", "have", "not", "expired", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1116-L1122
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_name_preorder
def get_name_preorder( self, name, sender_script_pubkey, register_addr, include_failed=False ): """ Get the current preorder for a name, given the name, the sender's script pubkey, and the registration address used to calculate the preorder hash. Return the preorder record on success. Return None if not found, or the preorder is already registered and not expired (even if revoked). NOTE: possibly returns an expired preorder (by design, so as to prevent someone from re-sending the same preorder with the same preorder hash). """ # name registered and not expired? name_rec = self.get_name( name ) if name_rec is not None and not include_failed: return None # what namespace are we in? namespace_id = get_namespace_from_name(name) namespace = self.get_namespace(namespace_id) if namespace is None: return None # isn't currently registered, or we don't care preorder_hash = hash_name(name, sender_script_pubkey, register_addr=register_addr) preorder = namedb_get_name_preorder( self.db, preorder_hash, self.lastblock ) if preorder is None: # doesn't exist or expired return None # preorder must be younger than the namespace lifetime # (otherwise we get into weird conditions where someone can preorder # a name before someone else, and register it after it expires) namespace_lifetime_multiplier = get_epoch_namespace_lifetime_multiplier( self.lastblock, namespace_id ) if preorder['block_number'] + (namespace['lifetime'] * namespace_lifetime_multiplier) <= self.lastblock: log.debug("Preorder is too old (accepted at {}, namespace lifetime is {}, current block is {})".format(preorder['block_number'], namespace['lifetime'] * namespace_lifetime_multiplier, self.lastblock)) return None return preorder
python
def get_name_preorder( self, name, sender_script_pubkey, register_addr, include_failed=False ): """ Get the current preorder for a name, given the name, the sender's script pubkey, and the registration address used to calculate the preorder hash. Return the preorder record on success. Return None if not found, or the preorder is already registered and not expired (even if revoked). NOTE: possibly returns an expired preorder (by design, so as to prevent someone from re-sending the same preorder with the same preorder hash). """ # name registered and not expired? name_rec = self.get_name( name ) if name_rec is not None and not include_failed: return None # what namespace are we in? namespace_id = get_namespace_from_name(name) namespace = self.get_namespace(namespace_id) if namespace is None: return None # isn't currently registered, or we don't care preorder_hash = hash_name(name, sender_script_pubkey, register_addr=register_addr) preorder = namedb_get_name_preorder( self.db, preorder_hash, self.lastblock ) if preorder is None: # doesn't exist or expired return None # preorder must be younger than the namespace lifetime # (otherwise we get into weird conditions where someone can preorder # a name before someone else, and register it after it expires) namespace_lifetime_multiplier = get_epoch_namespace_lifetime_multiplier( self.lastblock, namespace_id ) if preorder['block_number'] + (namespace['lifetime'] * namespace_lifetime_multiplier) <= self.lastblock: log.debug("Preorder is too old (accepted at {}, namespace lifetime is {}, current block is {})".format(preorder['block_number'], namespace['lifetime'] * namespace_lifetime_multiplier, self.lastblock)) return None return preorder
[ "def", "get_name_preorder", "(", "self", ",", "name", ",", "sender_script_pubkey", ",", "register_addr", ",", "include_failed", "=", "False", ")", ":", "name_rec", "=", "self", ".", "get_name", "(", "name", ")", "if", "name_rec", "is", "not", "None", "and", ...
Get the current preorder for a name, given the name, the sender's script pubkey, and the registration address used to calculate the preorder hash. Return the preorder record on success. Return None if not found, or the preorder is already registered and not expired (even if revoked). NOTE: possibly returns an expired preorder (by design, so as to prevent someone from re-sending the same preorder with the same preorder hash).
[ "Get", "the", "current", "preorder", "for", "a", "name", "given", "the", "name", "the", "sender", "s", "script", "pubkey", "and", "the", "registration", "address", "used", "to", "calculate", "the", "preorder", "hash", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1166-L1203
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_names_with_value_hash
def get_names_with_value_hash( self, value_hash ): """ Get the list of names with the given value hash, at the current block height. This excludes revoked names and expired names. Return None if there are no such names """ cur = self.db.cursor() names = namedb_get_names_with_value_hash( cur, value_hash, self.lastblock ) return names
python
def get_names_with_value_hash( self, value_hash ): """ Get the list of names with the given value hash, at the current block height. This excludes revoked names and expired names. Return None if there are no such names """ cur = self.db.cursor() names = namedb_get_names_with_value_hash( cur, value_hash, self.lastblock ) return names
[ "def", "get_names_with_value_hash", "(", "self", ",", "value_hash", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "names", "=", "namedb_get_names_with_value_hash", "(", "cur", ",", "value_hash", ",", "self", ".", "lastblock", ")", "return...
Get the list of names with the given value hash, at the current block height. This excludes revoked names and expired names. Return None if there are no such names
[ "Get", "the", "list", "of", "names", "with", "the", "given", "value", "hash", "at", "the", "current", "block", "height", ".", "This", "excludes", "revoked", "names", "and", "expired", "names", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1235-L1244
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_atlas_zonefile_info_at
def get_atlas_zonefile_info_at( self, block_id ): """ Get the blockchain-ordered sequence of names, value hashes, and txids. added at the given block height. The order will be in tx-order. Return [{'name': name, 'value_hash': value_hash, 'txid': txid}] """ nameops = self.get_all_blockstack_ops_at( block_id ) ret = [] for nameop in nameops: if nameop.has_key('op') and op_get_opcode_name(nameop['op']) in ['NAME_UPDATE', 'NAME_IMPORT', 'NAME_REGISTRATION', 'NAME_RENEWAL']: assert nameop.has_key('value_hash') assert nameop.has_key('name') assert nameop.has_key('txid') if nameop['value_hash'] is not None: ret.append( {'name': nameop['name'], 'value_hash': nameop['value_hash'], 'txid': nameop['txid']} ) return ret
python
def get_atlas_zonefile_info_at( self, block_id ): """ Get the blockchain-ordered sequence of names, value hashes, and txids. added at the given block height. The order will be in tx-order. Return [{'name': name, 'value_hash': value_hash, 'txid': txid}] """ nameops = self.get_all_blockstack_ops_at( block_id ) ret = [] for nameop in nameops: if nameop.has_key('op') and op_get_opcode_name(nameop['op']) in ['NAME_UPDATE', 'NAME_IMPORT', 'NAME_REGISTRATION', 'NAME_RENEWAL']: assert nameop.has_key('value_hash') assert nameop.has_key('name') assert nameop.has_key('txid') if nameop['value_hash'] is not None: ret.append( {'name': nameop['name'], 'value_hash': nameop['value_hash'], 'txid': nameop['txid']} ) return ret
[ "def", "get_atlas_zonefile_info_at", "(", "self", ",", "block_id", ")", ":", "nameops", "=", "self", ".", "get_all_blockstack_ops_at", "(", "block_id", ")", "ret", "=", "[", "]", "for", "nameop", "in", "nameops", ":", "if", "nameop", ".", "has_key", "(", "...
Get the blockchain-ordered sequence of names, value hashes, and txids. added at the given block height. The order will be in tx-order. Return [{'name': name, 'value_hash': value_hash, 'txid': txid}]
[ "Get", "the", "blockchain", "-", "ordered", "sequence", "of", "names", "value", "hashes", "and", "txids", ".", "added", "at", "the", "given", "block", "height", ".", "The", "order", "will", "be", "in", "tx", "-", "order", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1247-L1267
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_namespace_reveal
def get_namespace_reveal( self, namespace_id, include_history=True ): """ Given the name of a namespace, get it if it is currently being revealed. Return the reveal record on success. Return None if it is not being revealed, or is expired. """ cur = self.db.cursor() namespace_reveal = namedb_get_namespace_reveal( cur, namespace_id, self.lastblock, include_history=include_history ) return namespace_reveal
python
def get_namespace_reveal( self, namespace_id, include_history=True ): """ Given the name of a namespace, get it if it is currently being revealed. Return the reveal record on success. Return None if it is not being revealed, or is expired. """ cur = self.db.cursor() namespace_reveal = namedb_get_namespace_reveal( cur, namespace_id, self.lastblock, include_history=include_history ) return namespace_reveal
[ "def", "get_namespace_reveal", "(", "self", ",", "namespace_id", ",", "include_history", "=", "True", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_reveal", "=", "namedb_get_namespace_reveal", "(", "cur", ",", "namespace_id", ","...
Given the name of a namespace, get it if it is currently being revealed. Return the reveal record on success. Return None if it is not being revealed, or is expired.
[ "Given", "the", "name", "of", "a", "namespace", "get", "it", "if", "it", "is", "currently", "being", "revealed", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1306-L1316
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_name_registered
def is_name_registered( self, name ): """ Given the fully-qualified name, is it registered, not revoked, and not expired at the current block? """ name_rec = self.get_name( name ) # won't return the name if expired if name_rec is None: return False if name_rec['revoked']: return False return True
python
def is_name_registered( self, name ): """ Given the fully-qualified name, is it registered, not revoked, and not expired at the current block? """ name_rec = self.get_name( name ) # won't return the name if expired if name_rec is None: return False if name_rec['revoked']: return False return True
[ "def", "is_name_registered", "(", "self", ",", "name", ")", ":", "name_rec", "=", "self", ".", "get_name", "(", "name", ")", "if", "name_rec", "is", "None", ":", "return", "False", "if", "name_rec", "[", "'revoked'", "]", ":", "return", "False", "return"...
Given the fully-qualified name, is it registered, not revoked, and not expired at the current block?
[ "Given", "the", "fully", "-", "qualified", "name", "is", "it", "registered", "not", "revoked", "and", "not", "expired", "at", "the", "current", "block?" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1392-L1404
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_namespace_ready
def is_namespace_ready( self, namespace_id ): """ Given a namespace ID, determine if the namespace is ready at the current block. """ namespace = self.get_namespace( namespace_id ) if namespace is not None: return True else: return False
python
def is_namespace_ready( self, namespace_id ): """ Given a namespace ID, determine if the namespace is ready at the current block. """ namespace = self.get_namespace( namespace_id ) if namespace is not None: return True else: return False
[ "def", "is_namespace_ready", "(", "self", ",", "namespace_id", ")", ":", "namespace", "=", "self", ".", "get_namespace", "(", "namespace_id", ")", "if", "namespace", "is", "not", "None", ":", "return", "True", "else", ":", "return", "False" ]
Given a namespace ID, determine if the namespace is ready at the current block.
[ "Given", "a", "namespace", "ID", "determine", "if", "the", "namespace", "is", "ready", "at", "the", "current", "block", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1407-L1416
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_namespace_preordered
def is_namespace_preordered( self, namespace_id_hash ): """ Given a namespace preorder hash, determine if it is preordered at the current block. """ namespace_preorder = self.get_namespace_preorder(namespace_id_hash) if namespace_preorder is None: return False else: return True
python
def is_namespace_preordered( self, namespace_id_hash ): """ Given a namespace preorder hash, determine if it is preordered at the current block. """ namespace_preorder = self.get_namespace_preorder(namespace_id_hash) if namespace_preorder is None: return False else: return True
[ "def", "is_namespace_preordered", "(", "self", ",", "namespace_id_hash", ")", ":", "namespace_preorder", "=", "self", ".", "get_namespace_preorder", "(", "namespace_id_hash", ")", "if", "namespace_preorder", "is", "None", ":", "return", "False", "else", ":", "return...
Given a namespace preorder hash, determine if it is preordered at the current block.
[ "Given", "a", "namespace", "preorder", "hash", "determine", "if", "it", "is", "preordered", "at", "the", "current", "block", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1419-L1428
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_namespace_revealed
def is_namespace_revealed( self, namespace_id ): """ Given the name of a namespace, has it been revealed but not made ready at the current block? """ namespace_reveal = self.get_namespace_reveal( namespace_id ) if namespace_reveal is not None: return True else: return False
python
def is_namespace_revealed( self, namespace_id ): """ Given the name of a namespace, has it been revealed but not made ready at the current block? """ namespace_reveal = self.get_namespace_reveal( namespace_id ) if namespace_reveal is not None: return True else: return False
[ "def", "is_namespace_revealed", "(", "self", ",", "namespace_id", ")", ":", "namespace_reveal", "=", "self", ".", "get_namespace_reveal", "(", "namespace_id", ")", "if", "namespace_reveal", "is", "not", "None", ":", "return", "True", "else", ":", "return", "Fals...
Given the name of a namespace, has it been revealed but not made ready at the current block?
[ "Given", "the", "name", "of", "a", "namespace", "has", "it", "been", "revealed", "but", "not", "made", "ready", "at", "the", "current", "block?" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1431-L1440
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_name_owner
def is_name_owner( self, name, sender_script_pubkey ): """ Given the fully-qualified name and a sender's script pubkey, determine if the sender owns the name. The name must exist and not be revoked or expired at the current block. """ if not self.is_name_registered( name ): # no one owns it return False owner = self.get_name_owner( name ) if owner != sender_script_pubkey: return False else: return True
python
def is_name_owner( self, name, sender_script_pubkey ): """ Given the fully-qualified name and a sender's script pubkey, determine if the sender owns the name. The name must exist and not be revoked or expired at the current block. """ if not self.is_name_registered( name ): # no one owns it return False owner = self.get_name_owner( name ) if owner != sender_script_pubkey: return False else: return True
[ "def", "is_name_owner", "(", "self", ",", "name", ",", "sender_script_pubkey", ")", ":", "if", "not", "self", ".", "is_name_registered", "(", "name", ")", ":", "return", "False", "owner", "=", "self", ".", "get_name_owner", "(", "name", ")", "if", "owner",...
Given the fully-qualified name and a sender's script pubkey, determine if the sender owns the name. The name must exist and not be revoked or expired at the current block.
[ "Given", "the", "fully", "-", "qualified", "name", "and", "a", "sender", "s", "script", "pubkey", "determine", "if", "the", "sender", "owns", "the", "name", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1443-L1459
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_new_preorder
def is_new_preorder( self, preorder_hash, lastblock=None ): """ Given a preorder hash of a name, determine whether or not it is unseen before. """ if lastblock is None: lastblock = self.lastblock preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock ) if preorder is not None: return False else: return True
python
def is_new_preorder( self, preorder_hash, lastblock=None ): """ Given a preorder hash of a name, determine whether or not it is unseen before. """ if lastblock is None: lastblock = self.lastblock preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock ) if preorder is not None: return False else: return True
[ "def", "is_new_preorder", "(", "self", ",", "preorder_hash", ",", "lastblock", "=", "None", ")", ":", "if", "lastblock", "is", "None", ":", "lastblock", "=", "self", ".", "lastblock", "preorder", "=", "namedb_get_name_preorder", "(", "self", ".", "db", ",", ...
Given a preorder hash of a name, determine whether or not it is unseen before.
[ "Given", "a", "preorder", "hash", "of", "a", "name", "determine", "whether", "or", "not", "it", "is", "unseen", "before", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1462-L1473
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_new_namespace_preorder
def is_new_namespace_preorder( self, namespace_id_hash, lastblock=None ): """ Given a namespace preorder hash, determine whether or not is is unseen before. """ if lastblock is None: lastblock = self.lastblock preorder = namedb_get_namespace_preorder( self.db, namespace_id_hash, lastblock ) if preorder is not None: return False else: return True
python
def is_new_namespace_preorder( self, namespace_id_hash, lastblock=None ): """ Given a namespace preorder hash, determine whether or not is is unseen before. """ if lastblock is None: lastblock = self.lastblock preorder = namedb_get_namespace_preorder( self.db, namespace_id_hash, lastblock ) if preorder is not None: return False else: return True
[ "def", "is_new_namespace_preorder", "(", "self", ",", "namespace_id_hash", ",", "lastblock", "=", "None", ")", ":", "if", "lastblock", "is", "None", ":", "lastblock", "=", "self", ".", "lastblock", "preorder", "=", "namedb_get_namespace_preorder", "(", "self", "...
Given a namespace preorder hash, determine whether or not is is unseen before.
[ "Given", "a", "namespace", "preorder", "hash", "determine", "whether", "or", "not", "is", "is", "unseen", "before", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1476-L1487
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.is_name_revoked
def is_name_revoked( self, name ): """ Determine if a name is revoked at this block. """ name = self.get_name( name ) if name is None: return False if name['revoked']: return True else: return False
python
def is_name_revoked( self, name ): """ Determine if a name is revoked at this block. """ name = self.get_name( name ) if name is None: return False if name['revoked']: return True else: return False
[ "def", "is_name_revoked", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "get_name", "(", "name", ")", "if", "name", "is", "None", ":", "return", "False", "if", "name", "[", "'revoked'", "]", ":", "return", "True", "else", ":", "return...
Determine if a name is revoked at this block.
[ "Determine", "if", "a", "name", "is", "revoked", "at", "this", "block", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1490-L1501
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.get_value_hash_txids
def get_value_hash_txids(self, value_hash): """ Get the list of txids by value hash """ cur = self.db.cursor() return namedb_get_value_hash_txids(cur, value_hash)
python
def get_value_hash_txids(self, value_hash): """ Get the list of txids by value hash """ cur = self.db.cursor() return namedb_get_value_hash_txids(cur, value_hash)
[ "def", "get_value_hash_txids", "(", "self", ",", "value_hash", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_value_hash_txids", "(", "cur", ",", "value_hash", ")" ]
Get the list of txids by value hash
[ "Get", "the", "list", "of", "txids", "by", "value", "hash" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1511-L1516
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.nameop_set_collided
def nameop_set_collided( cls, nameop, history_id_key, history_id ): """ Mark a nameop as collided """ nameop['__collided__'] = True nameop['__collided_history_id_key__'] = history_id_key nameop['__collided_history_id__'] = history_id
python
def nameop_set_collided( cls, nameop, history_id_key, history_id ): """ Mark a nameop as collided """ nameop['__collided__'] = True nameop['__collided_history_id_key__'] = history_id_key nameop['__collided_history_id__'] = history_id
[ "def", "nameop_set_collided", "(", "cls", ",", "nameop", ",", "history_id_key", ",", "history_id", ")", ":", "nameop", "[", "'__collided__'", "]", "=", "True", "nameop", "[", "'__collided_history_id_key__'", "]", "=", "history_id_key", "nameop", "[", "'__collided_...
Mark a nameop as collided
[ "Mark", "a", "nameop", "as", "collided" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1530-L1536
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.nameop_put_collision
def nameop_put_collision( cls, collisions, nameop ): """ Record a nameop as collided with another nameop in this block. """ # these are supposed to have been put here by nameop_set_collided history_id_key = nameop.get('__collided_history_id_key__', None) history_id = nameop.get('__collided_history_id__', None) try: assert cls.nameop_is_collided( nameop ), "Nameop not collided" assert history_id_key is not None, "Nameop missing collision info" assert history_id is not None, "Nameop missing collision info" except Exception, e: log.exception(e) log.error("FATAL: BUG: bad collision info") os.abort() if not collisions.has_key(history_id_key): collisions[history_id_key] = [history_id] else: collisions[history_id_key].append( history_id )
python
def nameop_put_collision( cls, collisions, nameop ): """ Record a nameop as collided with another nameop in this block. """ # these are supposed to have been put here by nameop_set_collided history_id_key = nameop.get('__collided_history_id_key__', None) history_id = nameop.get('__collided_history_id__', None) try: assert cls.nameop_is_collided( nameop ), "Nameop not collided" assert history_id_key is not None, "Nameop missing collision info" assert history_id is not None, "Nameop missing collision info" except Exception, e: log.exception(e) log.error("FATAL: BUG: bad collision info") os.abort() if not collisions.has_key(history_id_key): collisions[history_id_key] = [history_id] else: collisions[history_id_key].append( history_id )
[ "def", "nameop_put_collision", "(", "cls", ",", "collisions", ",", "nameop", ")", ":", "history_id_key", "=", "nameop", ".", "get", "(", "'__collided_history_id_key__'", ",", "None", ")", "history_id", "=", "nameop", ".", "get", "(", "'__collided_history_id__'", ...
Record a nameop as collided with another nameop in this block.
[ "Record", "a", "nameop", "as", "collided", "with", "another", "nameop", "in", "this", "block", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1548-L1568
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.extract_consensus_op
def extract_consensus_op(self, opcode, op_data, processed_op_data, current_block_number): """ Using the operation data extracted from parsing the virtualchain operation (@op_data), and the checked, processed operation (@processed_op_data), return a dict that contains (1) all of the consensus fields to snapshot this operation, and (2) all of the data fields that we need to store for the name record (i.e. quirk fields) """ ret = {} consensus_fields = op_get_consensus_fields(opcode) quirk_fields = op_get_quirk_fields(opcode) for field in consensus_fields + quirk_fields: try: # assert field in processed_op_data or field in op_data, 'Missing consensus field "{}"'.format(field) assert field in processed_op_data, 'Missing consensus field "{}"'.format(field) except Exception as e: # should NEVER happen log.exception(e) log.error("FATAL: BUG: missing consensus field {}".format(field)) log.error("op_data:\n{}".format(json.dumps(op_data, indent=4, sort_keys=True))) log.error("processed_op_data:\n{}".format(json.dumps(op_data, indent=4, sort_keys=True))) os.abort() ret[field] = processed_op_data[field] return ret
python
def extract_consensus_op(self, opcode, op_data, processed_op_data, current_block_number): """ Using the operation data extracted from parsing the virtualchain operation (@op_data), and the checked, processed operation (@processed_op_data), return a dict that contains (1) all of the consensus fields to snapshot this operation, and (2) all of the data fields that we need to store for the name record (i.e. quirk fields) """ ret = {} consensus_fields = op_get_consensus_fields(opcode) quirk_fields = op_get_quirk_fields(opcode) for field in consensus_fields + quirk_fields: try: # assert field in processed_op_data or field in op_data, 'Missing consensus field "{}"'.format(field) assert field in processed_op_data, 'Missing consensus field "{}"'.format(field) except Exception as e: # should NEVER happen log.exception(e) log.error("FATAL: BUG: missing consensus field {}".format(field)) log.error("op_data:\n{}".format(json.dumps(op_data, indent=4, sort_keys=True))) log.error("processed_op_data:\n{}".format(json.dumps(op_data, indent=4, sort_keys=True))) os.abort() ret[field] = processed_op_data[field] return ret
[ "def", "extract_consensus_op", "(", "self", ",", "opcode", ",", "op_data", ",", "processed_op_data", ",", "current_block_number", ")", ":", "ret", "=", "{", "}", "consensus_fields", "=", "op_get_consensus_fields", "(", "opcode", ")", "quirk_fields", "=", "op_get_q...
Using the operation data extracted from parsing the virtualchain operation (@op_data), and the checked, processed operation (@processed_op_data), return a dict that contains (1) all of the consensus fields to snapshot this operation, and (2) all of the data fields that we need to store for the name record (i.e. quirk fields)
[ "Using", "the", "operation", "data", "extracted", "from", "parsing", "the", "virtualchain", "operation", "(" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1571-L1597
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.commit_operation
def commit_operation( self, input_op_data, accepted_nameop, current_block_number ): """ Commit an operation, thereby carrying out a state transition. Returns a dict with the new db record fields """ # have to have read-write disposition if self.disposition != DISPOSITION_RW: log.error("FATAL: borrowing violation: not a read-write connection") traceback.print_stack() os.abort() cur = self.db.cursor() canonical_op = None op_type_str = None # for debugging opcode = accepted_nameop.get('opcode', None) try: assert opcode is not None, "Undefined op '%s'" % accepted_nameop['op'] except Exception, e: log.exception(e) log.error("FATAL: unrecognized op '%s'" % accepted_nameop['op'] ) os.abort() if opcode in OPCODE_PREORDER_OPS: # preorder canonical_op = self.commit_state_preorder( accepted_nameop, current_block_number ) op_type_str = "state_preorder" elif opcode in OPCODE_CREATION_OPS: # creation canonical_op = self.commit_state_create( accepted_nameop, current_block_number ) op_type_str = "state_create" elif opcode in OPCODE_TRANSITION_OPS: # transition canonical_op = self.commit_state_transition( accepted_nameop, current_block_number ) op_type_str = "state_transition" elif opcode in OPCODE_TOKEN_OPS: # token operation canonical_op = self.commit_token_operation(accepted_nameop, current_block_number) op_type_str = "token_operation" else: raise Exception("Unknown operation {}".format(opcode)) if canonical_op is None: log.error("FATAL: no canonical op generated (for {})".format(op_type_str)) os.abort() log.debug("Extract consensus fields for {} in {}, as part of a {}".format(opcode, current_block_number, op_type_str)) consensus_op = self.extract_consensus_op(opcode, input_op_data, canonical_op, current_block_number) return consensus_op
python
def commit_operation( self, input_op_data, accepted_nameop, current_block_number ): """ Commit an operation, thereby carrying out a state transition. Returns a dict with the new db record fields """ # have to have read-write disposition if self.disposition != DISPOSITION_RW: log.error("FATAL: borrowing violation: not a read-write connection") traceback.print_stack() os.abort() cur = self.db.cursor() canonical_op = None op_type_str = None # for debugging opcode = accepted_nameop.get('opcode', None) try: assert opcode is not None, "Undefined op '%s'" % accepted_nameop['op'] except Exception, e: log.exception(e) log.error("FATAL: unrecognized op '%s'" % accepted_nameop['op'] ) os.abort() if opcode in OPCODE_PREORDER_OPS: # preorder canonical_op = self.commit_state_preorder( accepted_nameop, current_block_number ) op_type_str = "state_preorder" elif opcode in OPCODE_CREATION_OPS: # creation canonical_op = self.commit_state_create( accepted_nameop, current_block_number ) op_type_str = "state_create" elif opcode in OPCODE_TRANSITION_OPS: # transition canonical_op = self.commit_state_transition( accepted_nameop, current_block_number ) op_type_str = "state_transition" elif opcode in OPCODE_TOKEN_OPS: # token operation canonical_op = self.commit_token_operation(accepted_nameop, current_block_number) op_type_str = "token_operation" else: raise Exception("Unknown operation {}".format(opcode)) if canonical_op is None: log.error("FATAL: no canonical op generated (for {})".format(op_type_str)) os.abort() log.debug("Extract consensus fields for {} in {}, as part of a {}".format(opcode, current_block_number, op_type_str)) consensus_op = self.extract_consensus_op(opcode, input_op_data, canonical_op, current_block_number) return consensus_op
[ "def", "commit_operation", "(", "self", ",", "input_op_data", ",", "accepted_nameop", ",", "current_block_number", ")", ":", "if", "self", ".", "disposition", "!=", "DISPOSITION_RW", ":", "log", ".", "error", "(", "\"FATAL: borrowing violation: not a read-write connecti...
Commit an operation, thereby carrying out a state transition. Returns a dict with the new db record fields
[ "Commit", "an", "operation", "thereby", "carrying", "out", "a", "state", "transition", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1600-L1654
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.commit_token_operation
def commit_token_operation(self, token_op, current_block_number): """ Commit a token operation that debits one account and credits another Returns the new canonicalized record (with all compatibility quirks preserved) DO NOT CALL THIS DIRECTLY """ # have to have read-write disposition if self.disposition != DISPOSITION_RW: log.error("FATAL: borrowing violation: not a read-write connection") traceback.print_stack() os.abort() cur = self.db.cursor() opcode = token_op.get('opcode', None) clean_token_op = self.sanitize_op(token_op) try: assert token_operation_is_valid(token_op), 'Invalid token operation' assert opcode is not None, 'No opcode given' assert 'txid' in token_op, 'No txid' assert 'vtxindex' in token_op, 'No vtxindex' except Exception as e: log.exception(e) log.error('FATAL: failed to commit token operation') self.db.rollback() os.abort() table = token_operation_get_table(token_op) account_payment_info = token_operation_get_account_payment_info(token_op) account_credit_info = token_operation_get_account_credit_info(token_op) # fields must be set try: for key in account_payment_info: assert account_payment_info[key] is not None, 'BUG: payment info key {} is None'.format(key) for key in account_credit_info: assert account_credit_info[key] is not None, 'BUG: credit info key {} is not None'.format(key) # NOTE: do not check token amount and type, since in the future we want to support converting # between tokens except Exception as e: log.exception(e) log.error("FATAL: invalid token debit or credit info") os.abort() self.log_accept(current_block_number, token_op['vtxindex'], token_op['op'], token_op) # NOTE: this code is single-threaded, but this code must be atomic self.commit_account_debit(token_op, account_payment_info, current_block_number, token_op['vtxindex'], token_op['txid']) self.commit_account_credit(token_op, account_credit_info, current_block_number, token_op['vtxindex'], token_op['txid']) namedb_history_save(cur, opcode, token_op['address'], None, None, current_block_number, token_op['vtxindex'], token_op['txid'], clean_token_op) return clean_token_op
python
def commit_token_operation(self, token_op, current_block_number): """ Commit a token operation that debits one account and credits another Returns the new canonicalized record (with all compatibility quirks preserved) DO NOT CALL THIS DIRECTLY """ # have to have read-write disposition if self.disposition != DISPOSITION_RW: log.error("FATAL: borrowing violation: not a read-write connection") traceback.print_stack() os.abort() cur = self.db.cursor() opcode = token_op.get('opcode', None) clean_token_op = self.sanitize_op(token_op) try: assert token_operation_is_valid(token_op), 'Invalid token operation' assert opcode is not None, 'No opcode given' assert 'txid' in token_op, 'No txid' assert 'vtxindex' in token_op, 'No vtxindex' except Exception as e: log.exception(e) log.error('FATAL: failed to commit token operation') self.db.rollback() os.abort() table = token_operation_get_table(token_op) account_payment_info = token_operation_get_account_payment_info(token_op) account_credit_info = token_operation_get_account_credit_info(token_op) # fields must be set try: for key in account_payment_info: assert account_payment_info[key] is not None, 'BUG: payment info key {} is None'.format(key) for key in account_credit_info: assert account_credit_info[key] is not None, 'BUG: credit info key {} is not None'.format(key) # NOTE: do not check token amount and type, since in the future we want to support converting # between tokens except Exception as e: log.exception(e) log.error("FATAL: invalid token debit or credit info") os.abort() self.log_accept(current_block_number, token_op['vtxindex'], token_op['op'], token_op) # NOTE: this code is single-threaded, but this code must be atomic self.commit_account_debit(token_op, account_payment_info, current_block_number, token_op['vtxindex'], token_op['txid']) self.commit_account_credit(token_op, account_credit_info, current_block_number, token_op['vtxindex'], token_op['txid']) namedb_history_save(cur, opcode, token_op['address'], None, None, current_block_number, token_op['vtxindex'], token_op['txid'], clean_token_op) return clean_token_op
[ "def", "commit_token_operation", "(", "self", ",", "token_op", ",", "current_block_number", ")", ":", "if", "self", ".", "disposition", "!=", "DISPOSITION_RW", ":", "log", ".", "error", "(", "\"FATAL: borrowing violation: not a read-write connection\"", ")", "traceback"...
Commit a token operation that debits one account and credits another Returns the new canonicalized record (with all compatibility quirks preserved) DO NOT CALL THIS DIRECTLY
[ "Commit", "a", "token", "operation", "that", "debits", "one", "account", "and", "credits", "another" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1935-L1990
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
BlockstackDB.commit_account_vesting
def commit_account_vesting(self, block_height): """ vest any tokens at this block height """ # save all state log.debug("Commit all database state before vesting") self.db.commit() if block_height in self.vesting: traceback.print_stack() log.fatal("Tried to vest tokens twice at {}".format(block_height)) os.abort() # commit all vesting in one transaction cur = self.db.cursor() namedb_query_execute(cur, 'BEGIN', ()) res = namedb_accounts_vest(cur, block_height) namedb_query_execute(cur, 'END', ()) self.vesting[block_height] = True return True
python
def commit_account_vesting(self, block_height): """ vest any tokens at this block height """ # save all state log.debug("Commit all database state before vesting") self.db.commit() if block_height in self.vesting: traceback.print_stack() log.fatal("Tried to vest tokens twice at {}".format(block_height)) os.abort() # commit all vesting in one transaction cur = self.db.cursor() namedb_query_execute(cur, 'BEGIN', ()) res = namedb_accounts_vest(cur, block_height) namedb_query_execute(cur, 'END', ()) self.vesting[block_height] = True return True
[ "def", "commit_account_vesting", "(", "self", ",", "block_height", ")", ":", "log", ".", "debug", "(", "\"Commit all database state before vesting\"", ")", "self", ".", "db", ".", "commit", "(", ")", "if", "block_height", "in", "self", ".", "vesting", ":", "tr...
vest any tokens at this block height
[ "vest", "any", "tokens", "at", "this", "block", "height" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1993-L2013
train
blockstack/blockstack-core
blockstack/lib/scripts.py
is_name_valid
def is_name_valid(fqn): """ Is a fully-qualified name acceptable? Return True if so Return False if not >>> is_name_valid('abcd') False >>> is_name_valid('abcd.') False >>> is_name_valid('.abcd') False >>> is_name_valid('Abcd.abcd') False >>> is_name_valid('abcd.abc.d') False >>> is_name_valid('abcd.abc+d') False >>> is_name_valid('a.b.c') False >>> is_name_valid(True) False >>> is_name_valid(123) False >>> is_name_valid(None) False >>> is_name_valid('') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcda.bcd') True >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdab.bcd') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True >>> is_name_valid('a+b.c') False >>> is_name_valid('a_b.c') True """ if not isinstance(fqn, (str,unicode)): return False if fqn.count( "." ) != 1: return False name, namespace_id = fqn.split(".") if len(name) == 0 or len(namespace_id) == 0: return False if not is_b40( name ) or "+" in name or "." in name: return False if not is_namespace_valid( namespace_id ): return False if len(fqn) > LENGTHS['blockchain_id_name']: # too long return False return True
python
def is_name_valid(fqn): """ Is a fully-qualified name acceptable? Return True if so Return False if not >>> is_name_valid('abcd') False >>> is_name_valid('abcd.') False >>> is_name_valid('.abcd') False >>> is_name_valid('Abcd.abcd') False >>> is_name_valid('abcd.abc.d') False >>> is_name_valid('abcd.abc+d') False >>> is_name_valid('a.b.c') False >>> is_name_valid(True) False >>> is_name_valid(123) False >>> is_name_valid(None) False >>> is_name_valid('') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcda.bcd') True >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdab.bcd') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True >>> is_name_valid('a+b.c') False >>> is_name_valid('a_b.c') True """ if not isinstance(fqn, (str,unicode)): return False if fqn.count( "." ) != 1: return False name, namespace_id = fqn.split(".") if len(name) == 0 or len(namespace_id) == 0: return False if not is_b40( name ) or "+" in name or "." in name: return False if not is_namespace_valid( namespace_id ): return False if len(fqn) > LENGTHS['blockchain_id_name']: # too long return False return True
[ "def", "is_name_valid", "(", "fqn", ")", ":", "if", "not", "isinstance", "(", "fqn", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "False", "if", "fqn", ".", "count", "(", "\".\"", ")", "!=", "1", ":", "return", "False", "name", ",", ...
Is a fully-qualified name acceptable? Return True if so Return False if not >>> is_name_valid('abcd') False >>> is_name_valid('abcd.') False >>> is_name_valid('.abcd') False >>> is_name_valid('Abcd.abcd') False >>> is_name_valid('abcd.abc.d') False >>> is_name_valid('abcd.abc+d') False >>> is_name_valid('a.b.c') False >>> is_name_valid(True) False >>> is_name_valid(123) False >>> is_name_valid(None) False >>> is_name_valid('') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcda.bcd') True >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdab.bcd') False >>> is_name_valid('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True >>> is_name_valid('a+b.c') False >>> is_name_valid('a_b.c') True
[ "Is", "a", "fully", "-", "qualified", "name", "acceptable?", "Return", "True", "if", "so", "Return", "False", "if", "not" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L35-L96
train
blockstack/blockstack-core
blockstack/lib/scripts.py
is_namespace_valid
def is_namespace_valid( namespace_id ): """ Is a namespace ID valid? >>> is_namespace_valid('abcd') True >>> is_namespace_valid('+abcd') False >>> is_namespace_valid('abc.def') False >>> is_namespace_valid('.abcd') False >>> is_namespace_valid('abcdabcdabcdabcdabcd') False >>> is_namespace_valid('abcdabcdabcdabcdabc') True """ if not is_b40( namespace_id ) or "+" in namespace_id or namespace_id.count(".") > 0: return False if len(namespace_id) == 0 or len(namespace_id) > LENGTHS['blockchain_id_namespace_id']: return False return True
python
def is_namespace_valid( namespace_id ): """ Is a namespace ID valid? >>> is_namespace_valid('abcd') True >>> is_namespace_valid('+abcd') False >>> is_namespace_valid('abc.def') False >>> is_namespace_valid('.abcd') False >>> is_namespace_valid('abcdabcdabcdabcdabcd') False >>> is_namespace_valid('abcdabcdabcdabcdabc') True """ if not is_b40( namespace_id ) or "+" in namespace_id or namespace_id.count(".") > 0: return False if len(namespace_id) == 0 or len(namespace_id) > LENGTHS['blockchain_id_namespace_id']: return False return True
[ "def", "is_namespace_valid", "(", "namespace_id", ")", ":", "if", "not", "is_b40", "(", "namespace_id", ")", "or", "\"+\"", "in", "namespace_id", "or", "namespace_id", ".", "count", "(", "\".\"", ")", ">", "0", ":", "return", "False", "if", "len", "(", "...
Is a namespace ID valid? >>> is_namespace_valid('abcd') True >>> is_namespace_valid('+abcd') False >>> is_namespace_valid('abc.def') False >>> is_namespace_valid('.abcd') False >>> is_namespace_valid('abcdabcdabcdabcdabcd') False >>> is_namespace_valid('abcdabcdabcdabcdabc') True
[ "Is", "a", "namespace", "ID", "valid?" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L99-L122
train
blockstack/blockstack-core
blockstack/lib/scripts.py
price_namespace
def price_namespace( namespace_id, block_height, units ): """ Calculate the cost of a namespace. Returns the price on success Returns None if the namespace is invalid or if the units are invalid """ price_table = get_epoch_namespace_prices( block_height, units ) if price_table is None: return None if len(namespace_id) >= len(price_table) or len(namespace_id) == 0: return None return price_table[len(namespace_id)]
python
def price_namespace( namespace_id, block_height, units ): """ Calculate the cost of a namespace. Returns the price on success Returns None if the namespace is invalid or if the units are invalid """ price_table = get_epoch_namespace_prices( block_height, units ) if price_table is None: return None if len(namespace_id) >= len(price_table) or len(namespace_id) == 0: return None return price_table[len(namespace_id)]
[ "def", "price_namespace", "(", "namespace_id", ",", "block_height", ",", "units", ")", ":", "price_table", "=", "get_epoch_namespace_prices", "(", "block_height", ",", "units", ")", "if", "price_table", "is", "None", ":", "return", "None", "if", "len", "(", "n...
Calculate the cost of a namespace. Returns the price on success Returns None if the namespace is invalid or if the units are invalid
[ "Calculate", "the", "cost", "of", "a", "namespace", ".", "Returns", "the", "price", "on", "success", "Returns", "None", "if", "the", "namespace", "is", "invalid", "or", "if", "the", "units", "are", "invalid" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L311-L324
train
blockstack/blockstack-core
blockstack/lib/scripts.py
find_by_opcode
def find_by_opcode( checked_ops, opcode ): """ Given all previously-accepted operations in this block, find the ones that are of a particular opcode. @opcode can be one opcode, or a list of opcodes >>> find_by_opcode([{'op': '+'}, {'op': '>'}], 'NAME_UPDATE') [{'op': '+'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ['NAME_UPDATE', 'NAME_TRANSFER']) [{'op': '+'}, {'op': '>'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ':') [] >>> find_by_opcode([], ':') [] """ if type(opcode) != list: opcode = [opcode] ret = [] for opdata in checked_ops: if op_get_opcode_name(opdata['op']) in opcode: ret.append(opdata) return ret
python
def find_by_opcode( checked_ops, opcode ): """ Given all previously-accepted operations in this block, find the ones that are of a particular opcode. @opcode can be one opcode, or a list of opcodes >>> find_by_opcode([{'op': '+'}, {'op': '>'}], 'NAME_UPDATE') [{'op': '+'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ['NAME_UPDATE', 'NAME_TRANSFER']) [{'op': '+'}, {'op': '>'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ':') [] >>> find_by_opcode([], ':') [] """ if type(opcode) != list: opcode = [opcode] ret = [] for opdata in checked_ops: if op_get_opcode_name(opdata['op']) in opcode: ret.append(opdata) return ret
[ "def", "find_by_opcode", "(", "checked_ops", ",", "opcode", ")", ":", "if", "type", "(", "opcode", ")", "!=", "list", ":", "opcode", "=", "[", "opcode", "]", "ret", "=", "[", "]", "for", "opdata", "in", "checked_ops", ":", "if", "op_get_opcode_name", "...
Given all previously-accepted operations in this block, find the ones that are of a particular opcode. @opcode can be one opcode, or a list of opcodes >>> find_by_opcode([{'op': '+'}, {'op': '>'}], 'NAME_UPDATE') [{'op': '+'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ['NAME_UPDATE', 'NAME_TRANSFER']) [{'op': '+'}, {'op': '>'}] >>> find_by_opcode([{'op': '+'}, {'op': '>'}], ':') [] >>> find_by_opcode([], ':') []
[ "Given", "all", "previously", "-", "accepted", "operations", "in", "this", "block", "find", "the", "ones", "that", "are", "of", "a", "particular", "opcode", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L327-L352
train
blockstack/blockstack-core
blockstack/lib/scripts.py
get_public_key_hex_from_tx
def get_public_key_hex_from_tx( inputs, address ): """ Given a list of inputs and the address of one of the inputs, find the public key. This only works for p2pkh scripts. We only really need this for NAMESPACE_REVEAL, but we included it in other transactions' consensus data for legacy reasons that now have to be supported forever :( """ ret = None for inp in inputs: input_scriptsig = inp['script'] input_script_code = virtualchain.btc_script_deserialize(input_scriptsig) if len(input_script_code) == 2: # signature pubkey pubkey_candidate = input_script_code[1] pubkey = None try: pubkey = virtualchain.BitcoinPublicKey(pubkey_candidate) except Exception as e: traceback.print_exc() log.warn("Invalid public key {}".format(pubkey_candidate)) continue if address != pubkey.address(): continue # success! return pubkey_candidate return None
python
def get_public_key_hex_from_tx( inputs, address ): """ Given a list of inputs and the address of one of the inputs, find the public key. This only works for p2pkh scripts. We only really need this for NAMESPACE_REVEAL, but we included it in other transactions' consensus data for legacy reasons that now have to be supported forever :( """ ret = None for inp in inputs: input_scriptsig = inp['script'] input_script_code = virtualchain.btc_script_deserialize(input_scriptsig) if len(input_script_code) == 2: # signature pubkey pubkey_candidate = input_script_code[1] pubkey = None try: pubkey = virtualchain.BitcoinPublicKey(pubkey_candidate) except Exception as e: traceback.print_exc() log.warn("Invalid public key {}".format(pubkey_candidate)) continue if address != pubkey.address(): continue # success! return pubkey_candidate return None
[ "def", "get_public_key_hex_from_tx", "(", "inputs", ",", "address", ")", ":", "ret", "=", "None", "for", "inp", "in", "inputs", ":", "input_scriptsig", "=", "inp", "[", "'script'", "]", "input_script_code", "=", "virtualchain", ".", "btc_script_deserialize", "("...
Given a list of inputs and the address of one of the inputs, find the public key. This only works for p2pkh scripts. We only really need this for NAMESPACE_REVEAL, but we included it in other transactions' consensus data for legacy reasons that now have to be supported forever :(
[ "Given", "a", "list", "of", "inputs", "and", "the", "address", "of", "one", "of", "the", "inputs", "find", "the", "public", "key", "." ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L355-L388
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_name
def check_name(name): """ Verify the name is well-formed >>> check_name(123) False >>> check_name('') False >>> check_name('abc') False >>> check_name('abc.def') True >>> check_name('abc.def.ghi') False >>> check_name('abc.d-ef') True >>> check_name('abc.d+ef') False >>> check_name('.abc') False >>> check_name('abc.') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.abcd') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True """ if type(name) not in [str, unicode]: return False if not is_name_valid(name): return False return True
python
def check_name(name): """ Verify the name is well-formed >>> check_name(123) False >>> check_name('') False >>> check_name('abc') False >>> check_name('abc.def') True >>> check_name('abc.def.ghi') False >>> check_name('abc.d-ef') True >>> check_name('abc.d+ef') False >>> check_name('.abc') False >>> check_name('abc.') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.abcd') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True """ if type(name) not in [str, unicode]: return False if not is_name_valid(name): return False return True
[ "def", "check_name", "(", "name", ")", ":", "if", "type", "(", "name", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_name_valid", "(", "name", ")", ":", "return", "False", "return", "True" ]
Verify the name is well-formed >>> check_name(123) False >>> check_name('') False >>> check_name('abc') False >>> check_name('abc.def') True >>> check_name('abc.def.ghi') False >>> check_name('abc.d-ef') True >>> check_name('abc.d+ef') False >>> check_name('.abc') False >>> check_name('abc.') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.abcd') False >>> check_name('abcdabcdabcdabcdabcdabcdabcdabcdabc.d') True
[ "Verify", "the", "name", "is", "well", "-", "formed" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L391-L424
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_namespace
def check_namespace(namespace_id): """ Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> check_namespace('a+bcd') False >>> check_namespace('.abcd') False >>> check_namespace('abcdabcdabcdabcdabcd') False >>> check_namespace('abcdabcdabcdabcdabc') True """ if type(namespace_id) not in [str, unicode]: return False if not is_namespace_valid(namespace_id): return False return True
python
def check_namespace(namespace_id): """ Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> check_namespace('a+bcd') False >>> check_namespace('.abcd') False >>> check_namespace('abcdabcdabcdabcdabcd') False >>> check_namespace('abcdabcdabcdabcdabc') True """ if type(namespace_id) not in [str, unicode]: return False if not is_namespace_valid(namespace_id): return False return True
[ "def", "check_namespace", "(", "namespace_id", ")", ":", "if", "type", "(", "namespace_id", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_namespace_valid", "(", "namespace_id", ")", ":", "return", "False", "ret...
Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> check_namespace('a+bcd') False >>> check_namespace('.abcd') False >>> check_namespace('abcdabcdabcdabcdabcd') False >>> check_namespace('abcdabcdabcdabcdabc') True
[ "Verify", "that", "a", "namespace", "ID", "is", "well", "-", "formed" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L427-L456
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_token_type
def check_token_type(token_type): """ Verify that a token type is well-formed >>> check_token_type('STACKS') True >>> check_token_type('BTC') False >>> check_token_type('abcdabcdabcd') True >>> check_token_type('abcdabcdabcdabcdabcd') False """ return check_string(token_type, min_length=1, max_length=LENGTHS['namespace_id'], pattern='^{}$|{}'.format(TOKEN_TYPE_STACKS, OP_NAMESPACE_PATTERN))
python
def check_token_type(token_type): """ Verify that a token type is well-formed >>> check_token_type('STACKS') True >>> check_token_type('BTC') False >>> check_token_type('abcdabcdabcd') True >>> check_token_type('abcdabcdabcdabcdabcd') False """ return check_string(token_type, min_length=1, max_length=LENGTHS['namespace_id'], pattern='^{}$|{}'.format(TOKEN_TYPE_STACKS, OP_NAMESPACE_PATTERN))
[ "def", "check_token_type", "(", "token_type", ")", ":", "return", "check_string", "(", "token_type", ",", "min_length", "=", "1", ",", "max_length", "=", "LENGTHS", "[", "'namespace_id'", "]", ",", "pattern", "=", "'^{}$|{}'", ".", "format", "(", "TOKEN_TYPE_S...
Verify that a token type is well-formed >>> check_token_type('STACKS') True >>> check_token_type('BTC') False >>> check_token_type('abcdabcdabcd') True >>> check_token_type('abcdabcdabcdabcdabcd') False
[ "Verify", "that", "a", "token", "type", "is", "well", "-", "formed" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L459-L472
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_subdomain
def check_subdomain(fqn): """ Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a.b') True >>> check_subdomain('a.abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a') False >>> check_subdomain('a.b.cdabcdabcdabcdabcdabcdabcdabcdabcd') False >>> check_subdomain('a.b') False """ if type(fqn) not in [str, unicode]: return False if not is_subdomain(fqn): return False return True
python
def check_subdomain(fqn): """ Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a.b') True >>> check_subdomain('a.abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a') False >>> check_subdomain('a.b.cdabcdabcdabcdabcdabcdabcdabcdabcd') False >>> check_subdomain('a.b') False """ if type(fqn) not in [str, unicode]: return False if not is_subdomain(fqn): return False return True
[ "def", "check_subdomain", "(", "fqn", ")", ":", "if", "type", "(", "fqn", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_subdomain", "(", "fqn", ")", ":", "return", "False", "return", "True" ]
Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a.b') True >>> check_subdomain('a.abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a') False >>> check_subdomain('a.b.cdabcdabcdabcdabcdabcdabcdabcdabcd') False >>> check_subdomain('a.b') False
[ "Verify", "that", "the", "given", "fqn", "is", "a", "subdomain" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L475-L502
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_block
def check_block(block_id): """ Verify that a block ID is valid >>> check_block(FIRST_BLOCK_MAINNET) True >>> check_block(FIRST_BLOCK_MAINNET-1) False >>> check_block(-1) False >>> check_block("abc") False >>> check_block(int(1e7) + 1) False >>> check_block(int(1e7) - 1) True """ if type(block_id) not in [int, long]: return False if BLOCKSTACK_TEST: if block_id <= 0: return False else: if block_id < FIRST_BLOCK_MAINNET: return False if block_id > 1e7: # 1 million blocks? not in my lifetime return False return True
python
def check_block(block_id): """ Verify that a block ID is valid >>> check_block(FIRST_BLOCK_MAINNET) True >>> check_block(FIRST_BLOCK_MAINNET-1) False >>> check_block(-1) False >>> check_block("abc") False >>> check_block(int(1e7) + 1) False >>> check_block(int(1e7) - 1) True """ if type(block_id) not in [int, long]: return False if BLOCKSTACK_TEST: if block_id <= 0: return False else: if block_id < FIRST_BLOCK_MAINNET: return False if block_id > 1e7: # 1 million blocks? not in my lifetime return False return True
[ "def", "check_block", "(", "block_id", ")", ":", "if", "type", "(", "block_id", ")", "not", "in", "[", "int", ",", "long", "]", ":", "return", "False", "if", "BLOCKSTACK_TEST", ":", "if", "block_id", "<=", "0", ":", "return", "False", "else", ":", "i...
Verify that a block ID is valid >>> check_block(FIRST_BLOCK_MAINNET) True >>> check_block(FIRST_BLOCK_MAINNET-1) False >>> check_block(-1) False >>> check_block("abc") False >>> check_block(int(1e7) + 1) False >>> check_block(int(1e7) - 1) True
[ "Verify", "that", "a", "block", "ID", "is", "valid" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L505-L537
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_offset
def check_offset(offset, max_value=None): """ Verify that an offset is valid >>> check_offset(0) True >>> check_offset(-1) False >>> check_offset(2, max_value=2) True >>> check_offset(0) True >>> check_offset(2, max_value=1) False >>> check_offset('abc') False """ if type(offset) not in [int, long]: return False if offset < 0: return False if max_value and offset > max_value: return False return True
python
def check_offset(offset, max_value=None): """ Verify that an offset is valid >>> check_offset(0) True >>> check_offset(-1) False >>> check_offset(2, max_value=2) True >>> check_offset(0) True >>> check_offset(2, max_value=1) False >>> check_offset('abc') False """ if type(offset) not in [int, long]: return False if offset < 0: return False if max_value and offset > max_value: return False return True
[ "def", "check_offset", "(", "offset", ",", "max_value", "=", "None", ")", ":", "if", "type", "(", "offset", ")", "not", "in", "[", "int", ",", "long", "]", ":", "return", "False", "if", "offset", "<", "0", ":", "return", "False", "if", "max_value", ...
Verify that an offset is valid >>> check_offset(0) True >>> check_offset(-1) False >>> check_offset(2, max_value=2) True >>> check_offset(0) True >>> check_offset(2, max_value=1) False >>> check_offset('abc') False
[ "Verify", "that", "an", "offset", "is", "valid" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L540-L566
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_string
def check_string(value, min_length=None, max_length=None, pattern=None): """ verify that a string has a particular size and conforms to a particular alphabet >>> check_string(1) False >>> check_string(None) False >>> check_string(True) False >>> check_string({}) False >>> check_string([]) False >>> check_string((1,2)) False >>> check_string('abc') True >>> check_string('') True >>> check_string(u'') True >>> check_string('abc', min_length=0, max_length=3) True >>> check_string('abc', min_length=3, max_length=3) True >>> check_string('abc', min_length=4, max_length=5) False >>> check_string('abc', min_length=0, max_length=2) False >>> check_string('abc', pattern='^abc$') True >>> check_string('abc', pattern='^abd$') False """ if type(value) not in [str, unicode]: return False if min_length and len(value) < min_length: return False if max_length and len(value) > max_length: return False if pattern and not re.match(pattern, value): return False return True
python
def check_string(value, min_length=None, max_length=None, pattern=None): """ verify that a string has a particular size and conforms to a particular alphabet >>> check_string(1) False >>> check_string(None) False >>> check_string(True) False >>> check_string({}) False >>> check_string([]) False >>> check_string((1,2)) False >>> check_string('abc') True >>> check_string('') True >>> check_string(u'') True >>> check_string('abc', min_length=0, max_length=3) True >>> check_string('abc', min_length=3, max_length=3) True >>> check_string('abc', min_length=4, max_length=5) False >>> check_string('abc', min_length=0, max_length=2) False >>> check_string('abc', pattern='^abc$') True >>> check_string('abc', pattern='^abd$') False """ if type(value) not in [str, unicode]: return False if min_length and len(value) < min_length: return False if max_length and len(value) > max_length: return False if pattern and not re.match(pattern, value): return False return True
[ "def", "check_string", "(", "value", ",", "min_length", "=", "None", ",", "max_length", "=", "None", ",", "pattern", "=", "None", ")", ":", "if", "type", "(", "value", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", ...
verify that a string has a particular size and conforms to a particular alphabet >>> check_string(1) False >>> check_string(None) False >>> check_string(True) False >>> check_string({}) False >>> check_string([]) False >>> check_string((1,2)) False >>> check_string('abc') True >>> check_string('') True >>> check_string(u'') True >>> check_string('abc', min_length=0, max_length=3) True >>> check_string('abc', min_length=3, max_length=3) True >>> check_string('abc', min_length=4, max_length=5) False >>> check_string('abc', min_length=0, max_length=2) False >>> check_string('abc', pattern='^abc$') True >>> check_string('abc', pattern='^abd$') False
[ "verify", "that", "a", "string", "has", "a", "particular", "size", "and", "conforms", "to", "a", "particular", "alphabet" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L606-L654
train
blockstack/blockstack-core
blockstack/lib/scripts.py
check_address
def check_address(address): """ verify that a string is a base58check address >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg') True >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh') False >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu') True >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWv') False >>> check_address('MD8WooqTKmwromdMQfSNh8gPTPCSf8KaZj') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2j') False >>> check_address('16SuThrz') False >>> check_address('1TGKrgtrQjgoPjoa5BnUZ9Qu') False >>> check_address('1LPckRbeTfLjzrfTfnCtP7z2GxFTpZLafXi') True """ if not check_string(address, min_length=26, max_length=35, pattern=OP_ADDRESS_PATTERN): return False try: keylib.b58check_decode(address) return True except: return False
python
def check_address(address): """ verify that a string is a base58check address >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg') True >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh') False >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu') True >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWv') False >>> check_address('MD8WooqTKmwromdMQfSNh8gPTPCSf8KaZj') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2j') False >>> check_address('16SuThrz') False >>> check_address('1TGKrgtrQjgoPjoa5BnUZ9Qu') False >>> check_address('1LPckRbeTfLjzrfTfnCtP7z2GxFTpZLafXi') True """ if not check_string(address, min_length=26, max_length=35, pattern=OP_ADDRESS_PATTERN): return False try: keylib.b58check_decode(address) return True except: return False
[ "def", "check_address", "(", "address", ")", ":", "if", "not", "check_string", "(", "address", ",", "min_length", "=", "26", ",", "max_length", "=", "35", ",", "pattern", "=", "OP_ADDRESS_PATTERN", ")", ":", "return", "False", "try", ":", "keylib", ".", ...
verify that a string is a base58check address >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg') True >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh') False >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu') True >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWv') False >>> check_address('MD8WooqTKmwromdMQfSNh8gPTPCSf8KaZj') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i') True >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2j') False >>> check_address('16SuThrz') False >>> check_address('1TGKrgtrQjgoPjoa5BnUZ9Qu') False >>> check_address('1LPckRbeTfLjzrfTfnCtP7z2GxFTpZLafXi') True
[ "verify", "that", "a", "string", "is", "a", "base58check", "address" ]
1dcfdd39b152d29ce13e736a6a1a0981401a0505
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L657-L689
train