id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,700 | blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_get_consensus_fields | def op_get_consensus_fields( op_name ):
"""
Get the set of consensus-generating fields for an operation.
"""
global SERIALIZE_FIELDS
if op_name not in SERIALIZE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name )
fields = SERIALIZE_FIELDS[op_name][:]
return fields | python | def op_get_consensus_fields( op_name ):
"""
Get the set of consensus-generating fields for an operation.
"""
global SERIALIZE_FIELDS
if op_name not in SERIALIZE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name )
fields = SERIALIZE_FIELDS[op_name][:]
return fields | [
"def",
"op_get_consensus_fields",
"(",
"op_name",
")",
":",
"global",
"SERIALIZE_FIELDS",
"if",
"op_name",
"not",
"in",
"SERIALIZE_FIELDS",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"No such operation '%s'\"",
"%",
"op_name",
")",
"fields",
"=",
"SERIALIZE_FIELDS",
"[",
"op_name",
"]",
"[",
":",
"]",
"return",
"fields"
] | Get the set of consensus-generating fields for an operation. | [
"Get",
"the",
"set",
"of",
"consensus",
"-",
"generating",
"fields",
"for",
"an",
"operation",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L360-L370 |
230,701 | blockstack/blockstack-core | blockstack/lib/operations/update.py | check | def check(state_engine, nameop, block_id, checked_ops ):
"""
Verify the validity of an update to a name's associated data.
Use the nameop's 128-bit name hash to find the name itself.
NAME_UPDATE isn't allowed during an import, so the name's namespace must be ready.
Return True if accepted
Return False if not.
"""
name_consensus_hash = nameop['name_consensus_hash']
sender = nameop['sender']
# deny updates if we exceed quota--the only legal operations are to revoke or transfer.
sender_names = state_engine.get_names_owned_by_sender( sender )
if len(sender_names) > MAX_NAMES_PER_SENDER:
log.warning("Sender '%s' has exceeded quota: only transfers or revokes are allowed" % (sender))
return False
name, consensus_hash = state_engine.get_name_from_name_consensus_hash( name_consensus_hash, sender, block_id )
# name must exist
if name is None or consensus_hash is None:
log.warning("Unable to resolve name consensus hash '%s' to a name owned by '%s'" % (name_consensus_hash, sender))
# nothing to do--write is stale or on a fork
return False
namespace_id = get_namespace_from_name( name )
name_rec = state_engine.get_name( name )
if name_rec is None:
log.warning("Name '%s' does not exist" % name)
return False
# namespace must be ready
if not state_engine.is_namespace_ready( namespace_id ):
# non-existent namespace
log.warning("Namespace '%s' is not ready" % (namespace_id))
return False
# name must not be revoked
if state_engine.is_name_revoked( name ):
log.warning("Name '%s' is revoked" % name)
return False
# name must not be expired as of the *last block processed*
if state_engine.is_name_expired( name, state_engine.lastblock ):
log.warning("Name '%s' is expired" % name)
return False
# name must not be in grace period in *this* block
if state_engine.is_name_in_grace_period(name, block_id):
log.warning("Name '{}' is in the renewal grace period. It can only be renewed at this time.".format(name))
return False
# the name must be registered
if not state_engine.is_name_registered( name ):
# doesn't exist
log.warning("Name '%s' is not registered" % name )
return False
# the name must be owned by the same person who sent this nameop
if not state_engine.is_name_owner( name, sender ):
# wrong owner
log.warning("Name '%s' is not owned by '%s'" % (name, sender))
return False
# remember the name and consensus hash, so we don't have to re-calculate it...
nameop['name'] = name
nameop['consensus_hash'] = consensus_hash
nameop['sender_pubkey'] = name_rec['sender_pubkey']
# not stored, but re-calculateable
del nameop['name_consensus_hash']
return True | python | def check(state_engine, nameop, block_id, checked_ops ):
"""
Verify the validity of an update to a name's associated data.
Use the nameop's 128-bit name hash to find the name itself.
NAME_UPDATE isn't allowed during an import, so the name's namespace must be ready.
Return True if accepted
Return False if not.
"""
name_consensus_hash = nameop['name_consensus_hash']
sender = nameop['sender']
# deny updates if we exceed quota--the only legal operations are to revoke or transfer.
sender_names = state_engine.get_names_owned_by_sender( sender )
if len(sender_names) > MAX_NAMES_PER_SENDER:
log.warning("Sender '%s' has exceeded quota: only transfers or revokes are allowed" % (sender))
return False
name, consensus_hash = state_engine.get_name_from_name_consensus_hash( name_consensus_hash, sender, block_id )
# name must exist
if name is None or consensus_hash is None:
log.warning("Unable to resolve name consensus hash '%s' to a name owned by '%s'" % (name_consensus_hash, sender))
# nothing to do--write is stale or on a fork
return False
namespace_id = get_namespace_from_name( name )
name_rec = state_engine.get_name( name )
if name_rec is None:
log.warning("Name '%s' does not exist" % name)
return False
# namespace must be ready
if not state_engine.is_namespace_ready( namespace_id ):
# non-existent namespace
log.warning("Namespace '%s' is not ready" % (namespace_id))
return False
# name must not be revoked
if state_engine.is_name_revoked( name ):
log.warning("Name '%s' is revoked" % name)
return False
# name must not be expired as of the *last block processed*
if state_engine.is_name_expired( name, state_engine.lastblock ):
log.warning("Name '%s' is expired" % name)
return False
# name must not be in grace period in *this* block
if state_engine.is_name_in_grace_period(name, block_id):
log.warning("Name '{}' is in the renewal grace period. It can only be renewed at this time.".format(name))
return False
# the name must be registered
if not state_engine.is_name_registered( name ):
# doesn't exist
log.warning("Name '%s' is not registered" % name )
return False
# the name must be owned by the same person who sent this nameop
if not state_engine.is_name_owner( name, sender ):
# wrong owner
log.warning("Name '%s' is not owned by '%s'" % (name, sender))
return False
# remember the name and consensus hash, so we don't have to re-calculate it...
nameop['name'] = name
nameop['consensus_hash'] = consensus_hash
nameop['sender_pubkey'] = name_rec['sender_pubkey']
# not stored, but re-calculateable
del nameop['name_consensus_hash']
return True | [
"def",
"check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"name_consensus_hash",
"=",
"nameop",
"[",
"'name_consensus_hash'",
"]",
"sender",
"=",
"nameop",
"[",
"'sender'",
"]",
"# deny updates if we exceed quota--the only legal operations are to revoke or transfer.",
"sender_names",
"=",
"state_engine",
".",
"get_names_owned_by_sender",
"(",
"sender",
")",
"if",
"len",
"(",
"sender_names",
")",
">",
"MAX_NAMES_PER_SENDER",
":",
"log",
".",
"warning",
"(",
"\"Sender '%s' has exceeded quota: only transfers or revokes are allowed\"",
"%",
"(",
"sender",
")",
")",
"return",
"False",
"name",
",",
"consensus_hash",
"=",
"state_engine",
".",
"get_name_from_name_consensus_hash",
"(",
"name_consensus_hash",
",",
"sender",
",",
"block_id",
")",
"# name must exist",
"if",
"name",
"is",
"None",
"or",
"consensus_hash",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"Unable to resolve name consensus hash '%s' to a name owned by '%s'\"",
"%",
"(",
"name_consensus_hash",
",",
"sender",
")",
")",
"# nothing to do--write is stale or on a fork",
"return",
"False",
"namespace_id",
"=",
"get_namespace_from_name",
"(",
"name",
")",
"name_rec",
"=",
"state_engine",
".",
"get_name",
"(",
"name",
")",
"if",
"name_rec",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"Name '%s' does not exist\"",
"%",
"name",
")",
"return",
"False",
"# namespace must be ready",
"if",
"not",
"state_engine",
".",
"is_namespace_ready",
"(",
"namespace_id",
")",
":",
"# non-existent namespace",
"log",
".",
"warning",
"(",
"\"Namespace '%s' is not ready\"",
"%",
"(",
"namespace_id",
")",
")",
"return",
"False",
"# name must not be revoked",
"if",
"state_engine",
".",
"is_name_revoked",
"(",
"name",
")",
":",
"log",
".",
"warning",
"(",
"\"Name '%s' is revoked\"",
"%",
"name",
")",
"return",
"False",
"# name must not be expired as of the *last block processed*",
"if",
"state_engine",
".",
"is_name_expired",
"(",
"name",
",",
"state_engine",
".",
"lastblock",
")",
":",
"log",
".",
"warning",
"(",
"\"Name '%s' is expired\"",
"%",
"name",
")",
"return",
"False",
"# name must not be in grace period in *this* block ",
"if",
"state_engine",
".",
"is_name_in_grace_period",
"(",
"name",
",",
"block_id",
")",
":",
"log",
".",
"warning",
"(",
"\"Name '{}' is in the renewal grace period. It can only be renewed at this time.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"False",
"# the name must be registered",
"if",
"not",
"state_engine",
".",
"is_name_registered",
"(",
"name",
")",
":",
"# doesn't exist",
"log",
".",
"warning",
"(",
"\"Name '%s' is not registered\"",
"%",
"name",
")",
"return",
"False",
"# the name must be owned by the same person who sent this nameop",
"if",
"not",
"state_engine",
".",
"is_name_owner",
"(",
"name",
",",
"sender",
")",
":",
"# wrong owner",
"log",
".",
"warning",
"(",
"\"Name '%s' is not owned by '%s'\"",
"%",
"(",
"name",
",",
"sender",
")",
")",
"return",
"False",
"# remember the name and consensus hash, so we don't have to re-calculate it...",
"nameop",
"[",
"'name'",
"]",
"=",
"name",
"nameop",
"[",
"'consensus_hash'",
"]",
"=",
"consensus_hash",
"nameop",
"[",
"'sender_pubkey'",
"]",
"=",
"name_rec",
"[",
"'sender_pubkey'",
"]",
"# not stored, but re-calculateable",
"del",
"nameop",
"[",
"'name_consensus_hash'",
"]",
"return",
"True"
] | Verify the validity of an update to a name's associated data.
Use the nameop's 128-bit name hash to find the name itself.
NAME_UPDATE isn't allowed during an import, so the name's namespace must be ready.
Return True if accepted
Return False if not. | [
"Verify",
"the",
"validity",
"of",
"an",
"update",
"to",
"a",
"name",
"s",
"associated",
"data",
".",
"Use",
"the",
"nameop",
"s",
"128",
"-",
"bit",
"name",
"hash",
"to",
"find",
"the",
"name",
"itself",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/update.py#L73-L149 |
230,702 | blockstack/blockstack-core | blockstack/lib/audit.py | genesis_block_audit | def genesis_block_audit(genesis_block_stages, key_bundle=GENESIS_BLOCK_SIGNING_KEYS):
"""
Verify the authenticity of the stages of the genesis block, optionally with a given set of keys.
Return True if valid
Return False if not
"""
gpg2_path = find_gpg2()
if gpg2_path is None:
raise Exception('You must install gpg2 to audit the genesis block, and it must be in your PATH')
log.debug('Loading {} signing key(s)...'.format(len(key_bundle)))
res = load_signing_keys(gpg2_path, [key_bundle[kid] for kid in key_bundle])
if not res:
raise Exception('Failed to install signing keys')
log.debug('Verifying {} signing key(s)...'.format(len(key_bundle)))
res = check_gpg2_keys(gpg2_path, key_bundle.keys())
if not res:
raise Exception('Failed to verify installation of signing keys')
d = tempfile.mkdtemp(prefix='.genesis-block-audit-')
# each entry in genesis_block_stages is a genesis block with its own history
for stage_id, stage in enumerate(genesis_block_stages):
log.debug('Verify stage {}'.format(stage_id))
try:
jsonschema.validate(GENESIS_BLOCK_SCHEMA, stage)
except jsonschema.ValidationError:
shutil.rmtree(d)
log.error('Invalid genesis block -- does not match schema')
raise ValueError('Invalid genesis block')
# all history rows must be signed with a trusted key
for history_id, history_row in enumerate(stage['history']):
with open(os.path.join(d, 'sig'), 'w') as f:
f.write(history_row['signature'])
with open(os.path.join(d, 'hash'), 'w') as f:
f.write(history_row['hash'])
p = subprocess.Popen([gpg2_path, '--verify', os.path.join(d,'sig'), os.path.join(d,'hash')], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
log.error('Failed to verify stage {} history {}'.format(stage_id, history_id))
shutil.rmtree(d)
return False
gb_rows_str = json.dumps(stage['rows'], sort_keys=True, separators=(',',':')) + '\n'
gb_rows_hash = hashlib.sha256(gb_rows_str).hexdigest()
# must match final history row
if gb_rows_hash != stage['history'][-1]['hash']:
log.error('Genesis block stage {} hash mismatch: {} != {}'.format(stage_id, gb_rows_hash, stage['history'][-1]['hash']))
shutil.rmtree(d)
return False
shutil.rmtree(d)
log.info('Genesis block is legitimate')
return True | python | def genesis_block_audit(genesis_block_stages, key_bundle=GENESIS_BLOCK_SIGNING_KEYS):
"""
Verify the authenticity of the stages of the genesis block, optionally with a given set of keys.
Return True if valid
Return False if not
"""
gpg2_path = find_gpg2()
if gpg2_path is None:
raise Exception('You must install gpg2 to audit the genesis block, and it must be in your PATH')
log.debug('Loading {} signing key(s)...'.format(len(key_bundle)))
res = load_signing_keys(gpg2_path, [key_bundle[kid] for kid in key_bundle])
if not res:
raise Exception('Failed to install signing keys')
log.debug('Verifying {} signing key(s)...'.format(len(key_bundle)))
res = check_gpg2_keys(gpg2_path, key_bundle.keys())
if not res:
raise Exception('Failed to verify installation of signing keys')
d = tempfile.mkdtemp(prefix='.genesis-block-audit-')
# each entry in genesis_block_stages is a genesis block with its own history
for stage_id, stage in enumerate(genesis_block_stages):
log.debug('Verify stage {}'.format(stage_id))
try:
jsonschema.validate(GENESIS_BLOCK_SCHEMA, stage)
except jsonschema.ValidationError:
shutil.rmtree(d)
log.error('Invalid genesis block -- does not match schema')
raise ValueError('Invalid genesis block')
# all history rows must be signed with a trusted key
for history_id, history_row in enumerate(stage['history']):
with open(os.path.join(d, 'sig'), 'w') as f:
f.write(history_row['signature'])
with open(os.path.join(d, 'hash'), 'w') as f:
f.write(history_row['hash'])
p = subprocess.Popen([gpg2_path, '--verify', os.path.join(d,'sig'), os.path.join(d,'hash')], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
log.error('Failed to verify stage {} history {}'.format(stage_id, history_id))
shutil.rmtree(d)
return False
gb_rows_str = json.dumps(stage['rows'], sort_keys=True, separators=(',',':')) + '\n'
gb_rows_hash = hashlib.sha256(gb_rows_str).hexdigest()
# must match final history row
if gb_rows_hash != stage['history'][-1]['hash']:
log.error('Genesis block stage {} hash mismatch: {} != {}'.format(stage_id, gb_rows_hash, stage['history'][-1]['hash']))
shutil.rmtree(d)
return False
shutil.rmtree(d)
log.info('Genesis block is legitimate')
return True | [
"def",
"genesis_block_audit",
"(",
"genesis_block_stages",
",",
"key_bundle",
"=",
"GENESIS_BLOCK_SIGNING_KEYS",
")",
":",
"gpg2_path",
"=",
"find_gpg2",
"(",
")",
"if",
"gpg2_path",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'You must install gpg2 to audit the genesis block, and it must be in your PATH'",
")",
"log",
".",
"debug",
"(",
"'Loading {} signing key(s)...'",
".",
"format",
"(",
"len",
"(",
"key_bundle",
")",
")",
")",
"res",
"=",
"load_signing_keys",
"(",
"gpg2_path",
",",
"[",
"key_bundle",
"[",
"kid",
"]",
"for",
"kid",
"in",
"key_bundle",
"]",
")",
"if",
"not",
"res",
":",
"raise",
"Exception",
"(",
"'Failed to install signing keys'",
")",
"log",
".",
"debug",
"(",
"'Verifying {} signing key(s)...'",
".",
"format",
"(",
"len",
"(",
"key_bundle",
")",
")",
")",
"res",
"=",
"check_gpg2_keys",
"(",
"gpg2_path",
",",
"key_bundle",
".",
"keys",
"(",
")",
")",
"if",
"not",
"res",
":",
"raise",
"Exception",
"(",
"'Failed to verify installation of signing keys'",
")",
"d",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'.genesis-block-audit-'",
")",
"# each entry in genesis_block_stages is a genesis block with its own history ",
"for",
"stage_id",
",",
"stage",
"in",
"enumerate",
"(",
"genesis_block_stages",
")",
":",
"log",
".",
"debug",
"(",
"'Verify stage {}'",
".",
"format",
"(",
"stage_id",
")",
")",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"GENESIS_BLOCK_SCHEMA",
",",
"stage",
")",
"except",
"jsonschema",
".",
"ValidationError",
":",
"shutil",
".",
"rmtree",
"(",
"d",
")",
"log",
".",
"error",
"(",
"'Invalid genesis block -- does not match schema'",
")",
"raise",
"ValueError",
"(",
"'Invalid genesis block'",
")",
"# all history rows must be signed with a trusted key",
"for",
"history_id",
",",
"history_row",
"in",
"enumerate",
"(",
"stage",
"[",
"'history'",
"]",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'sig'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"history_row",
"[",
"'signature'",
"]",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'hash'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"history_row",
"[",
"'hash'",
"]",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"gpg2_path",
",",
"'--verify'",
",",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'sig'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'hash'",
")",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"!=",
"0",
":",
"log",
".",
"error",
"(",
"'Failed to verify stage {} history {}'",
".",
"format",
"(",
"stage_id",
",",
"history_id",
")",
")",
"shutil",
".",
"rmtree",
"(",
"d",
")",
"return",
"False",
"gb_rows_str",
"=",
"json",
".",
"dumps",
"(",
"stage",
"[",
"'rows'",
"]",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
"+",
"'\\n'",
"gb_rows_hash",
"=",
"hashlib",
".",
"sha256",
"(",
"gb_rows_str",
")",
".",
"hexdigest",
"(",
")",
"# must match final history row ",
"if",
"gb_rows_hash",
"!=",
"stage",
"[",
"'history'",
"]",
"[",
"-",
"1",
"]",
"[",
"'hash'",
"]",
":",
"log",
".",
"error",
"(",
"'Genesis block stage {} hash mismatch: {} != {}'",
".",
"format",
"(",
"stage_id",
",",
"gb_rows_hash",
",",
"stage",
"[",
"'history'",
"]",
"[",
"-",
"1",
"]",
"[",
"'hash'",
"]",
")",
")",
"shutil",
".",
"rmtree",
"(",
"d",
")",
"return",
"False",
"shutil",
".",
"rmtree",
"(",
"d",
")",
"log",
".",
"info",
"(",
"'Genesis block is legitimate'",
")",
"return",
"True"
] | Verify the authenticity of the stages of the genesis block, optionally with a given set of keys.
Return True if valid
Return False if not | [
"Verify",
"the",
"authenticity",
"of",
"the",
"stages",
"of",
"the",
"genesis",
"block",
"optionally",
"with",
"a",
"given",
"set",
"of",
"keys",
".",
"Return",
"True",
"if",
"valid",
"Return",
"False",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/audit.py#L97-L155 |
230,703 | blockstack/blockstack-core | api/resolver.py | is_profile_in_legacy_format | def is_profile_in_legacy_format(profile):
"""
Is a given profile JSON object in legacy format?
"""
if isinstance(profile, dict):
pass
elif isinstance(profile, (str, unicode)):
try:
profile = json.loads(profile)
except ValueError:
return False
else:
return False
if "@type" in profile:
return False
if "@context" in profile:
return False
is_in_legacy_format = False
if "avatar" in profile:
is_in_legacy_format = True
elif "cover" in profile:
is_in_legacy_format = True
elif "bio" in profile:
is_in_legacy_format = True
elif "twitter" in profile:
is_in_legacy_format = True
elif "facebook" in profile:
is_in_legacy_format = True
return is_in_legacy_format | python | def is_profile_in_legacy_format(profile):
"""
Is a given profile JSON object in legacy format?
"""
if isinstance(profile, dict):
pass
elif isinstance(profile, (str, unicode)):
try:
profile = json.loads(profile)
except ValueError:
return False
else:
return False
if "@type" in profile:
return False
if "@context" in profile:
return False
is_in_legacy_format = False
if "avatar" in profile:
is_in_legacy_format = True
elif "cover" in profile:
is_in_legacy_format = True
elif "bio" in profile:
is_in_legacy_format = True
elif "twitter" in profile:
is_in_legacy_format = True
elif "facebook" in profile:
is_in_legacy_format = True
return is_in_legacy_format | [
"def",
"is_profile_in_legacy_format",
"(",
"profile",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"dict",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"profile",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"try",
":",
"profile",
"=",
"json",
".",
"loads",
"(",
"profile",
")",
"except",
"ValueError",
":",
"return",
"False",
"else",
":",
"return",
"False",
"if",
"\"@type\"",
"in",
"profile",
":",
"return",
"False",
"if",
"\"@context\"",
"in",
"profile",
":",
"return",
"False",
"is_in_legacy_format",
"=",
"False",
"if",
"\"avatar\"",
"in",
"profile",
":",
"is_in_legacy_format",
"=",
"True",
"elif",
"\"cover\"",
"in",
"profile",
":",
"is_in_legacy_format",
"=",
"True",
"elif",
"\"bio\"",
"in",
"profile",
":",
"is_in_legacy_format",
"=",
"True",
"elif",
"\"twitter\"",
"in",
"profile",
":",
"is_in_legacy_format",
"=",
"True",
"elif",
"\"facebook\"",
"in",
"profile",
":",
"is_in_legacy_format",
"=",
"True",
"return",
"is_in_legacy_format"
] | Is a given profile JSON object in legacy format? | [
"Is",
"a",
"given",
"profile",
"JSON",
"object",
"in",
"legacy",
"format?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/resolver.py#L114-L147 |
230,704 | blockstack/blockstack-core | api/resolver.py | format_profile | def format_profile(profile, fqa, zone_file, address, public_key):
""" Process profile data and
1) Insert verifications
2) Check if profile data is valid JSON
"""
# if the zone file is a string, then parse it
if isinstance(zone_file, (str,unicode)):
try:
zone_file = blockstack_zones.parse_zone_file(zone_file)
except:
# leave as text
pass
data = {'profile' : profile,
'zone_file' : zone_file,
'public_key': public_key,
'owner_address' : address}
if not fqa.endswith('.id'):
data['verifications'] = ["No verifications for non-id namespaces."]
return data
profile_in_legacy_format = is_profile_in_legacy_format(profile)
if not profile_in_legacy_format:
data['verifications'] = fetch_proofs(data['profile'], fqa, address,
profile_ver=3, zonefile=zone_file)
else:
if type(profile) is not dict:
data['profile'] = json.loads(profile)
data['verifications'] = fetch_proofs(data['profile'], fqa, address)
return data | python | def format_profile(profile, fqa, zone_file, address, public_key):
""" Process profile data and
1) Insert verifications
2) Check if profile data is valid JSON
"""
# if the zone file is a string, then parse it
if isinstance(zone_file, (str,unicode)):
try:
zone_file = blockstack_zones.parse_zone_file(zone_file)
except:
# leave as text
pass
data = {'profile' : profile,
'zone_file' : zone_file,
'public_key': public_key,
'owner_address' : address}
if not fqa.endswith('.id'):
data['verifications'] = ["No verifications for non-id namespaces."]
return data
profile_in_legacy_format = is_profile_in_legacy_format(profile)
if not profile_in_legacy_format:
data['verifications'] = fetch_proofs(data['profile'], fqa, address,
profile_ver=3, zonefile=zone_file)
else:
if type(profile) is not dict:
data['profile'] = json.loads(profile)
data['verifications'] = fetch_proofs(data['profile'], fqa, address)
return data | [
"def",
"format_profile",
"(",
"profile",
",",
"fqa",
",",
"zone_file",
",",
"address",
",",
"public_key",
")",
":",
"# if the zone file is a string, then parse it ",
"if",
"isinstance",
"(",
"zone_file",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"try",
":",
"zone_file",
"=",
"blockstack_zones",
".",
"parse_zone_file",
"(",
"zone_file",
")",
"except",
":",
"# leave as text",
"pass",
"data",
"=",
"{",
"'profile'",
":",
"profile",
",",
"'zone_file'",
":",
"zone_file",
",",
"'public_key'",
":",
"public_key",
",",
"'owner_address'",
":",
"address",
"}",
"if",
"not",
"fqa",
".",
"endswith",
"(",
"'.id'",
")",
":",
"data",
"[",
"'verifications'",
"]",
"=",
"[",
"\"No verifications for non-id namespaces.\"",
"]",
"return",
"data",
"profile_in_legacy_format",
"=",
"is_profile_in_legacy_format",
"(",
"profile",
")",
"if",
"not",
"profile_in_legacy_format",
":",
"data",
"[",
"'verifications'",
"]",
"=",
"fetch_proofs",
"(",
"data",
"[",
"'profile'",
"]",
",",
"fqa",
",",
"address",
",",
"profile_ver",
"=",
"3",
",",
"zonefile",
"=",
"zone_file",
")",
"else",
":",
"if",
"type",
"(",
"profile",
")",
"is",
"not",
"dict",
":",
"data",
"[",
"'profile'",
"]",
"=",
"json",
".",
"loads",
"(",
"profile",
")",
"data",
"[",
"'verifications'",
"]",
"=",
"fetch_proofs",
"(",
"data",
"[",
"'profile'",
"]",
",",
"fqa",
",",
"address",
")",
"return",
"data"
] | Process profile data and
1) Insert verifications
2) Check if profile data is valid JSON | [
"Process",
"profile",
"data",
"and",
"1",
")",
"Insert",
"verifications",
"2",
")",
"Check",
"if",
"profile",
"data",
"is",
"valid",
"JSON"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/resolver.py#L149-L182 |
230,705 | blockstack/blockstack-core | api/resolver.py | get_users | def get_users(username):
""" Fetch data from username in .id namespace
"""
reply = {}
log.debug('Begin /v[x]/users/' + username)
if username is None:
reply['error'] = "No username given"
return jsonify(reply), 404
if ',' in username:
reply['error'] = 'Multiple username queries are no longer supported.'
return jsonify(reply), 401
if "." not in username:
fqa = "{}.{}".format(username, 'id')
else:
fqa = username
profile = get_profile(fqa)
reply[username] = profile
if 'error' in profile:
status_code = 200
if 'status_code' in profile:
status_code = profile['status_code']
del profile['status_code']
return jsonify(reply), status_code
else:
return jsonify(reply), 200 | python | def get_users(username):
""" Fetch data from username in .id namespace
"""
reply = {}
log.debug('Begin /v[x]/users/' + username)
if username is None:
reply['error'] = "No username given"
return jsonify(reply), 404
if ',' in username:
reply['error'] = 'Multiple username queries are no longer supported.'
return jsonify(reply), 401
if "." not in username:
fqa = "{}.{}".format(username, 'id')
else:
fqa = username
profile = get_profile(fqa)
reply[username] = profile
if 'error' in profile:
status_code = 200
if 'status_code' in profile:
status_code = profile['status_code']
del profile['status_code']
return jsonify(reply), status_code
else:
return jsonify(reply), 200 | [
"def",
"get_users",
"(",
"username",
")",
":",
"reply",
"=",
"{",
"}",
"log",
".",
"debug",
"(",
"'Begin /v[x]/users/'",
"+",
"username",
")",
"if",
"username",
"is",
"None",
":",
"reply",
"[",
"'error'",
"]",
"=",
"\"No username given\"",
"return",
"jsonify",
"(",
"reply",
")",
",",
"404",
"if",
"','",
"in",
"username",
":",
"reply",
"[",
"'error'",
"]",
"=",
"'Multiple username queries are no longer supported.'",
"return",
"jsonify",
"(",
"reply",
")",
",",
"401",
"if",
"\".\"",
"not",
"in",
"username",
":",
"fqa",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"username",
",",
"'id'",
")",
"else",
":",
"fqa",
"=",
"username",
"profile",
"=",
"get_profile",
"(",
"fqa",
")",
"reply",
"[",
"username",
"]",
"=",
"profile",
"if",
"'error'",
"in",
"profile",
":",
"status_code",
"=",
"200",
"if",
"'status_code'",
"in",
"profile",
":",
"status_code",
"=",
"profile",
"[",
"'status_code'",
"]",
"del",
"profile",
"[",
"'status_code'",
"]",
"return",
"jsonify",
"(",
"reply",
")",
",",
"status_code",
"else",
":",
"return",
"jsonify",
"(",
"reply",
")",
",",
"200"
] | Fetch data from username in .id namespace | [
"Fetch",
"data",
"from",
"username",
"in",
".",
"id",
"namespace"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/resolver.py#L250-L281 |
230,706 | blockstack/blockstack-core | blockstack/lib/operations/nameimport.py | is_earlier_than | def is_earlier_than( nameop1, block_id, vtxindex ):
"""
Does nameop1 come before bock_id and vtxindex?
"""
return nameop1['block_number'] < block_id or (nameop1['block_number'] == block_id and nameop1['vtxindex'] < vtxindex) | python | def is_earlier_than( nameop1, block_id, vtxindex ):
"""
Does nameop1 come before bock_id and vtxindex?
"""
return nameop1['block_number'] < block_id or (nameop1['block_number'] == block_id and nameop1['vtxindex'] < vtxindex) | [
"def",
"is_earlier_than",
"(",
"nameop1",
",",
"block_id",
",",
"vtxindex",
")",
":",
"return",
"nameop1",
"[",
"'block_number'",
"]",
"<",
"block_id",
"or",
"(",
"nameop1",
"[",
"'block_number'",
"]",
"==",
"block_id",
"and",
"nameop1",
"[",
"'vtxindex'",
"]",
"<",
"vtxindex",
")"
] | Does nameop1 come before bock_id and vtxindex? | [
"Does",
"nameop1",
"come",
"before",
"bock_id",
"and",
"vtxindex?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/nameimport.py#L107-L111 |
230,707 | blockstack/blockstack-core | blockstack/lib/operations/namespacereveal.py | namespacereveal_sanity_check | def namespacereveal_sanity_check( namespace_id, version, lifetime, coeff, base, bucket_exponents, nonalpha_discount, no_vowel_discount ):
"""
Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid.
"""
# sanity check
if not is_b40( namespace_id ) or "+" in namespace_id or namespace_id.count(".") > 0:
raise Exception("Namespace ID '%s' has non-base-38 characters" % namespace_id)
if len(namespace_id) > LENGTHS['blockchain_id_namespace_id']:
raise Exception("Invalid namespace ID length for '%s' (expected length between 1 and %s)" % (namespace_id, LENGTHS['blockchain_id_namespace_id']))
if version not in [NAMESPACE_VERSION_PAY_TO_BURN, NAMESPACE_VERSION_PAY_TO_CREATOR, NAMESPACE_VERSION_PAY_WITH_STACKS]:
raise Exception("Invalid namespace version bits {:x}".format(version))
if lifetime < 0 or lifetime > (2**32 - 1):
lifetime = NAMESPACE_LIFE_INFINITE
if coeff < 0 or coeff > 255:
raise Exception("Invalid cost multiplier %s: must be in range [0, 256)" % coeff)
if base < 0 or base > 255:
raise Exception("Invalid base price %s: must be in range [0, 256)" % base)
if type(bucket_exponents) != list:
raise Exception("Bucket exponents must be a list")
if len(bucket_exponents) != 16:
raise Exception("Exactly 16 buckets required")
for i in xrange(0, len(bucket_exponents)):
if bucket_exponents[i] < 0 or bucket_exponents[i] > 15:
raise Exception("Invalid bucket exponent %s (must be in range [0, 16)" % bucket_exponents[i])
if nonalpha_discount <= 0 or nonalpha_discount > 15:
raise Exception("Invalid non-alpha discount %s: must be in range [0, 16)" % nonalpha_discount)
if no_vowel_discount <= 0 or no_vowel_discount > 15:
raise Exception("Invalid no-vowel discount %s: must be in range [0, 16)" % no_vowel_discount)
return True | python | def namespacereveal_sanity_check( namespace_id, version, lifetime, coeff, base, bucket_exponents, nonalpha_discount, no_vowel_discount ):
"""
Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid.
"""
# sanity check
if not is_b40( namespace_id ) or "+" in namespace_id or namespace_id.count(".") > 0:
raise Exception("Namespace ID '%s' has non-base-38 characters" % namespace_id)
if len(namespace_id) > LENGTHS['blockchain_id_namespace_id']:
raise Exception("Invalid namespace ID length for '%s' (expected length between 1 and %s)" % (namespace_id, LENGTHS['blockchain_id_namespace_id']))
if version not in [NAMESPACE_VERSION_PAY_TO_BURN, NAMESPACE_VERSION_PAY_TO_CREATOR, NAMESPACE_VERSION_PAY_WITH_STACKS]:
raise Exception("Invalid namespace version bits {:x}".format(version))
if lifetime < 0 or lifetime > (2**32 - 1):
lifetime = NAMESPACE_LIFE_INFINITE
if coeff < 0 or coeff > 255:
raise Exception("Invalid cost multiplier %s: must be in range [0, 256)" % coeff)
if base < 0 or base > 255:
raise Exception("Invalid base price %s: must be in range [0, 256)" % base)
if type(bucket_exponents) != list:
raise Exception("Bucket exponents must be a list")
if len(bucket_exponents) != 16:
raise Exception("Exactly 16 buckets required")
for i in xrange(0, len(bucket_exponents)):
if bucket_exponents[i] < 0 or bucket_exponents[i] > 15:
raise Exception("Invalid bucket exponent %s (must be in range [0, 16)" % bucket_exponents[i])
if nonalpha_discount <= 0 or nonalpha_discount > 15:
raise Exception("Invalid non-alpha discount %s: must be in range [0, 16)" % nonalpha_discount)
if no_vowel_discount <= 0 or no_vowel_discount > 15:
raise Exception("Invalid no-vowel discount %s: must be in range [0, 16)" % no_vowel_discount)
return True | [
"def",
"namespacereveal_sanity_check",
"(",
"namespace_id",
",",
"version",
",",
"lifetime",
",",
"coeff",
",",
"base",
",",
"bucket_exponents",
",",
"nonalpha_discount",
",",
"no_vowel_discount",
")",
":",
"# sanity check ",
"if",
"not",
"is_b40",
"(",
"namespace_id",
")",
"or",
"\"+\"",
"in",
"namespace_id",
"or",
"namespace_id",
".",
"count",
"(",
"\".\"",
")",
">",
"0",
":",
"raise",
"Exception",
"(",
"\"Namespace ID '%s' has non-base-38 characters\"",
"%",
"namespace_id",
")",
"if",
"len",
"(",
"namespace_id",
")",
">",
"LENGTHS",
"[",
"'blockchain_id_namespace_id'",
"]",
":",
"raise",
"Exception",
"(",
"\"Invalid namespace ID length for '%s' (expected length between 1 and %s)\"",
"%",
"(",
"namespace_id",
",",
"LENGTHS",
"[",
"'blockchain_id_namespace_id'",
"]",
")",
")",
"if",
"version",
"not",
"in",
"[",
"NAMESPACE_VERSION_PAY_TO_BURN",
",",
"NAMESPACE_VERSION_PAY_TO_CREATOR",
",",
"NAMESPACE_VERSION_PAY_WITH_STACKS",
"]",
":",
"raise",
"Exception",
"(",
"\"Invalid namespace version bits {:x}\"",
".",
"format",
"(",
"version",
")",
")",
"if",
"lifetime",
"<",
"0",
"or",
"lifetime",
">",
"(",
"2",
"**",
"32",
"-",
"1",
")",
":",
"lifetime",
"=",
"NAMESPACE_LIFE_INFINITE",
"if",
"coeff",
"<",
"0",
"or",
"coeff",
">",
"255",
":",
"raise",
"Exception",
"(",
"\"Invalid cost multiplier %s: must be in range [0, 256)\"",
"%",
"coeff",
")",
"if",
"base",
"<",
"0",
"or",
"base",
">",
"255",
":",
"raise",
"Exception",
"(",
"\"Invalid base price %s: must be in range [0, 256)\"",
"%",
"base",
")",
"if",
"type",
"(",
"bucket_exponents",
")",
"!=",
"list",
":",
"raise",
"Exception",
"(",
"\"Bucket exponents must be a list\"",
")",
"if",
"len",
"(",
"bucket_exponents",
")",
"!=",
"16",
":",
"raise",
"Exception",
"(",
"\"Exactly 16 buckets required\"",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"bucket_exponents",
")",
")",
":",
"if",
"bucket_exponents",
"[",
"i",
"]",
"<",
"0",
"or",
"bucket_exponents",
"[",
"i",
"]",
">",
"15",
":",
"raise",
"Exception",
"(",
"\"Invalid bucket exponent %s (must be in range [0, 16)\"",
"%",
"bucket_exponents",
"[",
"i",
"]",
")",
"if",
"nonalpha_discount",
"<=",
"0",
"or",
"nonalpha_discount",
">",
"15",
":",
"raise",
"Exception",
"(",
"\"Invalid non-alpha discount %s: must be in range [0, 16)\"",
"%",
"nonalpha_discount",
")",
"if",
"no_vowel_discount",
"<=",
"0",
"or",
"no_vowel_discount",
">",
"15",
":",
"raise",
"Exception",
"(",
"\"Invalid no-vowel discount %s: must be in range [0, 16)\"",
"%",
"no_vowel_discount",
")",
"return",
"True"
] | Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid. | [
"Verify",
"the",
"validity",
"of",
"a",
"namespace",
"reveal",
".",
"Return",
"True",
"if",
"valid",
"Raise",
"an",
"Exception",
"if",
"not",
"valid",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/namespacereveal.py#L66-L107 |
230,708 | blockstack/blockstack-core | blockstack/lib/operations/preorder.py | check | def check( state_engine, nameop, block_id, checked_ops ):
"""
Verify that a preorder of a name at a particular block number is well-formed
NOTE: these *can't* be incorporated into namespace-imports,
since we have no way of knowning which namespace the
nameop belongs to (it is blinded until registration).
But that's okay--we don't need to preorder names during
a namespace import, because we will only accept names
sent from the importer until the NAMESPACE_REVEAL operation
is sent.
Return True if accepted
Return False if not.
"""
from .register import get_num_names_owned
preorder_name_hash = nameop['preorder_hash']
consensus_hash = nameop['consensus_hash']
sender = nameop['sender']
token_fee = nameop['token_fee']
token_type = nameop['token_units']
token_address = nameop['address']
# must be unique in this block
# NOTE: now checked externally in the @state_preorder decorator
# must be unique across all pending preorders
if not state_engine.is_new_preorder( preorder_name_hash ):
log.warning("Name hash '%s' is already preordered" % preorder_name_hash )
return False
# must have a valid consensus hash
if not state_engine.is_consensus_hash_valid( block_id, consensus_hash ):
log.warning("Invalid consensus hash '%s'" % consensus_hash )
return False
# sender must be beneath quota
num_names = get_num_names_owned( state_engine, checked_ops, sender )
if num_names >= MAX_NAMES_PER_SENDER:
log.warning("Sender '%s' exceeded name quota of %s" % (sender, MAX_NAMES_PER_SENDER ))
return False
# burn fee must be present
if not 'op_fee' in nameop:
log.warning("Missing preorder fee")
return False
epoch_features = get_epoch_features(block_id)
if EPOCH_FEATURE_NAMEOPS_COST_TOKENS in epoch_features and token_type is not None and token_fee is not None:
# does this account have enough balance?
account_info = state_engine.get_account(token_address, token_type)
if account_info is None:
log.warning("No account for {} ({})".format(token_address, token_type))
return False
account_balance = state_engine.get_account_balance(account_info)
assert isinstance(account_balance, (int,long)), 'BUG: account_balance of {} is {} (type {})'.format(token_address, account_balance, type(account_balance))
assert isinstance(token_fee, (int,long)), 'BUG: token_fee is {} (type {})'.format(token_fee, type(token_fee))
if account_balance < token_fee:
# can't afford
log.warning("Account {} has balance {} {}, but needs to pay {} {}".format(token_address, account_balance, token_type, token_fee, token_type))
return False
# must be the black hole address, regardless of namespace version (since we don't yet support pay-stacks-to-namespace-creator)
if nameop['burn_address'] != BLOCKSTACK_BURN_ADDRESS:
# not sent to the right address
log.warning('Preorder burned to {}, but expected {}'.format(nameop['burn_address'], BLOCKSTACK_BURN_ADDRESS))
return False
# for now, this must be Stacks
if nameop['token_units'] != TOKEN_TYPE_STACKS:
# can't use any other token (yet)
log.warning('Preorder burned unrecognized token unit "{}"'.format(nameop['token_units']))
return False
# debit this account when we commit
state_preorder_put_account_payment_info(nameop, token_address, token_type, token_fee)
# NOTE: must be a string, to avoid overflow
nameop['token_fee'] = '{}'.format(token_fee)
else:
# not paying in tokens, but say so!
state_preorder_put_account_payment_info(nameop, None, None, None)
nameop['token_fee'] = '0'
nameop['token_units'] = 'BTC'
return True | python | def check( state_engine, nameop, block_id, checked_ops ):
"""
Verify that a preorder of a name at a particular block number is well-formed
NOTE: these *can't* be incorporated into namespace-imports,
since we have no way of knowning which namespace the
nameop belongs to (it is blinded until registration).
But that's okay--we don't need to preorder names during
a namespace import, because we will only accept names
sent from the importer until the NAMESPACE_REVEAL operation
is sent.
Return True if accepted
Return False if not.
"""
from .register import get_num_names_owned
preorder_name_hash = nameop['preorder_hash']
consensus_hash = nameop['consensus_hash']
sender = nameop['sender']
token_fee = nameop['token_fee']
token_type = nameop['token_units']
token_address = nameop['address']
# must be unique in this block
# NOTE: now checked externally in the @state_preorder decorator
# must be unique across all pending preorders
if not state_engine.is_new_preorder( preorder_name_hash ):
log.warning("Name hash '%s' is already preordered" % preorder_name_hash )
return False
# must have a valid consensus hash
if not state_engine.is_consensus_hash_valid( block_id, consensus_hash ):
log.warning("Invalid consensus hash '%s'" % consensus_hash )
return False
# sender must be beneath quota
num_names = get_num_names_owned( state_engine, checked_ops, sender )
if num_names >= MAX_NAMES_PER_SENDER:
log.warning("Sender '%s' exceeded name quota of %s" % (sender, MAX_NAMES_PER_SENDER ))
return False
# burn fee must be present
if not 'op_fee' in nameop:
log.warning("Missing preorder fee")
return False
epoch_features = get_epoch_features(block_id)
if EPOCH_FEATURE_NAMEOPS_COST_TOKENS in epoch_features and token_type is not None and token_fee is not None:
# does this account have enough balance?
account_info = state_engine.get_account(token_address, token_type)
if account_info is None:
log.warning("No account for {} ({})".format(token_address, token_type))
return False
account_balance = state_engine.get_account_balance(account_info)
assert isinstance(account_balance, (int,long)), 'BUG: account_balance of {} is {} (type {})'.format(token_address, account_balance, type(account_balance))
assert isinstance(token_fee, (int,long)), 'BUG: token_fee is {} (type {})'.format(token_fee, type(token_fee))
if account_balance < token_fee:
# can't afford
log.warning("Account {} has balance {} {}, but needs to pay {} {}".format(token_address, account_balance, token_type, token_fee, token_type))
return False
# must be the black hole address, regardless of namespace version (since we don't yet support pay-stacks-to-namespace-creator)
if nameop['burn_address'] != BLOCKSTACK_BURN_ADDRESS:
# not sent to the right address
log.warning('Preorder burned to {}, but expected {}'.format(nameop['burn_address'], BLOCKSTACK_BURN_ADDRESS))
return False
# for now, this must be Stacks
if nameop['token_units'] != TOKEN_TYPE_STACKS:
# can't use any other token (yet)
log.warning('Preorder burned unrecognized token unit "{}"'.format(nameop['token_units']))
return False
# debit this account when we commit
state_preorder_put_account_payment_info(nameop, token_address, token_type, token_fee)
# NOTE: must be a string, to avoid overflow
nameop['token_fee'] = '{}'.format(token_fee)
else:
# not paying in tokens, but say so!
state_preorder_put_account_payment_info(nameop, None, None, None)
nameop['token_fee'] = '0'
nameop['token_units'] = 'BTC'
return True | [
"def",
"check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"from",
".",
"register",
"import",
"get_num_names_owned",
"preorder_name_hash",
"=",
"nameop",
"[",
"'preorder_hash'",
"]",
"consensus_hash",
"=",
"nameop",
"[",
"'consensus_hash'",
"]",
"sender",
"=",
"nameop",
"[",
"'sender'",
"]",
"token_fee",
"=",
"nameop",
"[",
"'token_fee'",
"]",
"token_type",
"=",
"nameop",
"[",
"'token_units'",
"]",
"token_address",
"=",
"nameop",
"[",
"'address'",
"]",
"# must be unique in this block",
"# NOTE: now checked externally in the @state_preorder decorator",
"# must be unique across all pending preorders",
"if",
"not",
"state_engine",
".",
"is_new_preorder",
"(",
"preorder_name_hash",
")",
":",
"log",
".",
"warning",
"(",
"\"Name hash '%s' is already preordered\"",
"%",
"preorder_name_hash",
")",
"return",
"False",
"# must have a valid consensus hash",
"if",
"not",
"state_engine",
".",
"is_consensus_hash_valid",
"(",
"block_id",
",",
"consensus_hash",
")",
":",
"log",
".",
"warning",
"(",
"\"Invalid consensus hash '%s'\"",
"%",
"consensus_hash",
")",
"return",
"False",
"# sender must be beneath quota",
"num_names",
"=",
"get_num_names_owned",
"(",
"state_engine",
",",
"checked_ops",
",",
"sender",
")",
"if",
"num_names",
">=",
"MAX_NAMES_PER_SENDER",
":",
"log",
".",
"warning",
"(",
"\"Sender '%s' exceeded name quota of %s\"",
"%",
"(",
"sender",
",",
"MAX_NAMES_PER_SENDER",
")",
")",
"return",
"False",
"# burn fee must be present",
"if",
"not",
"'op_fee'",
"in",
"nameop",
":",
"log",
".",
"warning",
"(",
"\"Missing preorder fee\"",
")",
"return",
"False",
"epoch_features",
"=",
"get_epoch_features",
"(",
"block_id",
")",
"if",
"EPOCH_FEATURE_NAMEOPS_COST_TOKENS",
"in",
"epoch_features",
"and",
"token_type",
"is",
"not",
"None",
"and",
"token_fee",
"is",
"not",
"None",
":",
"# does this account have enough balance?",
"account_info",
"=",
"state_engine",
".",
"get_account",
"(",
"token_address",
",",
"token_type",
")",
"if",
"account_info",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"No account for {} ({})\"",
".",
"format",
"(",
"token_address",
",",
"token_type",
")",
")",
"return",
"False",
"account_balance",
"=",
"state_engine",
".",
"get_account_balance",
"(",
"account_info",
")",
"assert",
"isinstance",
"(",
"account_balance",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'BUG: account_balance of {} is {} (type {})'",
".",
"format",
"(",
"token_address",
",",
"account_balance",
",",
"type",
"(",
"account_balance",
")",
")",
"assert",
"isinstance",
"(",
"token_fee",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'BUG: token_fee is {} (type {})'",
".",
"format",
"(",
"token_fee",
",",
"type",
"(",
"token_fee",
")",
")",
"if",
"account_balance",
"<",
"token_fee",
":",
"# can't afford ",
"log",
".",
"warning",
"(",
"\"Account {} has balance {} {}, but needs to pay {} {}\"",
".",
"format",
"(",
"token_address",
",",
"account_balance",
",",
"token_type",
",",
"token_fee",
",",
"token_type",
")",
")",
"return",
"False",
"# must be the black hole address, regardless of namespace version (since we don't yet support pay-stacks-to-namespace-creator)",
"if",
"nameop",
"[",
"'burn_address'",
"]",
"!=",
"BLOCKSTACK_BURN_ADDRESS",
":",
"# not sent to the right address",
"log",
".",
"warning",
"(",
"'Preorder burned to {}, but expected {}'",
".",
"format",
"(",
"nameop",
"[",
"'burn_address'",
"]",
",",
"BLOCKSTACK_BURN_ADDRESS",
")",
")",
"return",
"False",
"# for now, this must be Stacks",
"if",
"nameop",
"[",
"'token_units'",
"]",
"!=",
"TOKEN_TYPE_STACKS",
":",
"# can't use any other token (yet)",
"log",
".",
"warning",
"(",
"'Preorder burned unrecognized token unit \"{}\"'",
".",
"format",
"(",
"nameop",
"[",
"'token_units'",
"]",
")",
")",
"return",
"False",
"# debit this account when we commit",
"state_preorder_put_account_payment_info",
"(",
"nameop",
",",
"token_address",
",",
"token_type",
",",
"token_fee",
")",
"# NOTE: must be a string, to avoid overflow",
"nameop",
"[",
"'token_fee'",
"]",
"=",
"'{}'",
".",
"format",
"(",
"token_fee",
")",
"else",
":",
"# not paying in tokens, but say so!",
"state_preorder_put_account_payment_info",
"(",
"nameop",
",",
"None",
",",
"None",
",",
"None",
")",
"nameop",
"[",
"'token_fee'",
"]",
"=",
"'0'",
"nameop",
"[",
"'token_units'",
"]",
"=",
"'BTC'",
"return",
"True"
] | Verify that a preorder of a name at a particular block number is well-formed
NOTE: these *can't* be incorporated into namespace-imports,
since we have no way of knowning which namespace the
nameop belongs to (it is blinded until registration).
But that's okay--we don't need to preorder names during
a namespace import, because we will only accept names
sent from the importer until the NAMESPACE_REVEAL operation
is sent.
Return True if accepted
Return False if not. | [
"Verify",
"that",
"a",
"preorder",
"of",
"a",
"name",
"at",
"a",
"particular",
"block",
"number",
"is",
"well",
"-",
"formed"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/preorder.py#L53-L145 |
230,709 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_create | def namedb_create(path, genesis_block):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
"""
global BLOCKSTACK_DB_SCRIPT
if os.path.exists( path ):
raise Exception("Database '%s' already exists" % path)
lines = [l + ";" for l in BLOCKSTACK_DB_SCRIPT.split(";")]
con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
for line in lines:
db_query_execute(con, line, ())
con.row_factory = namedb_row_factory
# create genesis block
namedb_create_token_genesis(con, genesis_block['rows'], genesis_block['history'])
return con | python | def namedb_create(path, genesis_block):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
"""
global BLOCKSTACK_DB_SCRIPT
if os.path.exists( path ):
raise Exception("Database '%s' already exists" % path)
lines = [l + ";" for l in BLOCKSTACK_DB_SCRIPT.split(";")]
con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
for line in lines:
db_query_execute(con, line, ())
con.row_factory = namedb_row_factory
# create genesis block
namedb_create_token_genesis(con, genesis_block['rows'], genesis_block['history'])
return con | [
"def",
"namedb_create",
"(",
"path",
",",
"genesis_block",
")",
":",
"global",
"BLOCKSTACK_DB_SCRIPT",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"Exception",
"(",
"\"Database '%s' already exists\"",
"%",
"path",
")",
"lines",
"=",
"[",
"l",
"+",
"\";\"",
"for",
"l",
"in",
"BLOCKSTACK_DB_SCRIPT",
".",
"split",
"(",
"\";\"",
")",
"]",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
",",
"timeout",
"=",
"2",
"**",
"30",
")",
"for",
"line",
"in",
"lines",
":",
"db_query_execute",
"(",
"con",
",",
"line",
",",
"(",
")",
")",
"con",
".",
"row_factory",
"=",
"namedb_row_factory",
"# create genesis block",
"namedb_create_token_genesis",
"(",
"con",
",",
"genesis_block",
"[",
"'rows'",
"]",
",",
"genesis_block",
"[",
"'history'",
"]",
")",
"return",
"con"
] | Create a sqlite3 db at the given path.
Create all the tables and indexes we need. | [
"Create",
"a",
"sqlite3",
"db",
"at",
"the",
"given",
"path",
".",
"Create",
"all",
"the",
"tables",
"and",
"indexes",
"we",
"need",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L412-L433 |
230,710 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_open | def namedb_open( path ):
"""
Open a connection to our database
"""
con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
db_query_execute(con, 'pragma mmap_size=536870912', ())
con.row_factory = namedb_row_factory
version = namedb_get_version(con)
if not semver_equal(version, VERSION):
# wrong version
raise Exception('Database has version {}, but this node is version {}. Please update your node database (such as with fast_sync).'.format(version, VERSION))
return con | python | def namedb_open( path ):
"""
Open a connection to our database
"""
con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
db_query_execute(con, 'pragma mmap_size=536870912', ())
con.row_factory = namedb_row_factory
version = namedb_get_version(con)
if not semver_equal(version, VERSION):
# wrong version
raise Exception('Database has version {}, but this node is version {}. Please update your node database (such as with fast_sync).'.format(version, VERSION))
return con | [
"def",
"namedb_open",
"(",
"path",
")",
":",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
",",
"timeout",
"=",
"2",
"**",
"30",
")",
"db_query_execute",
"(",
"con",
",",
"'pragma mmap_size=536870912'",
",",
"(",
")",
")",
"con",
".",
"row_factory",
"=",
"namedb_row_factory",
"version",
"=",
"namedb_get_version",
"(",
"con",
")",
"if",
"not",
"semver_equal",
"(",
"version",
",",
"VERSION",
")",
":",
"# wrong version",
"raise",
"Exception",
"(",
"'Database has version {}, but this node is version {}. Please update your node database (such as with fast_sync).'",
".",
"format",
"(",
"version",
",",
"VERSION",
")",
")",
"return",
"con"
] | Open a connection to our database | [
"Open",
"a",
"connection",
"to",
"our",
"database"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L436-L449 |
230,711 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_insert_prepare | def namedb_insert_prepare( cur, record, table_name ):
"""
Prepare to insert a record, but make sure
that all of the column names have values first!
Return an INSERT INTO statement on success.
Raise an exception if not.
"""
namedb_assert_fields_match( cur, record, table_name )
columns = record.keys()
columns.sort()
values = []
for c in columns:
if record[c] == False:
values.append(0)
elif record[c] == True:
values.append(1)
else:
values.append(record[c])
values = tuple(values)
field_placeholders = ",".join( ["?"] * len(columns) )
query = "INSERT INTO %s (%s) VALUES (%s);" % (table_name, ",".join(columns), field_placeholders)
log.debug(namedb_format_query(query, values))
return (query, values) | python | def namedb_insert_prepare( cur, record, table_name ):
"""
Prepare to insert a record, but make sure
that all of the column names have values first!
Return an INSERT INTO statement on success.
Raise an exception if not.
"""
namedb_assert_fields_match( cur, record, table_name )
columns = record.keys()
columns.sort()
values = []
for c in columns:
if record[c] == False:
values.append(0)
elif record[c] == True:
values.append(1)
else:
values.append(record[c])
values = tuple(values)
field_placeholders = ",".join( ["?"] * len(columns) )
query = "INSERT INTO %s (%s) VALUES (%s);" % (table_name, ",".join(columns), field_placeholders)
log.debug(namedb_format_query(query, values))
return (query, values) | [
"def",
"namedb_insert_prepare",
"(",
"cur",
",",
"record",
",",
"table_name",
")",
":",
"namedb_assert_fields_match",
"(",
"cur",
",",
"record",
",",
"table_name",
")",
"columns",
"=",
"record",
".",
"keys",
"(",
")",
"columns",
".",
"sort",
"(",
")",
"values",
"=",
"[",
"]",
"for",
"c",
"in",
"columns",
":",
"if",
"record",
"[",
"c",
"]",
"==",
"False",
":",
"values",
".",
"append",
"(",
"0",
")",
"elif",
"record",
"[",
"c",
"]",
"==",
"True",
":",
"values",
".",
"append",
"(",
"1",
")",
"else",
":",
"values",
".",
"append",
"(",
"record",
"[",
"c",
"]",
")",
"values",
"=",
"tuple",
"(",
"values",
")",
"field_placeholders",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"?\"",
"]",
"*",
"len",
"(",
"columns",
")",
")",
"query",
"=",
"\"INSERT INTO %s (%s) VALUES (%s);\"",
"%",
"(",
"table_name",
",",
"\",\"",
".",
"join",
"(",
"columns",
")",
",",
"field_placeholders",
")",
"log",
".",
"debug",
"(",
"namedb_format_query",
"(",
"query",
",",
"values",
")",
")",
"return",
"(",
"query",
",",
"values",
")"
] | Prepare to insert a record, but make sure
that all of the column names have values first!
Return an INSERT INTO statement on success.
Raise an exception if not. | [
"Prepare",
"to",
"insert",
"a",
"record",
"but",
"make",
"sure",
"that",
"all",
"of",
"the",
"column",
"names",
"have",
"values",
"first!"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L530-L560 |
230,712 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_update_must_equal | def namedb_update_must_equal( rec, change_fields ):
"""
Generate the set of fields that must stay the same across an update.
"""
must_equal = []
if len(change_fields) != 0:
given = rec.keys()
for k in given:
if k not in change_fields:
must_equal.append(k)
return must_equal | python | def namedb_update_must_equal( rec, change_fields ):
"""
Generate the set of fields that must stay the same across an update.
"""
must_equal = []
if len(change_fields) != 0:
given = rec.keys()
for k in given:
if k not in change_fields:
must_equal.append(k)
return must_equal | [
"def",
"namedb_update_must_equal",
"(",
"rec",
",",
"change_fields",
")",
":",
"must_equal",
"=",
"[",
"]",
"if",
"len",
"(",
"change_fields",
")",
"!=",
"0",
":",
"given",
"=",
"rec",
".",
"keys",
"(",
")",
"for",
"k",
"in",
"given",
":",
"if",
"k",
"not",
"in",
"change_fields",
":",
"must_equal",
".",
"append",
"(",
"k",
")",
"return",
"must_equal"
] | Generate the set of fields that must stay the same across an update. | [
"Generate",
"the",
"set",
"of",
"fields",
"that",
"must",
"stay",
"the",
"same",
"across",
"an",
"update",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L659-L671 |
230,713 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_delete_prepare | def namedb_delete_prepare( cur, primary_key, primary_key_value, table_name ):
"""
Prepare to delete a record, but make sure the fields in record
correspond to actual columns.
Return a DELETE FROM ... WHERE statement on success.
Raise an Exception if not.
DO NOT CALL THIS METHOD DIRETLY
"""
# primary key corresponds to a real column
namedb_assert_fields_match( cur, {primary_key: primary_key_value}, table_name, columns_match_record=False )
query = "DELETE FROM %s WHERE %s = ?;" % (table_name, primary_key)
values = (primary_key_value,)
return (query, values) | python | def namedb_delete_prepare( cur, primary_key, primary_key_value, table_name ):
"""
Prepare to delete a record, but make sure the fields in record
correspond to actual columns.
Return a DELETE FROM ... WHERE statement on success.
Raise an Exception if not.
DO NOT CALL THIS METHOD DIRETLY
"""
# primary key corresponds to a real column
namedb_assert_fields_match( cur, {primary_key: primary_key_value}, table_name, columns_match_record=False )
query = "DELETE FROM %s WHERE %s = ?;" % (table_name, primary_key)
values = (primary_key_value,)
return (query, values) | [
"def",
"namedb_delete_prepare",
"(",
"cur",
",",
"primary_key",
",",
"primary_key_value",
",",
"table_name",
")",
":",
"# primary key corresponds to a real column ",
"namedb_assert_fields_match",
"(",
"cur",
",",
"{",
"primary_key",
":",
"primary_key_value",
"}",
",",
"table_name",
",",
"columns_match_record",
"=",
"False",
")",
"query",
"=",
"\"DELETE FROM %s WHERE %s = ?;\"",
"%",
"(",
"table_name",
",",
"primary_key",
")",
"values",
"=",
"(",
"primary_key_value",
",",
")",
"return",
"(",
"query",
",",
"values",
")"
] | Prepare to delete a record, but make sure the fields in record
correspond to actual columns.
Return a DELETE FROM ... WHERE statement on success.
Raise an Exception if not.
DO NOT CALL THIS METHOD DIRETLY | [
"Prepare",
"to",
"delete",
"a",
"record",
"but",
"make",
"sure",
"the",
"fields",
"in",
"record",
"correspond",
"to",
"actual",
"columns",
".",
"Return",
"a",
"DELETE",
"FROM",
"...",
"WHERE",
"statement",
"on",
"success",
".",
"Raise",
"an",
"Exception",
"if",
"not",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L674-L689 |
230,714 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_query_execute | def namedb_query_execute( cur, query, values, abort=True):
"""
Execute a query. If it fails, abort. Retry with timeouts on lock
DO NOT CALL THIS DIRECTLY.
"""
return db_query_execute(cur, query, values, abort=abort) | python | def namedb_query_execute( cur, query, values, abort=True):
"""
Execute a query. If it fails, abort. Retry with timeouts on lock
DO NOT CALL THIS DIRECTLY.
"""
return db_query_execute(cur, query, values, abort=abort) | [
"def",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
",",
"abort",
"=",
"True",
")",
":",
"return",
"db_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
",",
"abort",
"=",
"abort",
")"
] | Execute a query. If it fails, abort. Retry with timeouts on lock
DO NOT CALL THIS DIRECTLY. | [
"Execute",
"a",
"query",
".",
"If",
"it",
"fails",
"abort",
".",
"Retry",
"with",
"timeouts",
"on",
"lock"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L700-L706 |
230,715 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_preorder_insert | def namedb_preorder_insert( cur, preorder_rec ):
"""
Add a name or namespace preorder record, if it doesn't exist already.
DO NOT CALL THIS DIRECTLY.
"""
preorder_row = copy.deepcopy( preorder_rec )
assert 'preorder_hash' in preorder_row, "BUG: missing preorder_hash"
try:
preorder_query, preorder_values = namedb_insert_prepare( cur, preorder_row, "preorders" )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to insert name preorder '%s'" % preorder_row['preorder_hash'])
os.abort()
namedb_query_execute( cur, preorder_query, preorder_values )
return True | python | def namedb_preorder_insert( cur, preorder_rec ):
"""
Add a name or namespace preorder record, if it doesn't exist already.
DO NOT CALL THIS DIRECTLY.
"""
preorder_row = copy.deepcopy( preorder_rec )
assert 'preorder_hash' in preorder_row, "BUG: missing preorder_hash"
try:
preorder_query, preorder_values = namedb_insert_prepare( cur, preorder_row, "preorders" )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to insert name preorder '%s'" % preorder_row['preorder_hash'])
os.abort()
namedb_query_execute( cur, preorder_query, preorder_values )
return True | [
"def",
"namedb_preorder_insert",
"(",
"cur",
",",
"preorder_rec",
")",
":",
"preorder_row",
"=",
"copy",
".",
"deepcopy",
"(",
"preorder_rec",
")",
"assert",
"'preorder_hash'",
"in",
"preorder_row",
",",
"\"BUG: missing preorder_hash\"",
"try",
":",
"preorder_query",
",",
"preorder_values",
"=",
"namedb_insert_prepare",
"(",
"cur",
",",
"preorder_row",
",",
"\"preorders\"",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: Failed to insert name preorder '%s'\"",
"%",
"preorder_row",
"[",
"'preorder_hash'",
"]",
")",
"os",
".",
"abort",
"(",
")",
"namedb_query_execute",
"(",
"cur",
",",
"preorder_query",
",",
"preorder_values",
")",
"return",
"True"
] | Add a name or namespace preorder record, if it doesn't exist already.
DO NOT CALL THIS DIRECTLY. | [
"Add",
"a",
"name",
"or",
"namespace",
"preorder",
"record",
"if",
"it",
"doesn",
"t",
"exist",
"already",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L709-L728 |
230,716 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_preorder_remove | def namedb_preorder_remove( cur, preorder_hash ):
"""
Remove a preorder hash.
DO NOT CALL THIS DIRECTLY.
"""
try:
query, values = namedb_delete_prepare( cur, 'preorder_hash', preorder_hash, 'preorders' )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to delete preorder with hash '%s'" % preorder_hash )
os.abort()
log.debug(namedb_format_query(query, values))
namedb_query_execute( cur, query, values )
return True | python | def namedb_preorder_remove( cur, preorder_hash ):
"""
Remove a preorder hash.
DO NOT CALL THIS DIRECTLY.
"""
try:
query, values = namedb_delete_prepare( cur, 'preorder_hash', preorder_hash, 'preorders' )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to delete preorder with hash '%s'" % preorder_hash )
os.abort()
log.debug(namedb_format_query(query, values))
namedb_query_execute( cur, query, values )
return True | [
"def",
"namedb_preorder_remove",
"(",
"cur",
",",
"preorder_hash",
")",
":",
"try",
":",
"query",
",",
"values",
"=",
"namedb_delete_prepare",
"(",
"cur",
",",
"'preorder_hash'",
",",
"preorder_hash",
",",
"'preorders'",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: Failed to delete preorder with hash '%s'\"",
"%",
"preorder_hash",
")",
"os",
".",
"abort",
"(",
")",
"log",
".",
"debug",
"(",
"namedb_format_query",
"(",
"query",
",",
"values",
")",
")",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
")",
"return",
"True"
] | Remove a preorder hash.
DO NOT CALL THIS DIRECTLY. | [
"Remove",
"a",
"preorder",
"hash",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L731-L746 |
230,717 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_name_insert | def namedb_name_insert( cur, input_name_rec ):
"""
Add the given name record to the database,
if it doesn't exist already.
"""
name_rec = copy.deepcopy( input_name_rec )
namedb_name_fields_check( name_rec )
try:
query, values = namedb_insert_prepare( cur, name_rec, "name_records" )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to insert name '%s'" % name_rec['name'])
os.abort()
namedb_query_execute( cur, query, values )
return True | python | def namedb_name_insert( cur, input_name_rec ):
"""
Add the given name record to the database,
if it doesn't exist already.
"""
name_rec = copy.deepcopy( input_name_rec )
namedb_name_fields_check( name_rec )
try:
query, values = namedb_insert_prepare( cur, name_rec, "name_records" )
except Exception, e:
log.exception(e)
log.error("FATAL: Failed to insert name '%s'" % name_rec['name'])
os.abort()
namedb_query_execute( cur, query, values )
return True | [
"def",
"namedb_name_insert",
"(",
"cur",
",",
"input_name_rec",
")",
":",
"name_rec",
"=",
"copy",
".",
"deepcopy",
"(",
"input_name_rec",
")",
"namedb_name_fields_check",
"(",
"name_rec",
")",
"try",
":",
"query",
",",
"values",
"=",
"namedb_insert_prepare",
"(",
"cur",
",",
"name_rec",
",",
"\"name_records\"",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: Failed to insert name '%s'\"",
"%",
"name_rec",
"[",
"'name'",
"]",
")",
"os",
".",
"abort",
"(",
")",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
")",
"return",
"True"
] | Add the given name record to the database,
if it doesn't exist already. | [
"Add",
"the",
"given",
"name",
"record",
"to",
"the",
"database",
"if",
"it",
"doesn",
"t",
"exist",
"already",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L775-L793 |
230,718 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_name_update | def namedb_name_update( cur, opcode, input_opdata, only_if={}, constraints_ignored=[] ):
"""
Update an existing name in the database.
If non-empty, only update the given fields.
DO NOT CALL THIS METHOD DIRECTLY.
"""
opdata = copy.deepcopy( input_opdata )
namedb_name_fields_check( opdata )
mutate_fields = op_get_mutate_fields( opcode )
if opcode not in OPCODE_CREATION_OPS:
assert 'name' not in mutate_fields, "BUG: 'name' listed as a mutate field for '%s'" % (opcode)
# reduce opdata down to the given fields....
must_equal = namedb_update_must_equal( opdata, mutate_fields )
must_equal += ['name','block_number']
for ignored in constraints_ignored:
if ignored in must_equal:
# ignore this constraint
must_equal.remove( ignored )
try:
query, values = namedb_update_prepare( cur, ['name', 'block_number'], opdata, "name_records", must_equal=must_equal, only_if=only_if )
except Exception, e:
log.exception(e)
log.error("FATAL: failed to update name '%s'" % opdata['name'])
os.abort()
namedb_query_execute( cur, query, values )
try:
assert cur.rowcount == 1, "Updated %s row(s)" % cur.rowcount
except Exception, e:
log.exception(e)
log.error("FATAL: failed to update name '%s'" % opdata['name'])
log.error("Query: %s", "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] ))
os.abort()
return True | python | def namedb_name_update( cur, opcode, input_opdata, only_if={}, constraints_ignored=[] ):
"""
Update an existing name in the database.
If non-empty, only update the given fields.
DO NOT CALL THIS METHOD DIRECTLY.
"""
opdata = copy.deepcopy( input_opdata )
namedb_name_fields_check( opdata )
mutate_fields = op_get_mutate_fields( opcode )
if opcode not in OPCODE_CREATION_OPS:
assert 'name' not in mutate_fields, "BUG: 'name' listed as a mutate field for '%s'" % (opcode)
# reduce opdata down to the given fields....
must_equal = namedb_update_must_equal( opdata, mutate_fields )
must_equal += ['name','block_number']
for ignored in constraints_ignored:
if ignored in must_equal:
# ignore this constraint
must_equal.remove( ignored )
try:
query, values = namedb_update_prepare( cur, ['name', 'block_number'], opdata, "name_records", must_equal=must_equal, only_if=only_if )
except Exception, e:
log.exception(e)
log.error("FATAL: failed to update name '%s'" % opdata['name'])
os.abort()
namedb_query_execute( cur, query, values )
try:
assert cur.rowcount == 1, "Updated %s row(s)" % cur.rowcount
except Exception, e:
log.exception(e)
log.error("FATAL: failed to update name '%s'" % opdata['name'])
log.error("Query: %s", "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] ))
os.abort()
return True | [
"def",
"namedb_name_update",
"(",
"cur",
",",
"opcode",
",",
"input_opdata",
",",
"only_if",
"=",
"{",
"}",
",",
"constraints_ignored",
"=",
"[",
"]",
")",
":",
"opdata",
"=",
"copy",
".",
"deepcopy",
"(",
"input_opdata",
")",
"namedb_name_fields_check",
"(",
"opdata",
")",
"mutate_fields",
"=",
"op_get_mutate_fields",
"(",
"opcode",
")",
"if",
"opcode",
"not",
"in",
"OPCODE_CREATION_OPS",
":",
"assert",
"'name'",
"not",
"in",
"mutate_fields",
",",
"\"BUG: 'name' listed as a mutate field for '%s'\"",
"%",
"(",
"opcode",
")",
"# reduce opdata down to the given fields....",
"must_equal",
"=",
"namedb_update_must_equal",
"(",
"opdata",
",",
"mutate_fields",
")",
"must_equal",
"+=",
"[",
"'name'",
",",
"'block_number'",
"]",
"for",
"ignored",
"in",
"constraints_ignored",
":",
"if",
"ignored",
"in",
"must_equal",
":",
"# ignore this constraint ",
"must_equal",
".",
"remove",
"(",
"ignored",
")",
"try",
":",
"query",
",",
"values",
"=",
"namedb_update_prepare",
"(",
"cur",
",",
"[",
"'name'",
",",
"'block_number'",
"]",
",",
"opdata",
",",
"\"name_records\"",
",",
"must_equal",
"=",
"must_equal",
",",
"only_if",
"=",
"only_if",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: failed to update name '%s'\"",
"%",
"opdata",
"[",
"'name'",
"]",
")",
"os",
".",
"abort",
"(",
")",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
")",
"try",
":",
"assert",
"cur",
".",
"rowcount",
"==",
"1",
",",
"\"Updated %s row(s)\"",
"%",
"cur",
".",
"rowcount",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: failed to update name '%s'\"",
"%",
"opdata",
"[",
"'name'",
"]",
")",
"log",
".",
"error",
"(",
"\"Query: %s\"",
",",
"\"\"",
".",
"join",
"(",
"[",
"\"%s %s\"",
"%",
"(",
"frag",
",",
"\"'%s'\"",
"%",
"val",
"if",
"type",
"(",
"val",
")",
"in",
"[",
"str",
",",
"unicode",
"]",
"else",
"val",
")",
"for",
"(",
"frag",
",",
"val",
")",
"in",
"zip",
"(",
"query",
".",
"split",
"(",
"\"?\"",
")",
",",
"values",
"+",
"(",
"\"\"",
",",
")",
")",
"]",
")",
")",
"os",
".",
"abort",
"(",
")",
"return",
"True"
] | Update an existing name in the database.
If non-empty, only update the given fields.
DO NOT CALL THIS METHOD DIRECTLY. | [
"Update",
"an",
"existing",
"name",
"in",
"the",
"database",
".",
"If",
"non",
"-",
"empty",
"only",
"update",
"the",
"given",
"fields",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L796-L837 |
230,719 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_state_mutation_sanity_check | def namedb_state_mutation_sanity_check( opcode, op_data ):
"""
Make sure all mutate fields for this operation are present.
Return True if so
Raise exception if not
"""
# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.
missing = []
mutate_fields = op_get_mutate_fields( opcode )
for field in mutate_fields:
if field not in op_data.keys():
missing.append( field )
assert len(missing) == 0, ("BUG: operation '%s' is missing the following fields: %s" % (opcode, ",".join(missing)))
return True | python | def namedb_state_mutation_sanity_check( opcode, op_data ):
"""
Make sure all mutate fields for this operation are present.
Return True if so
Raise exception if not
"""
# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.
missing = []
mutate_fields = op_get_mutate_fields( opcode )
for field in mutate_fields:
if field not in op_data.keys():
missing.append( field )
assert len(missing) == 0, ("BUG: operation '%s' is missing the following fields: %s" % (opcode, ",".join(missing)))
return True | [
"def",
"namedb_state_mutation_sanity_check",
"(",
"opcode",
",",
"op_data",
")",
":",
"# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.",
"missing",
"=",
"[",
"]",
"mutate_fields",
"=",
"op_get_mutate_fields",
"(",
"opcode",
")",
"for",
"field",
"in",
"mutate_fields",
":",
"if",
"field",
"not",
"in",
"op_data",
".",
"keys",
"(",
")",
":",
"missing",
".",
"append",
"(",
"field",
")",
"assert",
"len",
"(",
"missing",
")",
"==",
"0",
",",
"(",
"\"BUG: operation '%s' is missing the following fields: %s\"",
"%",
"(",
"opcode",
",",
"\",\"",
".",
"join",
"(",
"missing",
")",
")",
")",
"return",
"True"
] | Make sure all mutate fields for this operation are present.
Return True if so
Raise exception if not | [
"Make",
"sure",
"all",
"mutate",
"fields",
"for",
"this",
"operation",
"are",
"present",
".",
"Return",
"True",
"if",
"so",
"Raise",
"exception",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L963-L978 |
230,720 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_last_name_import | def namedb_get_last_name_import(cur, name, block_id, vtxindex):
"""
Find the last name import for this name
"""
query = 'SELECT history_data FROM history WHERE history_id = ? AND (block_id < ? OR (block_id = ? AND vtxindex < ?)) ' + \
'ORDER BY block_id DESC,vtxindex DESC LIMIT 1;'
args = (name, block_id, block_id, vtxindex)
history_rows = namedb_query_execute(cur, query, args)
for row in history_rows:
history_data = json.loads(row['history_data'])
return history_data
return None | python | def namedb_get_last_name_import(cur, name, block_id, vtxindex):
"""
Find the last name import for this name
"""
query = 'SELECT history_data FROM history WHERE history_id = ? AND (block_id < ? OR (block_id = ? AND vtxindex < ?)) ' + \
'ORDER BY block_id DESC,vtxindex DESC LIMIT 1;'
args = (name, block_id, block_id, vtxindex)
history_rows = namedb_query_execute(cur, query, args)
for row in history_rows:
history_data = json.loads(row['history_data'])
return history_data
return None | [
"def",
"namedb_get_last_name_import",
"(",
"cur",
",",
"name",
",",
"block_id",
",",
"vtxindex",
")",
":",
"query",
"=",
"'SELECT history_data FROM history WHERE history_id = ? AND (block_id < ? OR (block_id = ? AND vtxindex < ?)) '",
"+",
"'ORDER BY block_id DESC,vtxindex DESC LIMIT 1;'",
"args",
"=",
"(",
"name",
",",
"block_id",
",",
"block_id",
",",
"vtxindex",
")",
"history_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"for",
"row",
"in",
"history_rows",
":",
"history_data",
"=",
"json",
".",
"loads",
"(",
"row",
"[",
"'history_data'",
"]",
")",
"return",
"history_data",
"return",
"None"
] | Find the last name import for this name | [
"Find",
"the",
"last",
"name",
"import",
"for",
"this",
"name"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1328-L1343 |
230,721 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_account_transaction_save | def namedb_account_transaction_save(cur, address, token_type, new_credit_value, new_debit_value, block_id, vtxindex, txid, existing_account):
"""
Insert the new state of an account at a particular point in time.
The data must be for a never-before-seen (txid,block_id,vtxindex) set in the accounts table, but must
correspond to an entry in the history table.
If existing_account is not None, then copy all other remaining fields from it.
Return True on success
Raise an Exception on error
"""
if existing_account is None:
existing_account = {}
accounts_insert = {
'address': address,
'type': token_type,
'credit_value': '{}'.format(new_credit_value),
'debit_value': '{}'.format(new_debit_value),
'lock_transfer_block_id': existing_account.get('lock_transfer_block_id', 0), # unlocks immediately if the account doesn't exist
'receive_whitelisted': existing_account.get('receive_whitelisted', True), # new accounts are whitelisted by default (for now)
'metadata': existing_account.get('metadata', None),
'block_id': block_id,
'txid': txid,
'vtxindex': vtxindex
}
try:
query, values = namedb_insert_prepare(cur, accounts_insert, 'accounts')
except Exception as e:
log.exception(e)
log.fatal('FATAL: failed to append account history record for {} at ({},{})'.format(address, block_id, vtxindex))
os.abort()
namedb_query_execute(cur, query, values)
return True | python | def namedb_account_transaction_save(cur, address, token_type, new_credit_value, new_debit_value, block_id, vtxindex, txid, existing_account):
"""
Insert the new state of an account at a particular point in time.
The data must be for a never-before-seen (txid,block_id,vtxindex) set in the accounts table, but must
correspond to an entry in the history table.
If existing_account is not None, then copy all other remaining fields from it.
Return True on success
Raise an Exception on error
"""
if existing_account is None:
existing_account = {}
accounts_insert = {
'address': address,
'type': token_type,
'credit_value': '{}'.format(new_credit_value),
'debit_value': '{}'.format(new_debit_value),
'lock_transfer_block_id': existing_account.get('lock_transfer_block_id', 0), # unlocks immediately if the account doesn't exist
'receive_whitelisted': existing_account.get('receive_whitelisted', True), # new accounts are whitelisted by default (for now)
'metadata': existing_account.get('metadata', None),
'block_id': block_id,
'txid': txid,
'vtxindex': vtxindex
}
try:
query, values = namedb_insert_prepare(cur, accounts_insert, 'accounts')
except Exception as e:
log.exception(e)
log.fatal('FATAL: failed to append account history record for {} at ({},{})'.format(address, block_id, vtxindex))
os.abort()
namedb_query_execute(cur, query, values)
return True | [
"def",
"namedb_account_transaction_save",
"(",
"cur",
",",
"address",
",",
"token_type",
",",
"new_credit_value",
",",
"new_debit_value",
",",
"block_id",
",",
"vtxindex",
",",
"txid",
",",
"existing_account",
")",
":",
"if",
"existing_account",
"is",
"None",
":",
"existing_account",
"=",
"{",
"}",
"accounts_insert",
"=",
"{",
"'address'",
":",
"address",
",",
"'type'",
":",
"token_type",
",",
"'credit_value'",
":",
"'{}'",
".",
"format",
"(",
"new_credit_value",
")",
",",
"'debit_value'",
":",
"'{}'",
".",
"format",
"(",
"new_debit_value",
")",
",",
"'lock_transfer_block_id'",
":",
"existing_account",
".",
"get",
"(",
"'lock_transfer_block_id'",
",",
"0",
")",
",",
"# unlocks immediately if the account doesn't exist",
"'receive_whitelisted'",
":",
"existing_account",
".",
"get",
"(",
"'receive_whitelisted'",
",",
"True",
")",
",",
"# new accounts are whitelisted by default (for now)",
"'metadata'",
":",
"existing_account",
".",
"get",
"(",
"'metadata'",
",",
"None",
")",
",",
"'block_id'",
":",
"block_id",
",",
"'txid'",
":",
"txid",
",",
"'vtxindex'",
":",
"vtxindex",
"}",
"try",
":",
"query",
",",
"values",
"=",
"namedb_insert_prepare",
"(",
"cur",
",",
"accounts_insert",
",",
"'accounts'",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"fatal",
"(",
"'FATAL: failed to append account history record for {} at ({},{})'",
".",
"format",
"(",
"address",
",",
"block_id",
",",
"vtxindex",
")",
")",
"os",
".",
"abort",
"(",
")",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"values",
")",
"return",
"True"
] | Insert the new state of an account at a particular point in time.
The data must be for a never-before-seen (txid,block_id,vtxindex) set in the accounts table, but must
correspond to an entry in the history table.
If existing_account is not None, then copy all other remaining fields from it.
Return True on success
Raise an Exception on error | [
"Insert",
"the",
"new",
"state",
"of",
"an",
"account",
"at",
"a",
"particular",
"point",
"in",
"time",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1420-L1456 |
230,722 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_account_debit | def namedb_account_debit(cur, account_addr, token_type, amount, block_id, vtxindex, txid):
"""
Debit an account at a particular point in time by the given amount.
Insert a new history entry for the account into the accounts table.
The account must exist
Abort the program if the account balance goes negative, or the count does not exist
"""
account = namedb_get_account(cur, account_addr, token_type)
if account is None:
traceback.print_stack()
log.fatal('Account {} does not exist'.format(account_addr))
os.abort()
new_credit_value = account['credit_value']
new_debit_value = account['debit_value'] + amount
# sanity check
if new_debit_value > new_credit_value:
traceback.print_stack()
log.fatal('Account {} for "{}" tokens overdrew (debits = {}, credits = {})'.format(account_addr, token_type, new_debit_value, new_credit_value))
os.abort()
new_balance = new_credit_value - new_debit_value
log.debug("Account balance of units of '{}' for {} is now {}".format(token_type, account_addr, new_balance))
res = namedb_account_transaction_save(cur, account_addr, token_type, new_credit_value, new_debit_value, block_id, vtxindex, txid, account)
if not res:
traceback.print_stack()
log.fatal('Failed to save new account state for {}'.format(account_addr))
os.abort()
return True | python | def namedb_account_debit(cur, account_addr, token_type, amount, block_id, vtxindex, txid):
"""
Debit an account at a particular point in time by the given amount.
Insert a new history entry for the account into the accounts table.
The account must exist
Abort the program if the account balance goes negative, or the count does not exist
"""
account = namedb_get_account(cur, account_addr, token_type)
if account is None:
traceback.print_stack()
log.fatal('Account {} does not exist'.format(account_addr))
os.abort()
new_credit_value = account['credit_value']
new_debit_value = account['debit_value'] + amount
# sanity check
if new_debit_value > new_credit_value:
traceback.print_stack()
log.fatal('Account {} for "{}" tokens overdrew (debits = {}, credits = {})'.format(account_addr, token_type, new_debit_value, new_credit_value))
os.abort()
new_balance = new_credit_value - new_debit_value
log.debug("Account balance of units of '{}' for {} is now {}".format(token_type, account_addr, new_balance))
res = namedb_account_transaction_save(cur, account_addr, token_type, new_credit_value, new_debit_value, block_id, vtxindex, txid, account)
if not res:
traceback.print_stack()
log.fatal('Failed to save new account state for {}'.format(account_addr))
os.abort()
return True | [
"def",
"namedb_account_debit",
"(",
"cur",
",",
"account_addr",
",",
"token_type",
",",
"amount",
",",
"block_id",
",",
"vtxindex",
",",
"txid",
")",
":",
"account",
"=",
"namedb_get_account",
"(",
"cur",
",",
"account_addr",
",",
"token_type",
")",
"if",
"account",
"is",
"None",
":",
"traceback",
".",
"print_stack",
"(",
")",
"log",
".",
"fatal",
"(",
"'Account {} does not exist'",
".",
"format",
"(",
"account_addr",
")",
")",
"os",
".",
"abort",
"(",
")",
"new_credit_value",
"=",
"account",
"[",
"'credit_value'",
"]",
"new_debit_value",
"=",
"account",
"[",
"'debit_value'",
"]",
"+",
"amount",
"# sanity check",
"if",
"new_debit_value",
">",
"new_credit_value",
":",
"traceback",
".",
"print_stack",
"(",
")",
"log",
".",
"fatal",
"(",
"'Account {} for \"{}\" tokens overdrew (debits = {}, credits = {})'",
".",
"format",
"(",
"account_addr",
",",
"token_type",
",",
"new_debit_value",
",",
"new_credit_value",
")",
")",
"os",
".",
"abort",
"(",
")",
"new_balance",
"=",
"new_credit_value",
"-",
"new_debit_value",
"log",
".",
"debug",
"(",
"\"Account balance of units of '{}' for {} is now {}\"",
".",
"format",
"(",
"token_type",
",",
"account_addr",
",",
"new_balance",
")",
")",
"res",
"=",
"namedb_account_transaction_save",
"(",
"cur",
",",
"account_addr",
",",
"token_type",
",",
"new_credit_value",
",",
"new_debit_value",
",",
"block_id",
",",
"vtxindex",
",",
"txid",
",",
"account",
")",
"if",
"not",
"res",
":",
"traceback",
".",
"print_stack",
"(",
")",
"log",
".",
"fatal",
"(",
"'Failed to save new account state for {}'",
".",
"format",
"(",
"account_addr",
")",
")",
"os",
".",
"abort",
"(",
")",
"return",
"True"
] | Debit an account at a particular point in time by the given amount.
Insert a new history entry for the account into the accounts table.
The account must exist
Abort the program if the account balance goes negative, or the count does not exist | [
"Debit",
"an",
"account",
"at",
"a",
"particular",
"point",
"in",
"time",
"by",
"the",
"given",
"amount",
".",
"Insert",
"a",
"new",
"history",
"entry",
"for",
"the",
"account",
"into",
"the",
"accounts",
"table",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1459-L1492 |
230,723 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_accounts_vest | def namedb_accounts_vest(cur, block_height):
"""
Vest tokens at this block to all recipients.
Goes through the vesting table and debits each account that should vest on this block.
"""
sql = 'SELECT * FROM account_vesting WHERE block_id = ?'
args = (block_height,)
vesting_rows = namedb_query_execute(cur, sql, args)
rows = []
for row in vesting_rows:
tmp = {}
tmp.update(row)
rows.append(tmp)
for row in rows:
addr = row['address']
token_type = row['type']
token_amount = row['vesting_value']
log.debug("Vest {} with {} {}".format(addr, token_amount, token_type))
fake_txid = namedb_vesting_txid(addr, token_type, token_amount, block_height)
res = namedb_account_credit(cur, addr, token_type, token_amount, block_height, 0, fake_txid)
if not res:
traceback.print_stack()
log.fatal('Failed to vest {} {} to {}'.format(token_amount, token_type, addr))
os.abort()
return True | python | def namedb_accounts_vest(cur, block_height):
"""
Vest tokens at this block to all recipients.
Goes through the vesting table and debits each account that should vest on this block.
"""
sql = 'SELECT * FROM account_vesting WHERE block_id = ?'
args = (block_height,)
vesting_rows = namedb_query_execute(cur, sql, args)
rows = []
for row in vesting_rows:
tmp = {}
tmp.update(row)
rows.append(tmp)
for row in rows:
addr = row['address']
token_type = row['type']
token_amount = row['vesting_value']
log.debug("Vest {} with {} {}".format(addr, token_amount, token_type))
fake_txid = namedb_vesting_txid(addr, token_type, token_amount, block_height)
res = namedb_account_credit(cur, addr, token_type, token_amount, block_height, 0, fake_txid)
if not res:
traceback.print_stack()
log.fatal('Failed to vest {} {} to {}'.format(token_amount, token_type, addr))
os.abort()
return True | [
"def",
"namedb_accounts_vest",
"(",
"cur",
",",
"block_height",
")",
":",
"sql",
"=",
"'SELECT * FROM account_vesting WHERE block_id = ?'",
"args",
"=",
"(",
"block_height",
",",
")",
"vesting_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"rows",
"=",
"[",
"]",
"for",
"row",
"in",
"vesting_rows",
":",
"tmp",
"=",
"{",
"}",
"tmp",
".",
"update",
"(",
"row",
")",
"rows",
".",
"append",
"(",
"tmp",
")",
"for",
"row",
"in",
"rows",
":",
"addr",
"=",
"row",
"[",
"'address'",
"]",
"token_type",
"=",
"row",
"[",
"'type'",
"]",
"token_amount",
"=",
"row",
"[",
"'vesting_value'",
"]",
"log",
".",
"debug",
"(",
"\"Vest {} with {} {}\"",
".",
"format",
"(",
"addr",
",",
"token_amount",
",",
"token_type",
")",
")",
"fake_txid",
"=",
"namedb_vesting_txid",
"(",
"addr",
",",
"token_type",
",",
"token_amount",
",",
"block_height",
")",
"res",
"=",
"namedb_account_credit",
"(",
"cur",
",",
"addr",
",",
"token_type",
",",
"token_amount",
",",
"block_height",
",",
"0",
",",
"fake_txid",
")",
"if",
"not",
"res",
":",
"traceback",
".",
"print_stack",
"(",
")",
"log",
".",
"fatal",
"(",
"'Failed to vest {} {} to {}'",
".",
"format",
"(",
"token_amount",
",",
"token_type",
",",
"addr",
")",
")",
"os",
".",
"abort",
"(",
")",
"return",
"True"
] | Vest tokens at this block to all recipients.
Goes through the vesting table and debits each account that should vest on this block. | [
"Vest",
"tokens",
"at",
"this",
"block",
"to",
"all",
"recipients",
".",
"Goes",
"through",
"the",
"vesting",
"table",
"and",
"debits",
"each",
"account",
"that",
"should",
"vest",
"on",
"this",
"block",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1538-L1568 |
230,724 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_is_history_snapshot | def namedb_is_history_snapshot( history_snapshot ):
"""
Given a dict, verify that it is a history snapshot.
It must have all consensus fields.
Return True if so.
Raise an exception of it doesn't.
"""
# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.
missing = []
assert 'op' in history_snapshot.keys(), "BUG: no op given"
opcode = op_get_opcode_name( history_snapshot['op'] )
assert opcode is not None, "BUG: unrecognized op '%s'" % history_snapshot['op']
consensus_fields = op_get_consensus_fields( opcode )
for field in consensus_fields:
if field not in history_snapshot.keys():
missing.append( field )
assert len(missing) == 0, ("BUG: operation '%s' is missing the following fields: %s" % (opcode, ",".join(missing)))
return True | python | def namedb_is_history_snapshot( history_snapshot ):
"""
Given a dict, verify that it is a history snapshot.
It must have all consensus fields.
Return True if so.
Raise an exception of it doesn't.
"""
# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.
missing = []
assert 'op' in history_snapshot.keys(), "BUG: no op given"
opcode = op_get_opcode_name( history_snapshot['op'] )
assert opcode is not None, "BUG: unrecognized op '%s'" % history_snapshot['op']
consensus_fields = op_get_consensus_fields( opcode )
for field in consensus_fields:
if field not in history_snapshot.keys():
missing.append( field )
assert len(missing) == 0, ("BUG: operation '%s' is missing the following fields: %s" % (opcode, ",".join(missing)))
return True | [
"def",
"namedb_is_history_snapshot",
"(",
"history_snapshot",
")",
":",
"# sanity check: each mutate field in the operation must be defined in op_data, even if it's null.",
"missing",
"=",
"[",
"]",
"assert",
"'op'",
"in",
"history_snapshot",
".",
"keys",
"(",
")",
",",
"\"BUG: no op given\"",
"opcode",
"=",
"op_get_opcode_name",
"(",
"history_snapshot",
"[",
"'op'",
"]",
")",
"assert",
"opcode",
"is",
"not",
"None",
",",
"\"BUG: unrecognized op '%s'\"",
"%",
"history_snapshot",
"[",
"'op'",
"]",
"consensus_fields",
"=",
"op_get_consensus_fields",
"(",
"opcode",
")",
"for",
"field",
"in",
"consensus_fields",
":",
"if",
"field",
"not",
"in",
"history_snapshot",
".",
"keys",
"(",
")",
":",
"missing",
".",
"append",
"(",
"field",
")",
"assert",
"len",
"(",
"missing",
")",
"==",
"0",
",",
"(",
"\"BUG: operation '%s' is missing the following fields: %s\"",
"%",
"(",
"opcode",
",",
"\",\"",
".",
"join",
"(",
"missing",
")",
")",
")",
"return",
"True"
] | Given a dict, verify that it is a history snapshot.
It must have all consensus fields.
Return True if so.
Raise an exception of it doesn't. | [
"Given",
"a",
"dict",
"verify",
"that",
"it",
"is",
"a",
"history",
"snapshot",
".",
"It",
"must",
"have",
"all",
"consensus",
"fields",
".",
"Return",
"True",
"if",
"so",
".",
"Raise",
"an",
"exception",
"of",
"it",
"doesn",
"t",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1571-L1593 |
230,725 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_account_tokens | def namedb_get_account_tokens(cur, address):
"""
Get an account's tokens
Returns the list of tokens on success
Returns None if not found
"""
sql = 'SELECT DISTINCT type FROM accounts WHERE address = ?;'
args = (address,)
rows = namedb_query_execute(cur, sql, args)
ret = []
for row in rows:
ret.append(row['type'])
return ret | python | def namedb_get_account_tokens(cur, address):
"""
Get an account's tokens
Returns the list of tokens on success
Returns None if not found
"""
sql = 'SELECT DISTINCT type FROM accounts WHERE address = ?;'
args = (address,)
rows = namedb_query_execute(cur, sql, args)
ret = []
for row in rows:
ret.append(row['type'])
return ret | [
"def",
"namedb_get_account_tokens",
"(",
"cur",
",",
"address",
")",
":",
"sql",
"=",
"'SELECT DISTINCT type FROM accounts WHERE address = ?;'",
"args",
"=",
"(",
"address",
",",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"ret",
".",
"append",
"(",
"row",
"[",
"'type'",
"]",
")",
"return",
"ret"
] | Get an account's tokens
Returns the list of tokens on success
Returns None if not found | [
"Get",
"an",
"account",
"s",
"tokens",
"Returns",
"the",
"list",
"of",
"tokens",
"on",
"success",
"Returns",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1742-L1756 |
230,726 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_account | def namedb_get_account(cur, address, token_type):
"""
Get an account, given the address.
Returns the account row on success
Returns None if not found
"""
sql = 'SELECT * FROM accounts WHERE address = ? AND type = ? ORDER BY block_id DESC, vtxindex DESC LIMIT 1;'
args = (address,token_type)
rows = namedb_query_execute(cur, sql, args)
row = rows.fetchone()
if row is None:
return None
ret = {}
ret.update(row)
return ret | python | def namedb_get_account(cur, address, token_type):
"""
Get an account, given the address.
Returns the account row on success
Returns None if not found
"""
sql = 'SELECT * FROM accounts WHERE address = ? AND type = ? ORDER BY block_id DESC, vtxindex DESC LIMIT 1;'
args = (address,token_type)
rows = namedb_query_execute(cur, sql, args)
row = rows.fetchone()
if row is None:
return None
ret = {}
ret.update(row)
return ret | [
"def",
"namedb_get_account",
"(",
"cur",
",",
"address",
",",
"token_type",
")",
":",
"sql",
"=",
"'SELECT * FROM accounts WHERE address = ? AND type = ? ORDER BY block_id DESC, vtxindex DESC LIMIT 1;'",
"args",
"=",
"(",
"address",
",",
"token_type",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"row",
"=",
"rows",
".",
"fetchone",
"(",
")",
"if",
"row",
"is",
"None",
":",
"return",
"None",
"ret",
"=",
"{",
"}",
"ret",
".",
"update",
"(",
"row",
")",
"return",
"ret"
] | Get an account, given the address.
Returns the account row on success
Returns None if not found | [
"Get",
"an",
"account",
"given",
"the",
"address",
".",
"Returns",
"the",
"account",
"row",
"on",
"success",
"Returns",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1759-L1775 |
230,727 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_account_diff | def namedb_get_account_diff(current, prior):
"""
Figure out what the expenditure difference is between two accounts.
They must be for the same token type and address.
Calculates current - prior
"""
if current['address'] != prior['address'] or current['type'] != prior['type']:
raise ValueError("Accounts for two different addresses and/or token types")
# NOTE: only possible since Python doesn't overflow :P
return namedb_get_account_balance(current) - namedb_get_account_balance(prior) | python | def namedb_get_account_diff(current, prior):
"""
Figure out what the expenditure difference is between two accounts.
They must be for the same token type and address.
Calculates current - prior
"""
if current['address'] != prior['address'] or current['type'] != prior['type']:
raise ValueError("Accounts for two different addresses and/or token types")
# NOTE: only possible since Python doesn't overflow :P
return namedb_get_account_balance(current) - namedb_get_account_balance(prior) | [
"def",
"namedb_get_account_diff",
"(",
"current",
",",
"prior",
")",
":",
"if",
"current",
"[",
"'address'",
"]",
"!=",
"prior",
"[",
"'address'",
"]",
"or",
"current",
"[",
"'type'",
"]",
"!=",
"prior",
"[",
"'type'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Accounts for two different addresses and/or token types\"",
")",
"# NOTE: only possible since Python doesn't overflow :P",
"return",
"namedb_get_account_balance",
"(",
"current",
")",
"-",
"namedb_get_account_balance",
"(",
"prior",
")"
] | Figure out what the expenditure difference is between two accounts.
They must be for the same token type and address.
Calculates current - prior | [
"Figure",
"out",
"what",
"the",
"expenditure",
"difference",
"is",
"between",
"two",
"accounts",
".",
"They",
"must",
"be",
"for",
"the",
"same",
"token",
"type",
"and",
"address",
".",
"Calculates",
"current",
"-",
"prior"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1808-L1818 |
230,728 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_account_history | def namedb_get_account_history(cur, address, offset=None, count=None):
"""
Get the history of an account's tokens
"""
sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'
args = (address,)
if count is not None:
sql += ' LIMIT ?'
args += (count,)
if offset is not None:
sql += ' OFFSET ?'
args += (offset,)
sql += ';'
rows = namedb_query_execute(cur, sql, args)
ret = []
for rowdata in rows:
tmp = {}
tmp.update(rowdata)
ret.append(tmp)
return ret | python | def namedb_get_account_history(cur, address, offset=None, count=None):
"""
Get the history of an account's tokens
"""
sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'
args = (address,)
if count is not None:
sql += ' LIMIT ?'
args += (count,)
if offset is not None:
sql += ' OFFSET ?'
args += (offset,)
sql += ';'
rows = namedb_query_execute(cur, sql, args)
ret = []
for rowdata in rows:
tmp = {}
tmp.update(rowdata)
ret.append(tmp)
return ret | [
"def",
"namedb_get_account_history",
"(",
"cur",
",",
"address",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"sql",
"=",
"'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'",
"args",
"=",
"(",
"address",
",",
")",
"if",
"count",
"is",
"not",
"None",
":",
"sql",
"+=",
"' LIMIT ?'",
"args",
"+=",
"(",
"count",
",",
")",
"if",
"offset",
"is",
"not",
"None",
":",
"sql",
"+=",
"' OFFSET ?'",
"args",
"+=",
"(",
"offset",
",",
")",
"sql",
"+=",
"';'",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"rowdata",
"in",
"rows",
":",
"tmp",
"=",
"{",
"}",
"tmp",
".",
"update",
"(",
"rowdata",
")",
"ret",
".",
"append",
"(",
"tmp",
")",
"return",
"ret"
] | Get the history of an account's tokens | [
"Get",
"the",
"history",
"of",
"an",
"account",
"s",
"tokens"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1821-L1845 |
230,729 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_account_addresses | def namedb_get_all_account_addresses(cur):
"""
TESTING ONLY
get all account addresses
"""
assert BLOCKSTACK_TEST, 'BUG: this method is only available in test mode'
sql = 'SELECT DISTINCT address FROM accounts;'
args = ()
rows = namedb_query_execute(cur, sql, args)
ret = []
for rowdata in rows:
ret.append(rowdata['address'])
return ret | python | def namedb_get_all_account_addresses(cur):
"""
TESTING ONLY
get all account addresses
"""
assert BLOCKSTACK_TEST, 'BUG: this method is only available in test mode'
sql = 'SELECT DISTINCT address FROM accounts;'
args = ()
rows = namedb_query_execute(cur, sql, args)
ret = []
for rowdata in rows:
ret.append(rowdata['address'])
return ret | [
"def",
"namedb_get_all_account_addresses",
"(",
"cur",
")",
":",
"assert",
"BLOCKSTACK_TEST",
",",
"'BUG: this method is only available in test mode'",
"sql",
"=",
"'SELECT DISTINCT address FROM accounts;'",
"args",
"=",
"(",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"rowdata",
"in",
"rows",
":",
"ret",
".",
"append",
"(",
"rowdata",
"[",
"'address'",
"]",
")",
"return",
"ret"
] | TESTING ONLY
get all account addresses | [
"TESTING",
"ONLY",
"get",
"all",
"account",
"addresses"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1848-L1862 |
230,730 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_name_at | def namedb_get_name_at(cur, name, block_number, include_expired=False):
"""
Get the sequence of states that a name record was in at a particular block height.
There can be more than one if the name changed during the block.
Returns only unexpired names by default. Can return expired names with include_expired=True
Returns None if this name does not exist at this block height.
"""
if not include_expired:
# don't return anything if this name is expired.
# however, we don't care if the name hasn't been created as of this block_number either, since we might return its preorder (hence only_registered=False)
name_rec = namedb_get_name(cur, name, block_number, include_expired=False, include_history=False, only_registered=False)
if name_rec is None:
# expired at this block.
return None
history_rows = namedb_get_record_states_at(cur, name, block_number)
if len(history_rows) == 0:
# doesn't exist
return None
else:
return history_rows | python | def namedb_get_name_at(cur, name, block_number, include_expired=False):
"""
Get the sequence of states that a name record was in at a particular block height.
There can be more than one if the name changed during the block.
Returns only unexpired names by default. Can return expired names with include_expired=True
Returns None if this name does not exist at this block height.
"""
if not include_expired:
# don't return anything if this name is expired.
# however, we don't care if the name hasn't been created as of this block_number either, since we might return its preorder (hence only_registered=False)
name_rec = namedb_get_name(cur, name, block_number, include_expired=False, include_history=False, only_registered=False)
if name_rec is None:
# expired at this block.
return None
history_rows = namedb_get_record_states_at(cur, name, block_number)
if len(history_rows) == 0:
# doesn't exist
return None
else:
return history_rows | [
"def",
"namedb_get_name_at",
"(",
"cur",
",",
"name",
",",
"block_number",
",",
"include_expired",
"=",
"False",
")",
":",
"if",
"not",
"include_expired",
":",
"# don't return anything if this name is expired.",
"# however, we don't care if the name hasn't been created as of this block_number either, since we might return its preorder (hence only_registered=False)",
"name_rec",
"=",
"namedb_get_name",
"(",
"cur",
",",
"name",
",",
"block_number",
",",
"include_expired",
"=",
"False",
",",
"include_history",
"=",
"False",
",",
"only_registered",
"=",
"False",
")",
"if",
"name_rec",
"is",
"None",
":",
"# expired at this block.",
"return",
"None",
"history_rows",
"=",
"namedb_get_record_states_at",
"(",
"cur",
",",
"name",
",",
"block_number",
")",
"if",
"len",
"(",
"history_rows",
")",
"==",
"0",
":",
"# doesn't exist",
"return",
"None",
"else",
":",
"return",
"history_rows"
] | Get the sequence of states that a name record was in at a particular block height.
There can be more than one if the name changed during the block.
Returns only unexpired names by default. Can return expired names with include_expired=True
Returns None if this name does not exist at this block height. | [
"Get",
"the",
"sequence",
"of",
"states",
"that",
"a",
"name",
"record",
"was",
"in",
"at",
"a",
"particular",
"block",
"height",
".",
"There",
"can",
"be",
"more",
"than",
"one",
"if",
"the",
"name",
"changed",
"during",
"the",
"block",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2150-L2171 |
230,731 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_namespace_at | def namedb_get_namespace_at(cur, namespace_id, block_number, include_expired=False):
"""
Get the sequence of states that a namespace record was in at a particular block height.
There can be more than one if the namespace changed durnig the block.
Returns only unexpired namespaces by default. Can return expired namespaces with include_expired=True
"""
if not include_expired:
# don't return anything if the namespace was expired at this block.
# (but do return something here even if the namespace was created after this block, so we can potentially pick up its preorder (hence only_revealed=False))
namespace_rec = namedb_get_namespace(cur, namespace_id, block_number, include_expired=False, include_history=False, only_revealed=False)
if namespace_rec is None:
# expired at this block
return None
history_rows = namedb_get_record_states_at(cur, namespace_id, block_number)
if len(history_rows) == 0:
# doesn't exist yet
return None
else:
return history_rows | python | def namedb_get_namespace_at(cur, namespace_id, block_number, include_expired=False):
"""
Get the sequence of states that a namespace record was in at a particular block height.
There can be more than one if the namespace changed durnig the block.
Returns only unexpired namespaces by default. Can return expired namespaces with include_expired=True
"""
if not include_expired:
# don't return anything if the namespace was expired at this block.
# (but do return something here even if the namespace was created after this block, so we can potentially pick up its preorder (hence only_revealed=False))
namespace_rec = namedb_get_namespace(cur, namespace_id, block_number, include_expired=False, include_history=False, only_revealed=False)
if namespace_rec is None:
# expired at this block
return None
history_rows = namedb_get_record_states_at(cur, namespace_id, block_number)
if len(history_rows) == 0:
# doesn't exist yet
return None
else:
return history_rows | [
"def",
"namedb_get_namespace_at",
"(",
"cur",
",",
"namespace_id",
",",
"block_number",
",",
"include_expired",
"=",
"False",
")",
":",
"if",
"not",
"include_expired",
":",
"# don't return anything if the namespace was expired at this block.",
"# (but do return something here even if the namespace was created after this block, so we can potentially pick up its preorder (hence only_revealed=False))",
"namespace_rec",
"=",
"namedb_get_namespace",
"(",
"cur",
",",
"namespace_id",
",",
"block_number",
",",
"include_expired",
"=",
"False",
",",
"include_history",
"=",
"False",
",",
"only_revealed",
"=",
"False",
")",
"if",
"namespace_rec",
"is",
"None",
":",
"# expired at this block",
"return",
"None",
"history_rows",
"=",
"namedb_get_record_states_at",
"(",
"cur",
",",
"namespace_id",
",",
"block_number",
")",
"if",
"len",
"(",
"history_rows",
")",
"==",
"0",
":",
"# doesn't exist yet ",
"return",
"None",
"else",
":",
"return",
"history_rows"
] | Get the sequence of states that a namespace record was in at a particular block height.
There can be more than one if the namespace changed durnig the block.
Returns only unexpired namespaces by default. Can return expired namespaces with include_expired=True | [
"Get",
"the",
"sequence",
"of",
"states",
"that",
"a",
"namespace",
"record",
"was",
"in",
"at",
"a",
"particular",
"block",
"height",
".",
"There",
"can",
"be",
"more",
"than",
"one",
"if",
"the",
"namespace",
"changed",
"durnig",
"the",
"block",
".",
"Returns",
"only",
"unexpired",
"namespaces",
"by",
"default",
".",
"Can",
"return",
"expired",
"namespaces",
"with",
"include_expired",
"=",
"True"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2174-L2194 |
230,732 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_account_balance | def namedb_get_account_balance(account):
"""
Get the balance of an account for a particular type of token.
This is its credits minus its debits.
Returns the current balance on success.
Aborts on error, or if the balance is somehow negative.
"""
# NOTE: this is only possible because Python does not overflow :P
balance = account['credit_value'] - account['debit_value']
if balance < 0:
log.fatal("Balance of {} is {} (credits = {}, debits = {})".format(account['address'], balance, account['credit_value'], account['debit_value']))
traceback.print_stack()
os.abort()
return balance | python | def namedb_get_account_balance(account):
"""
Get the balance of an account for a particular type of token.
This is its credits minus its debits.
Returns the current balance on success.
Aborts on error, or if the balance is somehow negative.
"""
# NOTE: this is only possible because Python does not overflow :P
balance = account['credit_value'] - account['debit_value']
if balance < 0:
log.fatal("Balance of {} is {} (credits = {}, debits = {})".format(account['address'], balance, account['credit_value'], account['debit_value']))
traceback.print_stack()
os.abort()
return balance | [
"def",
"namedb_get_account_balance",
"(",
"account",
")",
":",
"# NOTE: this is only possible because Python does not overflow :P",
"balance",
"=",
"account",
"[",
"'credit_value'",
"]",
"-",
"account",
"[",
"'debit_value'",
"]",
"if",
"balance",
"<",
"0",
":",
"log",
".",
"fatal",
"(",
"\"Balance of {} is {} (credits = {}, debits = {})\"",
".",
"format",
"(",
"account",
"[",
"'address'",
"]",
",",
"balance",
",",
"account",
"[",
"'credit_value'",
"]",
",",
"account",
"[",
"'debit_value'",
"]",
")",
")",
"traceback",
".",
"print_stack",
"(",
")",
"os",
".",
"abort",
"(",
")",
"return",
"balance"
] | Get the balance of an account for a particular type of token.
This is its credits minus its debits.
Returns the current balance on success.
Aborts on error, or if the balance is somehow negative. | [
"Get",
"the",
"balance",
"of",
"an",
"account",
"for",
"a",
"particular",
"type",
"of",
"token",
".",
"This",
"is",
"its",
"credits",
"minus",
"its",
"debits",
".",
"Returns",
"the",
"current",
"balance",
"on",
"success",
".",
"Aborts",
"on",
"error",
"or",
"if",
"the",
"balance",
"is",
"somehow",
"negative",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2197-L2211 |
230,733 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_preorder | def namedb_get_preorder(cur, preorder_hash, current_block_number, include_expired=False, expiry_time=None):
"""
Get a preorder record by hash.
If include_expired is set, then so must expiry_time
Return None if not found.
"""
select_query = None
args = None
if include_expired:
select_query = "SELECT * FROM preorders WHERE preorder_hash = ?;"
args = (preorder_hash,)
else:
assert expiry_time is not None, "expiry_time is required with include_expired"
select_query = "SELECT * FROM preorders WHERE preorder_hash = ? AND block_number < ?;"
args = (preorder_hash, expiry_time + current_block_number)
preorder_rows = namedb_query_execute( cur, select_query, (preorder_hash,))
preorder_row = preorder_rows.fetchone()
if preorder_row is None:
# no such preorder
return None
preorder_rec = {}
preorder_rec.update( preorder_row )
return preorder_rec | python | def namedb_get_preorder(cur, preorder_hash, current_block_number, include_expired=False, expiry_time=None):
"""
Get a preorder record by hash.
If include_expired is set, then so must expiry_time
Return None if not found.
"""
select_query = None
args = None
if include_expired:
select_query = "SELECT * FROM preorders WHERE preorder_hash = ?;"
args = (preorder_hash,)
else:
assert expiry_time is not None, "expiry_time is required with include_expired"
select_query = "SELECT * FROM preorders WHERE preorder_hash = ? AND block_number < ?;"
args = (preorder_hash, expiry_time + current_block_number)
preorder_rows = namedb_query_execute( cur, select_query, (preorder_hash,))
preorder_row = preorder_rows.fetchone()
if preorder_row is None:
# no such preorder
return None
preorder_rec = {}
preorder_rec.update( preorder_row )
return preorder_rec | [
"def",
"namedb_get_preorder",
"(",
"cur",
",",
"preorder_hash",
",",
"current_block_number",
",",
"include_expired",
"=",
"False",
",",
"expiry_time",
"=",
"None",
")",
":",
"select_query",
"=",
"None",
"args",
"=",
"None",
"if",
"include_expired",
":",
"select_query",
"=",
"\"SELECT * FROM preorders WHERE preorder_hash = ?;\"",
"args",
"=",
"(",
"preorder_hash",
",",
")",
"else",
":",
"assert",
"expiry_time",
"is",
"not",
"None",
",",
"\"expiry_time is required with include_expired\"",
"select_query",
"=",
"\"SELECT * FROM preorders WHERE preorder_hash = ? AND block_number < ?;\"",
"args",
"=",
"(",
"preorder_hash",
",",
"expiry_time",
"+",
"current_block_number",
")",
"preorder_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"(",
"preorder_hash",
",",
")",
")",
"preorder_row",
"=",
"preorder_rows",
".",
"fetchone",
"(",
")",
"if",
"preorder_row",
"is",
"None",
":",
"# no such preorder ",
"return",
"None",
"preorder_rec",
"=",
"{",
"}",
"preorder_rec",
".",
"update",
"(",
"preorder_row",
")",
"return",
"preorder_rec"
] | Get a preorder record by hash.
If include_expired is set, then so must expiry_time
Return None if not found. | [
"Get",
"a",
"preorder",
"record",
"by",
"hash",
".",
"If",
"include_expired",
"is",
"set",
"then",
"so",
"must",
"expiry_time",
"Return",
"None",
"if",
"not",
"found",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2214-L2242 |
230,734 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_num_historic_names_by_address | def namedb_get_num_historic_names_by_address( cur, address ):
"""
Get the number of names owned by an address throughout history
"""
select_query = "SELECT COUNT(*) FROM name_records JOIN history ON name_records.name = history.history_id " + \
"WHERE history.creator_address = ?;"
args = (address,)
count = namedb_select_count_rows( cur, select_query, args )
return count | python | def namedb_get_num_historic_names_by_address( cur, address ):
"""
Get the number of names owned by an address throughout history
"""
select_query = "SELECT COUNT(*) FROM name_records JOIN history ON name_records.name = history.history_id " + \
"WHERE history.creator_address = ?;"
args = (address,)
count = namedb_select_count_rows( cur, select_query, args )
return count | [
"def",
"namedb_get_num_historic_names_by_address",
"(",
"cur",
",",
"address",
")",
":",
"select_query",
"=",
"\"SELECT COUNT(*) FROM name_records JOIN history ON name_records.name = history.history_id \"",
"+",
"\"WHERE history.creator_address = ?;\"",
"args",
"=",
"(",
"address",
",",
")",
"count",
"=",
"namedb_select_count_rows",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"return",
"count"
] | Get the number of names owned by an address throughout history | [
"Get",
"the",
"number",
"of",
"names",
"owned",
"by",
"an",
"address",
"throughout",
"history"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2269-L2280 |
230,735 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_num_names | def namedb_get_num_names( cur, current_block, include_expired=False ):
"""
Get the number of names that exist at the current block
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# count all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";"
args = unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows | python | def namedb_get_num_names( cur, current_block, include_expired=False ):
"""
Get the number of names that exist at the current block
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# count all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";"
args = unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows | [
"def",
"namedb_get_num_names",
"(",
"cur",
",",
"current_block",
",",
"include_expired",
"=",
"False",
")",
":",
"unexpired_query",
"=",
"\"\"",
"unexpired_args",
"=",
"(",
")",
"if",
"not",
"include_expired",
":",
"# count all names, including expired ones",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"unexpired_query",
"=",
"'WHERE {}'",
".",
"format",
"(",
"unexpired_query",
")",
"query",
"=",
"\"SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \"",
"+",
"unexpired_query",
"+",
"\";\"",
"args",
"=",
"unexpired_args",
"num_rows",
"=",
"namedb_select_count_rows",
"(",
"cur",
",",
"query",
",",
"args",
",",
"count_column",
"=",
"'COUNT(name_records.name)'",
")",
"return",
"num_rows"
] | Get the number of names that exist at the current block | [
"Get",
"the",
"number",
"of",
"names",
"that",
"exist",
"at",
"the",
"current",
"block"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2458-L2474 |
230,736 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_names | def namedb_get_all_names( cur, current_block, offset=None, count=None, include_expired=False ):
"""
Get a list of all names in the database, optionally
paginated with offset and count. Exclude expired names. Include revoked names.
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + " ORDER BY name "
args = unexpired_args
offset_count_query, offset_count_args = namedb_offset_count_predicate( offset=offset, count=count )
query += offset_count_query + ";"
args += offset_count_args
name_rows = namedb_query_execute( cur, query, tuple(args) )
ret = []
for name_row in name_rows:
rec = {}
rec.update( name_row )
ret.append( rec['name'] )
return ret | python | def namedb_get_all_names( cur, current_block, offset=None, count=None, include_expired=False ):
"""
Get a list of all names in the database, optionally
paginated with offset and count. Exclude expired names. Include revoked names.
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# all names, including expired ones
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
unexpired_query = 'WHERE {}'.format(unexpired_query)
query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + " ORDER BY name "
args = unexpired_args
offset_count_query, offset_count_args = namedb_offset_count_predicate( offset=offset, count=count )
query += offset_count_query + ";"
args += offset_count_args
name_rows = namedb_query_execute( cur, query, tuple(args) )
ret = []
for name_row in name_rows:
rec = {}
rec.update( name_row )
ret.append( rec['name'] )
return ret | [
"def",
"namedb_get_all_names",
"(",
"cur",
",",
"current_block",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"include_expired",
"=",
"False",
")",
":",
"unexpired_query",
"=",
"\"\"",
"unexpired_args",
"=",
"(",
")",
"if",
"not",
"include_expired",
":",
"# all names, including expired ones",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"unexpired_query",
"=",
"'WHERE {}'",
".",
"format",
"(",
"unexpired_query",
")",
"query",
"=",
"\"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \"",
"+",
"unexpired_query",
"+",
"\" ORDER BY name \"",
"args",
"=",
"unexpired_args",
"offset_count_query",
",",
"offset_count_args",
"=",
"namedb_offset_count_predicate",
"(",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
")",
"query",
"+=",
"offset_count_query",
"+",
"\";\"",
"args",
"+=",
"offset_count_args",
"name_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"tuple",
"(",
"args",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"name_row",
"in",
"name_rows",
":",
"rec",
"=",
"{",
"}",
"rec",
".",
"update",
"(",
"name_row",
")",
"ret",
".",
"append",
"(",
"rec",
"[",
"'name'",
"]",
")",
"return",
"ret"
] | Get a list of all names in the database, optionally
paginated with offset and count. Exclude expired names. Include revoked names. | [
"Get",
"a",
"list",
"of",
"all",
"names",
"in",
"the",
"database",
"optionally",
"paginated",
"with",
"offset",
"and",
"count",
".",
"Exclude",
"expired",
"names",
".",
"Include",
"revoked",
"names",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2477-L2505 |
230,737 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_num_names_in_namespace | def namedb_get_num_names_in_namespace( cur, namespace_id, current_block ):
"""
Get the number of names in a given namespace
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND " + unexpired_query + " ORDER BY name;"
args = (namespace_id,) + unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows | python | def namedb_get_num_names_in_namespace( cur, namespace_id, current_block ):
"""
Get the number of names in a given namespace
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND " + unexpired_query + " ORDER BY name;"
args = (namespace_id,) + unexpired_args
num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )
return num_rows | [
"def",
"namedb_get_num_names_in_namespace",
"(",
"cur",
",",
"namespace_id",
",",
"current_block",
")",
":",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"query",
"=",
"\"SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND \"",
"+",
"unexpired_query",
"+",
"\" ORDER BY name;\"",
"args",
"=",
"(",
"namespace_id",
",",
")",
"+",
"unexpired_args",
"num_rows",
"=",
"namedb_select_count_rows",
"(",
"cur",
",",
"query",
",",
"args",
",",
"count_column",
"=",
"'COUNT(name_records.name)'",
")",
"return",
"num_rows"
] | Get the number of names in a given namespace | [
"Get",
"the",
"number",
"of",
"names",
"in",
"a",
"given",
"namespace"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2508-L2518 |
230,738 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_names_in_namespace | def namedb_get_names_in_namespace( cur, namespace_id, current_block, offset=None, count=None ):
"""
Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND " + unexpired_query + " ORDER BY name "
args = (namespace_id,) + unexpired_args
offset_count_query, offset_count_args = namedb_offset_count_predicate( offset=offset, count=count )
query += offset_count_query + ";"
args += offset_count_args
name_rows = namedb_query_execute( cur, query, tuple(args) )
ret = []
for name_row in name_rows:
rec = {}
rec.update( name_row )
ret.append( rec['name'] )
return ret | python | def namedb_get_names_in_namespace( cur, namespace_id, current_block, offset=None, count=None ):
"""
Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND " + unexpired_query + " ORDER BY name "
args = (namespace_id,) + unexpired_args
offset_count_query, offset_count_args = namedb_offset_count_predicate( offset=offset, count=count )
query += offset_count_query + ";"
args += offset_count_args
name_rows = namedb_query_execute( cur, query, tuple(args) )
ret = []
for name_row in name_rows:
rec = {}
rec.update( name_row )
ret.append( rec['name'] )
return ret | [
"def",
"namedb_get_names_in_namespace",
"(",
"cur",
",",
"namespace_id",
",",
"current_block",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"query",
"=",
"\"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND \"",
"+",
"unexpired_query",
"+",
"\" ORDER BY name \"",
"args",
"=",
"(",
"namespace_id",
",",
")",
"+",
"unexpired_args",
"offset_count_query",
",",
"offset_count_args",
"=",
"namedb_offset_count_predicate",
"(",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
")",
"query",
"+=",
"offset_count_query",
"+",
"\";\"",
"args",
"+=",
"offset_count_args",
"name_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"tuple",
"(",
"args",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"name_row",
"in",
"name_rows",
":",
"rec",
"=",
"{",
"}",
"rec",
".",
"update",
"(",
"name_row",
")",
"ret",
".",
"append",
"(",
"rec",
"[",
"'name'",
"]",
")",
"return",
"ret"
] | Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names | [
"Get",
"a",
"list",
"of",
"all",
"names",
"in",
"a",
"namespace",
"optionally",
"paginated",
"with",
"offset",
"and",
"count",
".",
"Exclude",
"expired",
"names"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2521-L2543 |
230,739 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_namespace_ids | def namedb_get_all_namespace_ids( cur ):
"""
Get a list of all READY namespace IDs.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ?;"
args = (NAMESPACE_READY,)
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['namespace_id'] )
return ret | python | def namedb_get_all_namespace_ids( cur ):
"""
Get a list of all READY namespace IDs.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ?;"
args = (NAMESPACE_READY,)
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['namespace_id'] )
return ret | [
"def",
"namedb_get_all_namespace_ids",
"(",
"cur",
")",
":",
"query",
"=",
"\"SELECT namespace_id FROM namespaces WHERE op = ?;\"",
"args",
"=",
"(",
"NAMESPACE_READY",
",",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"namespace_row",
"in",
"namespace_rows",
":",
"ret",
".",
"append",
"(",
"namespace_row",
"[",
"'namespace_id'",
"]",
")",
"return",
"ret"
] | Get a list of all READY namespace IDs. | [
"Get",
"a",
"list",
"of",
"all",
"READY",
"namespace",
"IDs",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2546-L2559 |
230,740 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_preordered_namespace_hashes | def namedb_get_all_preordered_namespace_hashes( cur, current_block ):
"""
Get a list of all preordered namespace hashes that haven't expired yet.
Used for testing
"""
query = "SELECT preorder_hash FROM preorders WHERE op = ? AND block_number >= ? AND block_number < ?;"
args = (NAMESPACE_PREORDER, current_block, current_block + NAMESPACE_PREORDER_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['preorder_hash'] )
return ret | python | def namedb_get_all_preordered_namespace_hashes( cur, current_block ):
"""
Get a list of all preordered namespace hashes that haven't expired yet.
Used for testing
"""
query = "SELECT preorder_hash FROM preorders WHERE op = ? AND block_number >= ? AND block_number < ?;"
args = (NAMESPACE_PREORDER, current_block, current_block + NAMESPACE_PREORDER_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['preorder_hash'] )
return ret | [
"def",
"namedb_get_all_preordered_namespace_hashes",
"(",
"cur",
",",
"current_block",
")",
":",
"query",
"=",
"\"SELECT preorder_hash FROM preorders WHERE op = ? AND block_number >= ? AND block_number < ?;\"",
"args",
"=",
"(",
"NAMESPACE_PREORDER",
",",
"current_block",
",",
"current_block",
"+",
"NAMESPACE_PREORDER_EXPIRE",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"namespace_row",
"in",
"namespace_rows",
":",
"ret",
".",
"append",
"(",
"namespace_row",
"[",
"'preorder_hash'",
"]",
")",
"return",
"ret"
] | Get a list of all preordered namespace hashes that haven't expired yet.
Used for testing | [
"Get",
"a",
"list",
"of",
"all",
"preordered",
"namespace",
"hashes",
"that",
"haven",
"t",
"expired",
"yet",
".",
"Used",
"for",
"testing"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2562-L2575 |
230,741 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_revealed_namespace_ids | def namedb_get_all_revealed_namespace_ids( self, current_block ):
"""
Get all non-expired revealed namespaces.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ? AND reveal_block < ?;"
args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['namespace_id'] )
return ret | python | def namedb_get_all_revealed_namespace_ids( self, current_block ):
"""
Get all non-expired revealed namespaces.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ? AND reveal_block < ?;"
args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['namespace_id'] )
return ret | [
"def",
"namedb_get_all_revealed_namespace_ids",
"(",
"self",
",",
"current_block",
")",
":",
"query",
"=",
"\"SELECT namespace_id FROM namespaces WHERE op = ? AND reveal_block < ?;\"",
"args",
"=",
"(",
"NAMESPACE_REVEAL",
",",
"current_block",
"+",
"NAMESPACE_REVEAL_EXPIRE",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"namespace_row",
"in",
"namespace_rows",
":",
"ret",
".",
"append",
"(",
"namespace_row",
"[",
"'namespace_id'",
"]",
")",
"return",
"ret"
] | Get all non-expired revealed namespaces. | [
"Get",
"all",
"non",
"-",
"expired",
"revealed",
"namespaces",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2578-L2591 |
230,742 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_all_importing_namespace_hashes | def namedb_get_all_importing_namespace_hashes( self, current_block ):
"""
Get the list of all non-expired preordered and revealed namespace hashes.
"""
query = "SELECT preorder_hash FROM namespaces WHERE (op = ? AND reveal_block < ?) OR (op = ? AND block_number < ?);"
args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE, NAMESPACE_PREORDER, current_block + NAMESPACE_PREORDER_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['preorder_hash'] )
return ret | python | def namedb_get_all_importing_namespace_hashes( self, current_block ):
"""
Get the list of all non-expired preordered and revealed namespace hashes.
"""
query = "SELECT preorder_hash FROM namespaces WHERE (op = ? AND reveal_block < ?) OR (op = ? AND block_number < ?);"
args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE, NAMESPACE_PREORDER, current_block + NAMESPACE_PREORDER_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['preorder_hash'] )
return ret | [
"def",
"namedb_get_all_importing_namespace_hashes",
"(",
"self",
",",
"current_block",
")",
":",
"query",
"=",
"\"SELECT preorder_hash FROM namespaces WHERE (op = ? AND reveal_block < ?) OR (op = ? AND block_number < ?);\"",
"args",
"=",
"(",
"NAMESPACE_REVEAL",
",",
"current_block",
"+",
"NAMESPACE_REVEAL_EXPIRE",
",",
"NAMESPACE_PREORDER",
",",
"current_block",
"+",
"NAMESPACE_PREORDER_EXPIRE",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"namespace_row",
"in",
"namespace_rows",
":",
"ret",
".",
"append",
"(",
"namespace_row",
"[",
"'preorder_hash'",
"]",
")",
"return",
"ret"
] | Get the list of all non-expired preordered and revealed namespace hashes. | [
"Get",
"the",
"list",
"of",
"all",
"non",
"-",
"expired",
"preordered",
"and",
"revealed",
"namespace",
"hashes",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2594-L2607 |
230,743 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_names_by_sender | def namedb_get_names_by_sender( cur, sender, current_block ):
"""
Given a sender pubkey script, find all the non-expired non-revoked names owned by it.
Return None if the sender owns no names.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT name_records.name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE name_records.sender = ? AND name_records.revoked = 0 AND " + unexpired_query + ";"
args = (sender,) + unexpired_args
name_rows = namedb_query_execute( cur, query, args )
names = []
for name_row in name_rows:
names.append( name_row['name'] )
return names | python | def namedb_get_names_by_sender( cur, sender, current_block ):
"""
Given a sender pubkey script, find all the non-expired non-revoked names owned by it.
Return None if the sender owns no names.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )
query = "SELECT name_records.name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE name_records.sender = ? AND name_records.revoked = 0 AND " + unexpired_query + ";"
args = (sender,) + unexpired_args
name_rows = namedb_query_execute( cur, query, args )
names = []
for name_row in name_rows:
names.append( name_row['name'] )
return names | [
"def",
"namedb_get_names_by_sender",
"(",
"cur",
",",
"sender",
",",
"current_block",
")",
":",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"query",
"=",
"\"SELECT name_records.name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \"",
"+",
"\"WHERE name_records.sender = ? AND name_records.revoked = 0 AND \"",
"+",
"unexpired_query",
"+",
"\";\"",
"args",
"=",
"(",
"sender",
",",
")",
"+",
"unexpired_args",
"name_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"names",
"=",
"[",
"]",
"for",
"name_row",
"in",
"name_rows",
":",
"names",
".",
"append",
"(",
"name_row",
"[",
"'name'",
"]",
")",
"return",
"names"
] | Given a sender pubkey script, find all the non-expired non-revoked names owned by it.
Return None if the sender owns no names. | [
"Given",
"a",
"sender",
"pubkey",
"script",
"find",
"all",
"the",
"non",
"-",
"expired",
"non",
"-",
"revoked",
"names",
"owned",
"by",
"it",
".",
"Return",
"None",
"if",
"the",
"sender",
"owns",
"no",
"names",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2610-L2629 |
230,744 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_namespace_preorder | def namedb_get_namespace_preorder( db, namespace_preorder_hash, current_block ):
"""
Get a namespace preorder, given its hash.
Return the preorder record on success.
Return None if not found, or if it expired, or if the namespace was revealed or readied.
"""
cur = db.cursor()
select_query = "SELECT * FROM preorders WHERE preorder_hash = ? AND op = ? AND block_number < ?;"
args = (namespace_preorder_hash, NAMESPACE_PREORDER, current_block + NAMESPACE_PREORDER_EXPIRE)
preorder_rows = namedb_query_execute( cur, select_query, args )
preorder_row = preorder_rows.fetchone()
if preorder_row is None:
# no such preorder
return None
preorder_rec = {}
preorder_rec.update( preorder_row )
# make sure that the namespace doesn't already exist
cur = db.cursor()
select_query = "SELECT preorder_hash FROM namespaces WHERE preorder_hash = ? AND ((op = ?) OR (op = ? AND reveal_block < ?));"
args = (namespace_preorder_hash, NAMESPACE_READY, NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE)
ns_rows = namedb_query_execute( cur, select_query, args )
ns_row = ns_rows.fetchone()
if ns_row is not None:
# exists
return None
return preorder_rec | python | def namedb_get_namespace_preorder( db, namespace_preorder_hash, current_block ):
"""
Get a namespace preorder, given its hash.
Return the preorder record on success.
Return None if not found, or if it expired, or if the namespace was revealed or readied.
"""
cur = db.cursor()
select_query = "SELECT * FROM preorders WHERE preorder_hash = ? AND op = ? AND block_number < ?;"
args = (namespace_preorder_hash, NAMESPACE_PREORDER, current_block + NAMESPACE_PREORDER_EXPIRE)
preorder_rows = namedb_query_execute( cur, select_query, args )
preorder_row = preorder_rows.fetchone()
if preorder_row is None:
# no such preorder
return None
preorder_rec = {}
preorder_rec.update( preorder_row )
# make sure that the namespace doesn't already exist
cur = db.cursor()
select_query = "SELECT preorder_hash FROM namespaces WHERE preorder_hash = ? AND ((op = ?) OR (op = ? AND reveal_block < ?));"
args = (namespace_preorder_hash, NAMESPACE_READY, NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE)
ns_rows = namedb_query_execute( cur, select_query, args )
ns_row = ns_rows.fetchone()
if ns_row is not None:
# exists
return None
return preorder_rec | [
"def",
"namedb_get_namespace_preorder",
"(",
"db",
",",
"namespace_preorder_hash",
",",
"current_block",
")",
":",
"cur",
"=",
"db",
".",
"cursor",
"(",
")",
"select_query",
"=",
"\"SELECT * FROM preorders WHERE preorder_hash = ? AND op = ? AND block_number < ?;\"",
"args",
"=",
"(",
"namespace_preorder_hash",
",",
"NAMESPACE_PREORDER",
",",
"current_block",
"+",
"NAMESPACE_PREORDER_EXPIRE",
")",
"preorder_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"preorder_row",
"=",
"preorder_rows",
".",
"fetchone",
"(",
")",
"if",
"preorder_row",
"is",
"None",
":",
"# no such preorder ",
"return",
"None",
"preorder_rec",
"=",
"{",
"}",
"preorder_rec",
".",
"update",
"(",
"preorder_row",
")",
"# make sure that the namespace doesn't already exist ",
"cur",
"=",
"db",
".",
"cursor",
"(",
")",
"select_query",
"=",
"\"SELECT preorder_hash FROM namespaces WHERE preorder_hash = ? AND ((op = ?) OR (op = ? AND reveal_block < ?));\"",
"args",
"=",
"(",
"namespace_preorder_hash",
",",
"NAMESPACE_READY",
",",
"NAMESPACE_REVEAL",
",",
"current_block",
"+",
"NAMESPACE_REVEAL_EXPIRE",
")",
"ns_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"ns_row",
"=",
"ns_rows",
".",
"fetchone",
"(",
")",
"if",
"ns_row",
"is",
"not",
"None",
":",
"# exists",
"return",
"None",
"return",
"preorder_rec"
] | Get a namespace preorder, given its hash.
Return the preorder record on success.
Return None if not found, or if it expired, or if the namespace was revealed or readied. | [
"Get",
"a",
"namespace",
"preorder",
"given",
"its",
"hash",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2676-L2708 |
230,745 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_namespace_ready | def namedb_get_namespace_ready( cur, namespace_id, include_history=True ):
"""
Get a ready namespace, and optionally its history.
Only return a namespace if it is ready.
"""
select_query = "SELECT * FROM namespaces WHERE namespace_id = ? AND op = ?;"
namespace_rows = namedb_query_execute( cur, select_query, (namespace_id, NAMESPACE_READY))
namespace_row = namespace_rows.fetchone()
if namespace_row is None:
# no such namespace
return None
namespace = {}
namespace.update( namespace_row )
if include_history:
hist = namedb_get_history( cur, namespace_id )
namespace['history'] = hist
namespace = op_decanonicalize('NAMESPACE_READY', namespace)
return namespace | python | def namedb_get_namespace_ready( cur, namespace_id, include_history=True ):
"""
Get a ready namespace, and optionally its history.
Only return a namespace if it is ready.
"""
select_query = "SELECT * FROM namespaces WHERE namespace_id = ? AND op = ?;"
namespace_rows = namedb_query_execute( cur, select_query, (namespace_id, NAMESPACE_READY))
namespace_row = namespace_rows.fetchone()
if namespace_row is None:
# no such namespace
return None
namespace = {}
namespace.update( namespace_row )
if include_history:
hist = namedb_get_history( cur, namespace_id )
namespace['history'] = hist
namespace = op_decanonicalize('NAMESPACE_READY', namespace)
return namespace | [
"def",
"namedb_get_namespace_ready",
"(",
"cur",
",",
"namespace_id",
",",
"include_history",
"=",
"True",
")",
":",
"select_query",
"=",
"\"SELECT * FROM namespaces WHERE namespace_id = ? AND op = ?;\"",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"(",
"namespace_id",
",",
"NAMESPACE_READY",
")",
")",
"namespace_row",
"=",
"namespace_rows",
".",
"fetchone",
"(",
")",
"if",
"namespace_row",
"is",
"None",
":",
"# no such namespace ",
"return",
"None",
"namespace",
"=",
"{",
"}",
"namespace",
".",
"update",
"(",
"namespace_row",
")",
"if",
"include_history",
":",
"hist",
"=",
"namedb_get_history",
"(",
"cur",
",",
"namespace_id",
")",
"namespace",
"[",
"'history'",
"]",
"=",
"hist",
"namespace",
"=",
"op_decanonicalize",
"(",
"'NAMESPACE_READY'",
",",
"namespace",
")",
"return",
"namespace"
] | Get a ready namespace, and optionally its history.
Only return a namespace if it is ready. | [
"Get",
"a",
"ready",
"namespace",
"and",
"optionally",
"its",
"history",
".",
"Only",
"return",
"a",
"namespace",
"if",
"it",
"is",
"ready",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2740-L2762 |
230,746 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_name_from_name_hash128 | def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ):
"""
Given the hexlified 128-bit hash of a name, get the name.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE name_hash128 = ? AND revoked = 0 AND " + unexpired_query + ";"
args = (name_hash128,) + unexpired_args
name_rows = namedb_query_execute( cur, select_query, args )
name_row = name_rows.fetchone()
if name_row is None:
# no such namespace
return None
return name_row['name'] | python | def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ):
"""
Given the hexlified 128-bit hash of a name, get the name.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE name_hash128 = ? AND revoked = 0 AND " + unexpired_query + ";"
args = (name_hash128,) + unexpired_args
name_rows = namedb_query_execute( cur, select_query, args )
name_row = name_rows.fetchone()
if name_row is None:
# no such namespace
return None
return name_row['name'] | [
"def",
"namedb_get_name_from_name_hash128",
"(",
"cur",
",",
"name_hash128",
",",
"block_number",
")",
":",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"block_number",
")",
"select_query",
"=",
"\"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \"",
"+",
"\"WHERE name_hash128 = ? AND revoked = 0 AND \"",
"+",
"unexpired_query",
"+",
"\";\"",
"args",
"=",
"(",
"name_hash128",
",",
")",
"+",
"unexpired_args",
"name_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"name_row",
"=",
"name_rows",
".",
"fetchone",
"(",
")",
"if",
"name_row",
"is",
"None",
":",
"# no such namespace ",
"return",
"None",
"return",
"name_row",
"[",
"'name'",
"]"
] | Given the hexlified 128-bit hash of a name, get the name. | [
"Given",
"the",
"hexlified",
"128",
"-",
"bit",
"hash",
"of",
"a",
"name",
"get",
"the",
"name",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2765-L2783 |
230,747 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_names_with_value_hash | def namedb_get_names_with_value_hash( cur, value_hash, block_number ):
"""
Get the names with the given value hash. Only includes current, non-revoked names.
Return None if there are no names.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE value_hash = ? AND revoked = 0 AND " + unexpired_query + ";"
args = (value_hash,) + unexpired_args
name_rows = namedb_query_execute( cur, select_query, args )
names = []
for name_row in name_rows:
names.append( name_row['name'] )
if len(names) == 0:
return None
else:
return names | python | def namedb_get_names_with_value_hash( cur, value_hash, block_number ):
"""
Get the names with the given value hash. Only includes current, non-revoked names.
Return None if there are no names.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE value_hash = ? AND revoked = 0 AND " + unexpired_query + ";"
args = (value_hash,) + unexpired_args
name_rows = namedb_query_execute( cur, select_query, args )
names = []
for name_row in name_rows:
names.append( name_row['name'] )
if len(names) == 0:
return None
else:
return names | [
"def",
"namedb_get_names_with_value_hash",
"(",
"cur",
",",
"value_hash",
",",
"block_number",
")",
":",
"unexpired_query",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"block_number",
")",
"select_query",
"=",
"\"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \"",
"+",
"\"WHERE value_hash = ? AND revoked = 0 AND \"",
"+",
"unexpired_query",
"+",
"\";\"",
"args",
"=",
"(",
"value_hash",
",",
")",
"+",
"unexpired_args",
"name_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"names",
"=",
"[",
"]",
"for",
"name_row",
"in",
"name_rows",
":",
"names",
".",
"append",
"(",
"name_row",
"[",
"'name'",
"]",
")",
"if",
"len",
"(",
"names",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"names"
] | Get the names with the given value hash. Only includes current, non-revoked names.
Return None if there are no names. | [
"Get",
"the",
"names",
"with",
"the",
"given",
"value",
"hash",
".",
"Only",
"includes",
"current",
"non",
"-",
"revoked",
"names",
".",
"Return",
"None",
"if",
"there",
"are",
"no",
"names",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2786-L2806 |
230,748 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_value_hash_txids | def namedb_get_value_hash_txids(cur, value_hash):
"""
Get the list of txs that sent this value hash, ordered by block and vtxindex
"""
query = 'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;'
args = (value_hash,)
rows = namedb_query_execute(cur, query, args)
txids = []
for r in rows:
# present
txid = str(r['txid'])
txids.append(txid)
return txids | python | def namedb_get_value_hash_txids(cur, value_hash):
"""
Get the list of txs that sent this value hash, ordered by block and vtxindex
"""
query = 'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;'
args = (value_hash,)
rows = namedb_query_execute(cur, query, args)
txids = []
for r in rows:
# present
txid = str(r['txid'])
txids.append(txid)
return txids | [
"def",
"namedb_get_value_hash_txids",
"(",
"cur",
",",
"value_hash",
")",
":",
"query",
"=",
"'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;'",
"args",
"=",
"(",
"value_hash",
",",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"txids",
"=",
"[",
"]",
"for",
"r",
"in",
"rows",
":",
"# present",
"txid",
"=",
"str",
"(",
"r",
"[",
"'txid'",
"]",
")",
"txids",
".",
"append",
"(",
"txid",
")",
"return",
"txids"
] | Get the list of txs that sent this value hash, ordered by block and vtxindex | [
"Get",
"the",
"list",
"of",
"txs",
"that",
"sent",
"this",
"value",
"hash",
"ordered",
"by",
"block",
"and",
"vtxindex"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2809-L2824 |
230,749 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_get_num_block_vtxs | def namedb_get_num_block_vtxs( cur, block_number ):
"""
How many virtual transactions were processed for this block?
"""
select_query = "SELECT vtxindex FROM history WHERE history_id = ?;"
args = (block_number,)
rows = namedb_query_execute( cur, select_query, args )
count = 0
for r in rows:
count += 1
return count | python | def namedb_get_num_block_vtxs( cur, block_number ):
"""
How many virtual transactions were processed for this block?
"""
select_query = "SELECT vtxindex FROM history WHERE history_id = ?;"
args = (block_number,)
rows = namedb_query_execute( cur, select_query, args )
count = 0
for r in rows:
count += 1
return count | [
"def",
"namedb_get_num_block_vtxs",
"(",
"cur",
",",
"block_number",
")",
":",
"select_query",
"=",
"\"SELECT vtxindex FROM history WHERE history_id = ?;\"",
"args",
"=",
"(",
"block_number",
",",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"args",
")",
"count",
"=",
"0",
"for",
"r",
"in",
"rows",
":",
"count",
"+=",
"1",
"return",
"count"
] | How many virtual transactions were processed for this block? | [
"How",
"many",
"virtual",
"transactions",
"were",
"processed",
"for",
"this",
"block?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2827-L2839 |
230,750 | blockstack/blockstack-core | blockstack/lib/nameset/db.py | namedb_is_name_zonefile_hash | def namedb_is_name_zonefile_hash(cur, name, zonefile_hash):
"""
Determine if a zone file hash was sent by a name.
Return True if so, false if not
"""
select_query = 'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?'
select_args = (name,zonefile_hash)
rows = namedb_query_execute(cur, select_query, select_args)
count = None
for r in rows:
count = r['COUNT(value_hash)']
break
return count > 0 | python | def namedb_is_name_zonefile_hash(cur, name, zonefile_hash):
"""
Determine if a zone file hash was sent by a name.
Return True if so, false if not
"""
select_query = 'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?'
select_args = (name,zonefile_hash)
rows = namedb_query_execute(cur, select_query, select_args)
count = None
for r in rows:
count = r['COUNT(value_hash)']
break
return count > 0 | [
"def",
"namedb_is_name_zonefile_hash",
"(",
"cur",
",",
"name",
",",
"zonefile_hash",
")",
":",
"select_query",
"=",
"'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?'",
"select_args",
"=",
"(",
"name",
",",
"zonefile_hash",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"select_query",
",",
"select_args",
")",
"count",
"=",
"None",
"for",
"r",
"in",
"rows",
":",
"count",
"=",
"r",
"[",
"'COUNT(value_hash)'",
"]",
"break",
"return",
"count",
">",
"0"
] | Determine if a zone file hash was sent by a name.
Return True if so, false if not | [
"Determine",
"if",
"a",
"zone",
"file",
"hash",
"was",
"sent",
"by",
"a",
"name",
".",
"Return",
"True",
"if",
"so",
"false",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2842-L2857 |
230,751 | blockstack/blockstack-core | blockstack/lib/operations/announce.py | process_announcement | def process_announcement( sender_namerec, op, working_dir ):
"""
If the announcement is valid, then immediately record it.
"""
node_config = get_blockstack_opts()
# valid announcement
announce_hash = op['message_hash']
announcer_id = op['announcer_id']
# verify that it came from this individual
name_history = sender_namerec['history']
allowed_value_hashes = []
for block_height in name_history.keys():
for historic_namerec in name_history[block_height]:
if historic_namerec.get('value_hash'):
allowed_value_hashes.append(historic_namerec['value_hash'])
if announce_hash not in allowed_value_hashes:
# this individual did not send this announcement
log.warning("Announce hash {} not found in name history for {}".format(announce_hash, announcer_id))
return
# go get it from Atlas
zonefiles_dir = node_config.get('zonefiles', None)
if not zonefiles_dir:
log.warning("This node does not store zone files, so no announcement can be found")
return
announce_text = get_atlas_zonefile_data(announce_hash, zonefiles_dir)
if announce_text is None:
log.warning("No zone file {} found".format(announce_hash))
return
# go append it
log.critical("ANNOUNCEMENT (from %s): %s\n------BEGIN MESSAGE------\n%s\n------END MESSAGE------\n" % (announcer_id, announce_hash, announce_text))
store_announcement( working_dir, announce_hash, announce_text ) | python | def process_announcement( sender_namerec, op, working_dir ):
"""
If the announcement is valid, then immediately record it.
"""
node_config = get_blockstack_opts()
# valid announcement
announce_hash = op['message_hash']
announcer_id = op['announcer_id']
# verify that it came from this individual
name_history = sender_namerec['history']
allowed_value_hashes = []
for block_height in name_history.keys():
for historic_namerec in name_history[block_height]:
if historic_namerec.get('value_hash'):
allowed_value_hashes.append(historic_namerec['value_hash'])
if announce_hash not in allowed_value_hashes:
# this individual did not send this announcement
log.warning("Announce hash {} not found in name history for {}".format(announce_hash, announcer_id))
return
# go get it from Atlas
zonefiles_dir = node_config.get('zonefiles', None)
if not zonefiles_dir:
log.warning("This node does not store zone files, so no announcement can be found")
return
announce_text = get_atlas_zonefile_data(announce_hash, zonefiles_dir)
if announce_text is None:
log.warning("No zone file {} found".format(announce_hash))
return
# go append it
log.critical("ANNOUNCEMENT (from %s): %s\n------BEGIN MESSAGE------\n%s\n------END MESSAGE------\n" % (announcer_id, announce_hash, announce_text))
store_announcement( working_dir, announce_hash, announce_text ) | [
"def",
"process_announcement",
"(",
"sender_namerec",
",",
"op",
",",
"working_dir",
")",
":",
"node_config",
"=",
"get_blockstack_opts",
"(",
")",
"# valid announcement",
"announce_hash",
"=",
"op",
"[",
"'message_hash'",
"]",
"announcer_id",
"=",
"op",
"[",
"'announcer_id'",
"]",
"# verify that it came from this individual",
"name_history",
"=",
"sender_namerec",
"[",
"'history'",
"]",
"allowed_value_hashes",
"=",
"[",
"]",
"for",
"block_height",
"in",
"name_history",
".",
"keys",
"(",
")",
":",
"for",
"historic_namerec",
"in",
"name_history",
"[",
"block_height",
"]",
":",
"if",
"historic_namerec",
".",
"get",
"(",
"'value_hash'",
")",
":",
"allowed_value_hashes",
".",
"append",
"(",
"historic_namerec",
"[",
"'value_hash'",
"]",
")",
"if",
"announce_hash",
"not",
"in",
"allowed_value_hashes",
":",
"# this individual did not send this announcement",
"log",
".",
"warning",
"(",
"\"Announce hash {} not found in name history for {}\"",
".",
"format",
"(",
"announce_hash",
",",
"announcer_id",
")",
")",
"return",
"# go get it from Atlas",
"zonefiles_dir",
"=",
"node_config",
".",
"get",
"(",
"'zonefiles'",
",",
"None",
")",
"if",
"not",
"zonefiles_dir",
":",
"log",
".",
"warning",
"(",
"\"This node does not store zone files, so no announcement can be found\"",
")",
"return",
"announce_text",
"=",
"get_atlas_zonefile_data",
"(",
"announce_hash",
",",
"zonefiles_dir",
")",
"if",
"announce_text",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"No zone file {} found\"",
".",
"format",
"(",
"announce_hash",
")",
")",
"return",
"# go append it ",
"log",
".",
"critical",
"(",
"\"ANNOUNCEMENT (from %s): %s\\n------BEGIN MESSAGE------\\n%s\\n------END MESSAGE------\\n\"",
"%",
"(",
"announcer_id",
",",
"announce_hash",
",",
"announce_text",
")",
")",
"store_announcement",
"(",
"working_dir",
",",
"announce_hash",
",",
"announce_text",
")"
] | If the announcement is valid, then immediately record it. | [
"If",
"the",
"announcement",
"is",
"valid",
"then",
"immediately",
"record",
"it",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/announce.py#L39-L75 |
230,752 | blockstack/blockstack-core | blockstack/lib/operations/announce.py | check | def check( state_engine, nameop, block_id, checked_ops ):
"""
Log an announcement from the blockstack developers,
but first verify that it is correct.
Return True if the announcement came from the announce IDs whitelist
Return False otherwise
"""
sender = nameop['sender']
sending_blockchain_id = None
found = False
blockchain_namerec = None
for blockchain_id in state_engine.get_announce_ids():
blockchain_namerec = state_engine.get_name( blockchain_id )
if blockchain_namerec is None:
# this name doesn't exist yet, or is expired or revoked
continue
if str(sender) == str(blockchain_namerec['sender']):
# yup!
found = True
sending_blockchain_id = blockchain_id
break
if not found:
log.warning("Announcement not sent from our whitelist of blockchain IDs")
return False
nameop['announcer_id'] = sending_blockchain_id
process_announcement( blockchain_namerec, nameop, state_engine.working_dir )
return True | python | def check( state_engine, nameop, block_id, checked_ops ):
"""
Log an announcement from the blockstack developers,
but first verify that it is correct.
Return True if the announcement came from the announce IDs whitelist
Return False otherwise
"""
sender = nameop['sender']
sending_blockchain_id = None
found = False
blockchain_namerec = None
for blockchain_id in state_engine.get_announce_ids():
blockchain_namerec = state_engine.get_name( blockchain_id )
if blockchain_namerec is None:
# this name doesn't exist yet, or is expired or revoked
continue
if str(sender) == str(blockchain_namerec['sender']):
# yup!
found = True
sending_blockchain_id = blockchain_id
break
if not found:
log.warning("Announcement not sent from our whitelist of blockchain IDs")
return False
nameop['announcer_id'] = sending_blockchain_id
process_announcement( blockchain_namerec, nameop, state_engine.working_dir )
return True | [
"def",
"check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"sender",
"=",
"nameop",
"[",
"'sender'",
"]",
"sending_blockchain_id",
"=",
"None",
"found",
"=",
"False",
"blockchain_namerec",
"=",
"None",
"for",
"blockchain_id",
"in",
"state_engine",
".",
"get_announce_ids",
"(",
")",
":",
"blockchain_namerec",
"=",
"state_engine",
".",
"get_name",
"(",
"blockchain_id",
")",
"if",
"blockchain_namerec",
"is",
"None",
":",
"# this name doesn't exist yet, or is expired or revoked",
"continue",
"if",
"str",
"(",
"sender",
")",
"==",
"str",
"(",
"blockchain_namerec",
"[",
"'sender'",
"]",
")",
":",
"# yup!",
"found",
"=",
"True",
"sending_blockchain_id",
"=",
"blockchain_id",
"break",
"if",
"not",
"found",
":",
"log",
".",
"warning",
"(",
"\"Announcement not sent from our whitelist of blockchain IDs\"",
")",
"return",
"False",
"nameop",
"[",
"'announcer_id'",
"]",
"=",
"sending_blockchain_id",
"process_announcement",
"(",
"blockchain_namerec",
",",
"nameop",
",",
"state_engine",
".",
"working_dir",
")",
"return",
"True"
] | Log an announcement from the blockstack developers,
but first verify that it is correct.
Return True if the announcement came from the announce IDs whitelist
Return False otherwise | [
"Log",
"an",
"announcement",
"from",
"the",
"blockstack",
"developers",
"but",
"first",
"verify",
"that",
"it",
"is",
"correct",
".",
"Return",
"True",
"if",
"the",
"announcement",
"came",
"from",
"the",
"announce",
"IDs",
"whitelist",
"Return",
"False",
"otherwise"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/announce.py#L157-L188 |
230,753 | blockstack/blockstack-core | blockstack/lib/snv.py | get_bitcoind_client | def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_passwd']
return create_bitcoind_service_proxy(bitcoind_user, bitcoind_passwd, server=bitcoind_host, port=bitcoind_port) | python | def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_passwd']
return create_bitcoind_service_proxy(bitcoind_user, bitcoind_passwd, server=bitcoind_host, port=bitcoind_port) | [
"def",
"get_bitcoind_client",
"(",
")",
":",
"bitcoind_opts",
"=",
"get_bitcoin_opts",
"(",
")",
"bitcoind_host",
"=",
"bitcoind_opts",
"[",
"'bitcoind_server'",
"]",
"bitcoind_port",
"=",
"bitcoind_opts",
"[",
"'bitcoind_port'",
"]",
"bitcoind_user",
"=",
"bitcoind_opts",
"[",
"'bitcoind_user'",
"]",
"bitcoind_passwd",
"=",
"bitcoind_opts",
"[",
"'bitcoind_passwd'",
"]",
"return",
"create_bitcoind_service_proxy",
"(",
"bitcoind_user",
",",
"bitcoind_passwd",
",",
"server",
"=",
"bitcoind_host",
",",
"port",
"=",
"bitcoind_port",
")"
] | Connect to the bitcoind node | [
"Connect",
"to",
"the",
"bitcoind",
"node"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/snv.py#L58-L68 |
230,754 | blockstack/blockstack-core | blockstack/lib/snv.py | txid_to_block_data | def txid_to_block_data(txid, bitcoind_proxy, proxy=None):
"""
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error
"""
proxy = get_default_proxy() if proxy is None else proxy
timeout = 1.0
while True:
try:
untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1)
untrusted_block_hash = untrusted_tx_data['blockhash']
untrusted_block_data = bitcoind_proxy.getblock(untrusted_block_hash)
break
except (OSError, IOError) as ie:
log.exception(ie)
log.error('Network error; retrying...')
timeout = timeout * 2 + random.randint(0, timeout)
continue
except Exception as e:
log.exception(e)
return None, None, None
bitcoind_opts = get_bitcoin_opts()
spv_headers_path = bitcoind_opts['bitcoind_spv_path']
# first, can we trust this block? is it in the SPV headers?
untrusted_block_header_hex = virtualchain.block_header_to_hex(
untrusted_block_data, untrusted_block_data['previousblockhash']
)
block_id = SPVClient.block_header_index(
spv_headers_path,
('{}00'.format(untrusted_block_header_hex)).decode('hex')
)
if block_id < 0:
# bad header
log.error('Block header "{}" is not in the SPV headers ({})'.format(
untrusted_block_header_hex, spv_headers_path
))
return None, None, None
# block header is trusted. Is the transaction data consistent with it?
verified_block_header = virtualchain.block_verify(untrusted_block_data)
if not verified_block_header:
msg = (
'Block transaction IDs are not consistent '
'with the Merkle root of the trusted header'
)
log.error(msg)
return None, None, None
# verify block hash
verified_block_hash = virtualchain.block_header_verify(
untrusted_block_data, untrusted_block_data['previousblockhash'], untrusted_block_hash
)
if not verified_block_hash:
log.error('Block hash is not consistent with block header')
return None, None, None
# we trust the block hash, block data, and txids
block_hash = untrusted_block_hash
block_data = untrusted_block_data
tx_data = untrusted_tx_data
return block_hash, block_data, tx_data | python | def txid_to_block_data(txid, bitcoind_proxy, proxy=None):
"""
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error
"""
proxy = get_default_proxy() if proxy is None else proxy
timeout = 1.0
while True:
try:
untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1)
untrusted_block_hash = untrusted_tx_data['blockhash']
untrusted_block_data = bitcoind_proxy.getblock(untrusted_block_hash)
break
except (OSError, IOError) as ie:
log.exception(ie)
log.error('Network error; retrying...')
timeout = timeout * 2 + random.randint(0, timeout)
continue
except Exception as e:
log.exception(e)
return None, None, None
bitcoind_opts = get_bitcoin_opts()
spv_headers_path = bitcoind_opts['bitcoind_spv_path']
# first, can we trust this block? is it in the SPV headers?
untrusted_block_header_hex = virtualchain.block_header_to_hex(
untrusted_block_data, untrusted_block_data['previousblockhash']
)
block_id = SPVClient.block_header_index(
spv_headers_path,
('{}00'.format(untrusted_block_header_hex)).decode('hex')
)
if block_id < 0:
# bad header
log.error('Block header "{}" is not in the SPV headers ({})'.format(
untrusted_block_header_hex, spv_headers_path
))
return None, None, None
# block header is trusted. Is the transaction data consistent with it?
verified_block_header = virtualchain.block_verify(untrusted_block_data)
if not verified_block_header:
msg = (
'Block transaction IDs are not consistent '
'with the Merkle root of the trusted header'
)
log.error(msg)
return None, None, None
# verify block hash
verified_block_hash = virtualchain.block_header_verify(
untrusted_block_data, untrusted_block_data['previousblockhash'], untrusted_block_hash
)
if not verified_block_hash:
log.error('Block hash is not consistent with block header')
return None, None, None
# we trust the block hash, block data, and txids
block_hash = untrusted_block_hash
block_data = untrusted_block_data
tx_data = untrusted_tx_data
return block_hash, block_data, tx_data | [
"def",
"txid_to_block_data",
"(",
"txid",
",",
"bitcoind_proxy",
",",
"proxy",
"=",
"None",
")",
":",
"proxy",
"=",
"get_default_proxy",
"(",
")",
"if",
"proxy",
"is",
"None",
"else",
"proxy",
"timeout",
"=",
"1.0",
"while",
"True",
":",
"try",
":",
"untrusted_tx_data",
"=",
"bitcoind_proxy",
".",
"getrawtransaction",
"(",
"txid",
",",
"1",
")",
"untrusted_block_hash",
"=",
"untrusted_tx_data",
"[",
"'blockhash'",
"]",
"untrusted_block_data",
"=",
"bitcoind_proxy",
".",
"getblock",
"(",
"untrusted_block_hash",
")",
"break",
"except",
"(",
"OSError",
",",
"IOError",
")",
"as",
"ie",
":",
"log",
".",
"exception",
"(",
"ie",
")",
"log",
".",
"error",
"(",
"'Network error; retrying...'",
")",
"timeout",
"=",
"timeout",
"*",
"2",
"+",
"random",
".",
"randint",
"(",
"0",
",",
"timeout",
")",
"continue",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"None",
",",
"None",
",",
"None",
"bitcoind_opts",
"=",
"get_bitcoin_opts",
"(",
")",
"spv_headers_path",
"=",
"bitcoind_opts",
"[",
"'bitcoind_spv_path'",
"]",
"# first, can we trust this block? is it in the SPV headers?",
"untrusted_block_header_hex",
"=",
"virtualchain",
".",
"block_header_to_hex",
"(",
"untrusted_block_data",
",",
"untrusted_block_data",
"[",
"'previousblockhash'",
"]",
")",
"block_id",
"=",
"SPVClient",
".",
"block_header_index",
"(",
"spv_headers_path",
",",
"(",
"'{}00'",
".",
"format",
"(",
"untrusted_block_header_hex",
")",
")",
".",
"decode",
"(",
"'hex'",
")",
")",
"if",
"block_id",
"<",
"0",
":",
"# bad header",
"log",
".",
"error",
"(",
"'Block header \"{}\" is not in the SPV headers ({})'",
".",
"format",
"(",
"untrusted_block_header_hex",
",",
"spv_headers_path",
")",
")",
"return",
"None",
",",
"None",
",",
"None",
"# block header is trusted. Is the transaction data consistent with it?",
"verified_block_header",
"=",
"virtualchain",
".",
"block_verify",
"(",
"untrusted_block_data",
")",
"if",
"not",
"verified_block_header",
":",
"msg",
"=",
"(",
"'Block transaction IDs are not consistent '",
"'with the Merkle root of the trusted header'",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"None",
",",
"None",
",",
"None",
"# verify block hash",
"verified_block_hash",
"=",
"virtualchain",
".",
"block_header_verify",
"(",
"untrusted_block_data",
",",
"untrusted_block_data",
"[",
"'previousblockhash'",
"]",
",",
"untrusted_block_hash",
")",
"if",
"not",
"verified_block_hash",
":",
"log",
".",
"error",
"(",
"'Block hash is not consistent with block header'",
")",
"return",
"None",
",",
"None",
",",
"None",
"# we trust the block hash, block data, and txids",
"block_hash",
"=",
"untrusted_block_hash",
"block_data",
"=",
"untrusted_block_data",
"tx_data",
"=",
"untrusted_tx_data",
"return",
"block_hash",
",",
"block_data",
",",
"tx_data"
] | Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error | [
"Given",
"a",
"txid",
"get",
"its",
"block",
"s",
"data",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/snv.py#L71-L150 |
230,755 | blockstack/blockstack-core | blockstack/lib/snv.py | get_consensus_hash_from_tx | def get_consensus_hash_from_tx(tx):
"""
Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error.
"""
opcode, payload = parse_tx_op_return(tx)
if opcode is None or payload is None:
return None
# only present in NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER
if opcode in [NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER]:
consensus_hash = payload[-16:].encode('hex')
return consensus_hash
msg = (
'Blockchain ID transaction is not a '
'NAME_PREORDER, NAMESPACE_PROERDER or NAME_TRANSFER'
)
log.error(msg)
return None | python | def get_consensus_hash_from_tx(tx):
"""
Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error.
"""
opcode, payload = parse_tx_op_return(tx)
if opcode is None or payload is None:
return None
# only present in NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER
if opcode in [NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER]:
consensus_hash = payload[-16:].encode('hex')
return consensus_hash
msg = (
'Blockchain ID transaction is not a '
'NAME_PREORDER, NAMESPACE_PROERDER or NAME_TRANSFER'
)
log.error(msg)
return None | [
"def",
"get_consensus_hash_from_tx",
"(",
"tx",
")",
":",
"opcode",
",",
"payload",
"=",
"parse_tx_op_return",
"(",
"tx",
")",
"if",
"opcode",
"is",
"None",
"or",
"payload",
"is",
"None",
":",
"return",
"None",
"# only present in NAME_PREORDER, NAMESPACE_PREORDER, NAME_TRANSFER",
"if",
"opcode",
"in",
"[",
"NAME_PREORDER",
",",
"NAMESPACE_PREORDER",
",",
"NAME_TRANSFER",
"]",
":",
"consensus_hash",
"=",
"payload",
"[",
"-",
"16",
":",
"]",
".",
"encode",
"(",
"'hex'",
")",
"return",
"consensus_hash",
"msg",
"=",
"(",
"'Blockchain ID transaction is not a '",
"'NAME_PREORDER, NAMESPACE_PROERDER or NAME_TRANSFER'",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"None"
] | Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error. | [
"Given",
"an",
"SPV",
"-",
"verified",
"transaction",
"extract",
"its",
"consensus",
"hash",
".",
"Only",
"works",
"of",
"the",
"tx",
"encodes",
"a",
"NAME_PREORDER",
"NAMESPACE_PREORDER",
"or",
"NAME_TRANSFER",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/snv.py#L278-L304 |
230,756 | blockstack/blockstack-core | blockstack/lib/client.py | json_is_exception | def json_is_exception(resp):
"""
Is the given response object
an exception traceback?
Return True if so
Return False if not
"""
if not json_is_error(resp):
return False
if 'traceback' not in resp.keys() or 'error' not in resp.keys():
return False
return True | python | def json_is_exception(resp):
"""
Is the given response object
an exception traceback?
Return True if so
Return False if not
"""
if not json_is_error(resp):
return False
if 'traceback' not in resp.keys() or 'error' not in resp.keys():
return False
return True | [
"def",
"json_is_exception",
"(",
"resp",
")",
":",
"if",
"not",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"False",
"if",
"'traceback'",
"not",
"in",
"resp",
".",
"keys",
"(",
")",
"or",
"'error'",
"not",
"in",
"resp",
".",
"keys",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Is the given response object
an exception traceback?
Return True if so
Return False if not | [
"Is",
"the",
"given",
"response",
"object",
"an",
"exception",
"traceback?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L240-L254 |
230,757 | blockstack/blockstack-core | blockstack/lib/client.py | put_zonefiles | def put_zonefiles(hostport, zonefile_data_list, timeout=30, my_hostport=None, proxy=None):
"""
Push one or more zonefiles to the given server.
Each zone file in the list must be base64-encoded
Return {'status': True, 'saved': [...]} on success
Return {'error': ...} on error
"""
assert hostport or proxy, 'need either hostport or proxy'
saved_schema = {
'type': 'object',
'properties': {
'saved': {
'type': 'array',
'items': {
'type': 'integer',
'minimum': 0,
'maximum': 1,
},
'minItems': len(zonefile_data_list),
'maxItems': len(zonefile_data_list)
},
},
'required': [
'saved'
]
}
schema = json_response_schema( saved_schema )
if proxy is None:
proxy = connect_hostport(hostport)
push_info = None
try:
push_info = proxy.put_zonefiles(zonefile_data_list)
push_info = json_validate(schema, push_info)
if json_is_error(push_info):
return push_info
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except ValidationError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return push_info | python | def put_zonefiles(hostport, zonefile_data_list, timeout=30, my_hostport=None, proxy=None):
"""
Push one or more zonefiles to the given server.
Each zone file in the list must be base64-encoded
Return {'status': True, 'saved': [...]} on success
Return {'error': ...} on error
"""
assert hostport or proxy, 'need either hostport or proxy'
saved_schema = {
'type': 'object',
'properties': {
'saved': {
'type': 'array',
'items': {
'type': 'integer',
'minimum': 0,
'maximum': 1,
},
'minItems': len(zonefile_data_list),
'maxItems': len(zonefile_data_list)
},
},
'required': [
'saved'
]
}
schema = json_response_schema( saved_schema )
if proxy is None:
proxy = connect_hostport(hostport)
push_info = None
try:
push_info = proxy.put_zonefiles(zonefile_data_list)
push_info = json_validate(schema, push_info)
if json_is_error(push_info):
return push_info
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except ValidationError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return push_info | [
"def",
"put_zonefiles",
"(",
"hostport",
",",
"zonefile_data_list",
",",
"timeout",
"=",
"30",
",",
"my_hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"assert",
"hostport",
"or",
"proxy",
",",
"'need either hostport or proxy'",
"saved_schema",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'saved'",
":",
"{",
"'type'",
":",
"'array'",
",",
"'items'",
":",
"{",
"'type'",
":",
"'integer'",
",",
"'minimum'",
":",
"0",
",",
"'maximum'",
":",
"1",
",",
"}",
",",
"'minItems'",
":",
"len",
"(",
"zonefile_data_list",
")",
",",
"'maxItems'",
":",
"len",
"(",
"zonefile_data_list",
")",
"}",
",",
"}",
",",
"'required'",
":",
"[",
"'saved'",
"]",
"}",
"schema",
"=",
"json_response_schema",
"(",
"saved_schema",
")",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",
"(",
"hostport",
")",
"push_info",
"=",
"None",
"try",
":",
"push_info",
"=",
"proxy",
".",
"put_zonefiles",
"(",
"zonefile_data_list",
")",
"push_info",
"=",
"json_validate",
"(",
"schema",
",",
"push_info",
")",
"if",
"json_is_error",
"(",
"push_info",
")",
":",
"return",
"push_info",
"except",
"socket",
".",
"timeout",
":",
"log",
".",
"error",
"(",
"\"Connection timed out\"",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host timed out.'",
",",
"'http_status'",
":",
"503",
"}",
"return",
"resp",
"except",
"socket",
".",
"error",
"as",
"se",
":",
"log",
".",
"error",
"(",
"\"Connection error {}\"",
".",
"format",
"(",
"se",
".",
"errno",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host failed.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"ValidationError",
"as",
"e",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"e",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"Exception",
"as",
"ee",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ee",
")",
"log",
".",
"error",
"(",
"\"Caught exception while connecting to Blockstack node: {}\"",
".",
"format",
"(",
"ee",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Failed to contact Blockstack node. Try again with `--debug`.'",
",",
"'http_status'",
":",
"500",
"}",
"return",
"resp",
"return",
"push_info"
] | Push one or more zonefiles to the given server.
Each zone file in the list must be base64-encoded
Return {'status': True, 'saved': [...]} on success
Return {'error': ...} on error | [
"Push",
"one",
"or",
"more",
"zonefiles",
"to",
"the",
"given",
"server",
".",
"Each",
"zone",
"file",
"in",
"the",
"list",
"must",
"be",
"base64",
"-",
"encoded"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L879-L945 |
230,758 | blockstack/blockstack-core | blockstack/lib/client.py | get_zonefiles_by_block | def get_zonefiles_by_block(from_block, to_block, hostport=None, proxy=None):
"""
Get zonefile information for zonefiles announced in [@from_block, @to_block]
Returns { 'last_block' : server's last seen block,
'zonefile_info' : [ { 'zonefile_hash' : '...',
'txid' : '...',
'block_height' : '...' } ] }
"""
assert hostport or proxy, 'need either hostport or proxy'
if proxy is None:
proxy = connect_hostport(hostport)
zonefile_info_schema = {
'type' : 'array',
'items' : {
'type' : 'object',
'properties' : {
'name' : {'type' : 'string'},
'zonefile_hash' : { 'type' : 'string',
'pattern' : OP_ZONEFILE_HASH_PATTERN },
'txid' : {'type' : 'string',
'pattern' : OP_TXID_PATTERN},
'block_height' : {'type' : 'integer'}
},
'required' : [ 'zonefile_hash', 'txid', 'block_height' ]
}
}
response_schema = {
'type' : 'object',
'properties' : {
'lastblock' : {'type' : 'integer'},
'zonefile_info' : zonefile_info_schema
},
'required' : ['lastblock', 'zonefile_info']
}
offset = 0
output_zonefiles = []
last_server_block = 0
resp = {'zonefile_info': []}
while offset == 0 or len(resp['zonefile_info']) > 0:
resp = proxy.get_zonefiles_by_block(from_block, to_block, offset, 100)
if 'error' in resp:
return resp
resp = json_validate(response_schema, resp)
if json_is_error(resp):
return resp
output_zonefiles += resp['zonefile_info']
offset += 100
last_server_block = max(resp['lastblock'], last_server_block)
return { 'last_block' : last_server_block,
'zonefile_info' : output_zonefiles } | python | def get_zonefiles_by_block(from_block, to_block, hostport=None, proxy=None):
"""
Get zonefile information for zonefiles announced in [@from_block, @to_block]
Returns { 'last_block' : server's last seen block,
'zonefile_info' : [ { 'zonefile_hash' : '...',
'txid' : '...',
'block_height' : '...' } ] }
"""
assert hostport or proxy, 'need either hostport or proxy'
if proxy is None:
proxy = connect_hostport(hostport)
zonefile_info_schema = {
'type' : 'array',
'items' : {
'type' : 'object',
'properties' : {
'name' : {'type' : 'string'},
'zonefile_hash' : { 'type' : 'string',
'pattern' : OP_ZONEFILE_HASH_PATTERN },
'txid' : {'type' : 'string',
'pattern' : OP_TXID_PATTERN},
'block_height' : {'type' : 'integer'}
},
'required' : [ 'zonefile_hash', 'txid', 'block_height' ]
}
}
response_schema = {
'type' : 'object',
'properties' : {
'lastblock' : {'type' : 'integer'},
'zonefile_info' : zonefile_info_schema
},
'required' : ['lastblock', 'zonefile_info']
}
offset = 0
output_zonefiles = []
last_server_block = 0
resp = {'zonefile_info': []}
while offset == 0 or len(resp['zonefile_info']) > 0:
resp = proxy.get_zonefiles_by_block(from_block, to_block, offset, 100)
if 'error' in resp:
return resp
resp = json_validate(response_schema, resp)
if json_is_error(resp):
return resp
output_zonefiles += resp['zonefile_info']
offset += 100
last_server_block = max(resp['lastblock'], last_server_block)
return { 'last_block' : last_server_block,
'zonefile_info' : output_zonefiles } | [
"def",
"get_zonefiles_by_block",
"(",
"from_block",
",",
"to_block",
",",
"hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"assert",
"hostport",
"or",
"proxy",
",",
"'need either hostport or proxy'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",
"(",
"hostport",
")",
"zonefile_info_schema",
"=",
"{",
"'type'",
":",
"'array'",
",",
"'items'",
":",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'name'",
":",
"{",
"'type'",
":",
"'string'",
"}",
",",
"'zonefile_hash'",
":",
"{",
"'type'",
":",
"'string'",
",",
"'pattern'",
":",
"OP_ZONEFILE_HASH_PATTERN",
"}",
",",
"'txid'",
":",
"{",
"'type'",
":",
"'string'",
",",
"'pattern'",
":",
"OP_TXID_PATTERN",
"}",
",",
"'block_height'",
":",
"{",
"'type'",
":",
"'integer'",
"}",
"}",
",",
"'required'",
":",
"[",
"'zonefile_hash'",
",",
"'txid'",
",",
"'block_height'",
"]",
"}",
"}",
"response_schema",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'lastblock'",
":",
"{",
"'type'",
":",
"'integer'",
"}",
",",
"'zonefile_info'",
":",
"zonefile_info_schema",
"}",
",",
"'required'",
":",
"[",
"'lastblock'",
",",
"'zonefile_info'",
"]",
"}",
"offset",
"=",
"0",
"output_zonefiles",
"=",
"[",
"]",
"last_server_block",
"=",
"0",
"resp",
"=",
"{",
"'zonefile_info'",
":",
"[",
"]",
"}",
"while",
"offset",
"==",
"0",
"or",
"len",
"(",
"resp",
"[",
"'zonefile_info'",
"]",
")",
">",
"0",
":",
"resp",
"=",
"proxy",
".",
"get_zonefiles_by_block",
"(",
"from_block",
",",
"to_block",
",",
"offset",
",",
"100",
")",
"if",
"'error'",
"in",
"resp",
":",
"return",
"resp",
"resp",
"=",
"json_validate",
"(",
"response_schema",
",",
"resp",
")",
"if",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"resp",
"output_zonefiles",
"+=",
"resp",
"[",
"'zonefile_info'",
"]",
"offset",
"+=",
"100",
"last_server_block",
"=",
"max",
"(",
"resp",
"[",
"'lastblock'",
"]",
",",
"last_server_block",
")",
"return",
"{",
"'last_block'",
":",
"last_server_block",
",",
"'zonefile_info'",
":",
"output_zonefiles",
"}"
] | Get zonefile information for zonefiles announced in [@from_block, @to_block]
Returns { 'last_block' : server's last seen block,
'zonefile_info' : [ { 'zonefile_hash' : '...',
'txid' : '...',
'block_height' : '...' } ] } | [
"Get",
"zonefile",
"information",
"for",
"zonefiles",
"announced",
"in",
"["
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L948-L1005 |
230,759 | blockstack/blockstack-core | blockstack/lib/client.py | get_account_tokens | def get_account_tokens(address, hostport=None, proxy=None):
"""
Get the types of tokens that an address owns
Returns a list of token types
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
tokens_schema = {
'type': 'object',
'properties': {
'token_types': {
'type': 'array',
'pattern': '^(.+){1,19}',
},
},
'required': [
'token_types',
]
}
schema = json_response_schema(tokens_schema)
try:
resp = proxy.get_account_tokens(address)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except AssertionError as ae:
if BLOCKSTACK_DEBUG:
log.exception(ae)
resp = json_traceback(resp.get('error'))
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
resp['token_types'].sort()
return resp['token_types'] | python | def get_account_tokens(address, hostport=None, proxy=None):
"""
Get the types of tokens that an address owns
Returns a list of token types
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
tokens_schema = {
'type': 'object',
'properties': {
'token_types': {
'type': 'array',
'pattern': '^(.+){1,19}',
},
},
'required': [
'token_types',
]
}
schema = json_response_schema(tokens_schema)
try:
resp = proxy.get_account_tokens(address)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except AssertionError as ae:
if BLOCKSTACK_DEBUG:
log.exception(ae)
resp = json_traceback(resp.get('error'))
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
resp['token_types'].sort()
return resp['token_types'] | [
"def",
"get_account_tokens",
"(",
"address",
",",
"hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",
"(",
"hostport",
")",
"tokens_schema",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'token_types'",
":",
"{",
"'type'",
":",
"'array'",
",",
"'pattern'",
":",
"'^(.+){1,19}'",
",",
"}",
",",
"}",
",",
"'required'",
":",
"[",
"'token_types'",
",",
"]",
"}",
"schema",
"=",
"json_response_schema",
"(",
"tokens_schema",
")",
"try",
":",
"resp",
"=",
"proxy",
".",
"get_account_tokens",
"(",
"address",
")",
"resp",
"=",
"json_validate",
"(",
"schema",
",",
"resp",
")",
"if",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"resp",
"except",
"ValidationError",
"as",
"ve",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ve",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"socket",
".",
"timeout",
":",
"log",
".",
"error",
"(",
"\"Connection timed out\"",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host timed out.'",
",",
"'http_status'",
":",
"503",
"}",
"return",
"resp",
"except",
"socket",
".",
"error",
"as",
"se",
":",
"log",
".",
"error",
"(",
"\"Connection error {}\"",
".",
"format",
"(",
"se",
".",
"errno",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host failed.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"AssertionError",
"as",
"ae",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ae",
")",
"resp",
"=",
"json_traceback",
"(",
"resp",
".",
"get",
"(",
"'error'",
")",
")",
"return",
"resp",
"except",
"Exception",
"as",
"ee",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ee",
")",
"log",
".",
"error",
"(",
"\"Caught exception while connecting to Blockstack node: {}\"",
".",
"format",
"(",
"ee",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Failed to contact Blockstack node. Try again with `--debug`.'",
",",
"'http_status'",
":",
"500",
"}",
"return",
"resp",
"resp",
"[",
"'token_types'",
"]",
".",
"sort",
"(",
")",
"return",
"resp",
"[",
"'token_types'",
"]"
] | Get the types of tokens that an address owns
Returns a list of token types | [
"Get",
"the",
"types",
"of",
"tokens",
"that",
"an",
"address",
"owns",
"Returns",
"a",
"list",
"of",
"token",
"types"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L1378-L1441 |
230,760 | blockstack/blockstack-core | blockstack/lib/client.py | get_account_balance | def get_account_balance(address, token_type, hostport=None, proxy=None):
"""
Get the balance of an account for a particular token
Returns an int
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
balance_schema = {
'type': 'object',
'properties': {
'balance': {
'type': 'integer',
},
},
'required': [
'balance',
],
}
schema = json_response_schema(balance_schema)
try:
resp = proxy.get_account_balance(address, token_type)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
except ValidationError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return resp['balance'] | python | def get_account_balance(address, token_type, hostport=None, proxy=None):
"""
Get the balance of an account for a particular token
Returns an int
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
balance_schema = {
'type': 'object',
'properties': {
'balance': {
'type': 'integer',
},
},
'required': [
'balance',
],
}
schema = json_response_schema(balance_schema)
try:
resp = proxy.get_account_balance(address, token_type)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
except ValidationError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return resp['balance'] | [
"def",
"get_account_balance",
"(",
"address",
",",
"token_type",
",",
"hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",
"(",
"hostport",
")",
"balance_schema",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'balance'",
":",
"{",
"'type'",
":",
"'integer'",
",",
"}",
",",
"}",
",",
"'required'",
":",
"[",
"'balance'",
",",
"]",
",",
"}",
"schema",
"=",
"json_response_schema",
"(",
"balance_schema",
")",
"try",
":",
"resp",
"=",
"proxy",
".",
"get_account_balance",
"(",
"address",
",",
"token_type",
")",
"resp",
"=",
"json_validate",
"(",
"schema",
",",
"resp",
")",
"if",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"resp",
"except",
"ValidationError",
"as",
"e",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"e",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"socket",
".",
"timeout",
":",
"log",
".",
"error",
"(",
"\"Connection timed out\"",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host timed out.'",
",",
"'http_status'",
":",
"503",
"}",
"return",
"resp",
"except",
"socket",
".",
"error",
"as",
"se",
":",
"log",
".",
"error",
"(",
"\"Connection error {}\"",
".",
"format",
"(",
"se",
".",
"errno",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host failed.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"Exception",
"as",
"ee",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ee",
")",
"log",
".",
"error",
"(",
"\"Caught exception while connecting to Blockstack node: {}\"",
".",
"format",
"(",
"ee",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Failed to contact Blockstack node. Try again with `--debug`.'",
",",
"'http_status'",
":",
"500",
"}",
"return",
"resp",
"return",
"resp",
"[",
"'balance'",
"]"
] | Get the balance of an account for a particular token
Returns an int | [
"Get",
"the",
"balance",
"of",
"an",
"account",
"for",
"a",
"particular",
"token",
"Returns",
"an",
"int"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L1504-L1558 |
230,761 | blockstack/blockstack-core | blockstack/lib/client.py | get_name_DID | def get_name_DID(name, proxy=None, hostport=None):
"""
Get the DID for a name or subdomain
Return the DID string on success
Return None if not found
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
did_schema = {
'type': 'object',
'properties': {
'did': {
'type': 'string'
}
},
'required': [ 'did' ],
}
schema = json_response_schema(did_schema)
resp = {}
try:
resp = proxy.get_name_DID(name)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
# DID must be well-formed
assert parse_DID(resp['did'])
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except AssertionError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server replied an unparseable DID'}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return resp['did'] | python | def get_name_DID(name, proxy=None, hostport=None):
"""
Get the DID for a name or subdomain
Return the DID string on success
Return None if not found
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
did_schema = {
'type': 'object',
'properties': {
'did': {
'type': 'string'
}
},
'required': [ 'did' ],
}
schema = json_response_schema(did_schema)
resp = {}
try:
resp = proxy.get_name_DID(name)
resp = json_validate(schema, resp)
if json_is_error(resp):
return resp
# DID must be well-formed
assert parse_DID(resp['did'])
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
resp = {'error': 'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
return resp
except AssertionError as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
resp = {'error': 'Server replied an unparseable DID'}
return resp
except socket.timeout:
log.error("Connection timed out")
resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
return resp
except socket.error as se:
log.error("Connection error {}".format(se.errno))
resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
return resp
except Exception as ee:
if BLOCKSTACK_DEBUG:
log.exception(ee)
log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
resp = {'error': 'Failed to contact Blockstack node. Try again with `--debug`.', 'http_status': 500}
return resp
return resp['did'] | [
"def",
"get_name_DID",
"(",
"name",
",",
"proxy",
"=",
"None",
",",
"hostport",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=",
"connect_hostport",
"(",
"hostport",
")",
"did_schema",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'properties'",
":",
"{",
"'did'",
":",
"{",
"'type'",
":",
"'string'",
"}",
"}",
",",
"'required'",
":",
"[",
"'did'",
"]",
",",
"}",
"schema",
"=",
"json_response_schema",
"(",
"did_schema",
")",
"resp",
"=",
"{",
"}",
"try",
":",
"resp",
"=",
"proxy",
".",
"get_name_DID",
"(",
"name",
")",
"resp",
"=",
"json_validate",
"(",
"schema",
",",
"resp",
")",
"if",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"resp",
"# DID must be well-formed",
"assert",
"parse_DID",
"(",
"resp",
"[",
"'did'",
"]",
")",
"except",
"ValidationError",
"as",
"ve",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ve",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Server response did not match expected schema. You are likely communicating with an out-of-date Blockstack node.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"AssertionError",
"as",
"e",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"e",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Server replied an unparseable DID'",
"}",
"return",
"resp",
"except",
"socket",
".",
"timeout",
":",
"log",
".",
"error",
"(",
"\"Connection timed out\"",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host timed out.'",
",",
"'http_status'",
":",
"503",
"}",
"return",
"resp",
"except",
"socket",
".",
"error",
"as",
"se",
":",
"log",
".",
"error",
"(",
"\"Connection error {}\"",
".",
"format",
"(",
"se",
".",
"errno",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Connection to remote host failed.'",
",",
"'http_status'",
":",
"502",
"}",
"return",
"resp",
"except",
"Exception",
"as",
"ee",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ee",
")",
"log",
".",
"error",
"(",
"\"Caught exception while connecting to Blockstack node: {}\"",
".",
"format",
"(",
"ee",
")",
")",
"resp",
"=",
"{",
"'error'",
":",
"'Failed to contact Blockstack node. Try again with `--debug`.'",
",",
"'http_status'",
":",
"500",
"}",
"return",
"resp",
"return",
"resp",
"[",
"'did'",
"]"
] | Get the DID for a name or subdomain
Return the DID string on success
Return None if not found | [
"Get",
"the",
"DID",
"for",
"a",
"name",
"or",
"subdomain",
"Return",
"the",
"DID",
"string",
"on",
"success",
"Return",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L2473-L2536 |
230,762 | blockstack/blockstack-core | blockstack/lib/client.py | get_JWT | def get_JWT(url, address=None):
"""
Given a URL, fetch and decode the JWT it points to.
If address is given, then authenticate the JWT with the address.
Return None if we could not fetch it, or unable to authenticate it.
NOTE: the URL must be usable by the requests library
"""
jwt_txt = None
jwt = None
log.debug("Try {}".format(url))
# special case: handle file://
urlinfo = urllib2.urlparse.urlparse(url)
if urlinfo.scheme == 'file':
# points to a path on disk
try:
with open(urlinfo.path, 'r') as f:
jwt_txt = f.read()
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Failed to read {}".format(url))
return None
else:
# http(s) URL or similar
try:
resp = requests.get(url)
assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
jwt_txt = resp.text
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Unable to resolve {}".format(url))
return None
try:
# one of two things are possible:
# * this is a JWT string
# * this is a serialized JSON string whose first item is a dict that has 'token' as key,
# and that key is a JWT string.
try:
jwt_txt = json.loads(jwt_txt)[0]['token']
except:
pass
jwt = jsontokens.decode_token(jwt_txt)
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Unable to decode token at {}".format(url))
return None
try:
# must be well-formed
assert isinstance(jwt, dict)
assert 'payload' in jwt, jwt
assert isinstance(jwt['payload'], dict)
assert 'issuer' in jwt['payload'], jwt
assert isinstance(jwt['payload']['issuer'], dict)
assert 'publicKey' in jwt['payload']['issuer'], jwt
assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))
except AssertionError as ae:
if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
log.exception(ae)
log.warning("JWT at {} is malformed".format(url))
return None
if address is not None:
public_key = str(jwt['payload']['issuer']['publicKey'])
addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]
if virtualchain.address_reencode(address) not in addrs:
# got a JWT, but it doesn't match the address
log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
return None
verifier = jsontokens.TokenVerifier()
if not verifier.verify(jwt_txt, public_key):
# got a JWT, and the address matches, but the signature does not
log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
return None
return jwt | python | def get_JWT(url, address=None):
"""
Given a URL, fetch and decode the JWT it points to.
If address is given, then authenticate the JWT with the address.
Return None if we could not fetch it, or unable to authenticate it.
NOTE: the URL must be usable by the requests library
"""
jwt_txt = None
jwt = None
log.debug("Try {}".format(url))
# special case: handle file://
urlinfo = urllib2.urlparse.urlparse(url)
if urlinfo.scheme == 'file':
# points to a path on disk
try:
with open(urlinfo.path, 'r') as f:
jwt_txt = f.read()
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Failed to read {}".format(url))
return None
else:
# http(s) URL or similar
try:
resp = requests.get(url)
assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
jwt_txt = resp.text
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Unable to resolve {}".format(url))
return None
try:
# one of two things are possible:
# * this is a JWT string
# * this is a serialized JSON string whose first item is a dict that has 'token' as key,
# and that key is a JWT string.
try:
jwt_txt = json.loads(jwt_txt)[0]['token']
except:
pass
jwt = jsontokens.decode_token(jwt_txt)
except Exception as e:
if BLOCKSTACK_TEST:
log.exception(e)
log.warning("Unable to decode token at {}".format(url))
return None
try:
# must be well-formed
assert isinstance(jwt, dict)
assert 'payload' in jwt, jwt
assert isinstance(jwt['payload'], dict)
assert 'issuer' in jwt['payload'], jwt
assert isinstance(jwt['payload']['issuer'], dict)
assert 'publicKey' in jwt['payload']['issuer'], jwt
assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))
except AssertionError as ae:
if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
log.exception(ae)
log.warning("JWT at {} is malformed".format(url))
return None
if address is not None:
public_key = str(jwt['payload']['issuer']['publicKey'])
addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]
if virtualchain.address_reencode(address) not in addrs:
# got a JWT, but it doesn't match the address
log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
return None
verifier = jsontokens.TokenVerifier()
if not verifier.verify(jwt_txt, public_key):
# got a JWT, and the address matches, but the signature does not
log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
return None
return jwt | [
"def",
"get_JWT",
"(",
"url",
",",
"address",
"=",
"None",
")",
":",
"jwt_txt",
"=",
"None",
"jwt",
"=",
"None",
"log",
".",
"debug",
"(",
"\"Try {}\"",
".",
"format",
"(",
"url",
")",
")",
"# special case: handle file://",
"urlinfo",
"=",
"urllib2",
".",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"if",
"urlinfo",
".",
"scheme",
"==",
"'file'",
":",
"# points to a path on disk",
"try",
":",
"with",
"open",
"(",
"urlinfo",
".",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"jwt_txt",
"=",
"f",
".",
"read",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"warning",
"(",
"\"Failed to read {}\"",
".",
"format",
"(",
"url",
")",
")",
"return",
"None",
"else",
":",
"# http(s) URL or similar",
"try",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"assert",
"resp",
".",
"status_code",
"==",
"200",
",",
"'Bad status code on {}: {}'",
".",
"format",
"(",
"url",
",",
"resp",
".",
"status_code",
")",
"jwt_txt",
"=",
"resp",
".",
"text",
"except",
"Exception",
"as",
"e",
":",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"warning",
"(",
"\"Unable to resolve {}\"",
".",
"format",
"(",
"url",
")",
")",
"return",
"None",
"try",
":",
"# one of two things are possible:",
"# * this is a JWT string",
"# * this is a serialized JSON string whose first item is a dict that has 'token' as key,",
"# and that key is a JWT string.",
"try",
":",
"jwt_txt",
"=",
"json",
".",
"loads",
"(",
"jwt_txt",
")",
"[",
"0",
"]",
"[",
"'token'",
"]",
"except",
":",
"pass",
"jwt",
"=",
"jsontokens",
".",
"decode_token",
"(",
"jwt_txt",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"warning",
"(",
"\"Unable to decode token at {}\"",
".",
"format",
"(",
"url",
")",
")",
"return",
"None",
"try",
":",
"# must be well-formed",
"assert",
"isinstance",
"(",
"jwt",
",",
"dict",
")",
"assert",
"'payload'",
"in",
"jwt",
",",
"jwt",
"assert",
"isinstance",
"(",
"jwt",
"[",
"'payload'",
"]",
",",
"dict",
")",
"assert",
"'issuer'",
"in",
"jwt",
"[",
"'payload'",
"]",
",",
"jwt",
"assert",
"isinstance",
"(",
"jwt",
"[",
"'payload'",
"]",
"[",
"'issuer'",
"]",
",",
"dict",
")",
"assert",
"'publicKey'",
"in",
"jwt",
"[",
"'payload'",
"]",
"[",
"'issuer'",
"]",
",",
"jwt",
"assert",
"virtualchain",
".",
"ecdsalib",
".",
"ecdsa_public_key",
"(",
"str",
"(",
"jwt",
"[",
"'payload'",
"]",
"[",
"'issuer'",
"]",
"[",
"'publicKey'",
"]",
")",
")",
"except",
"AssertionError",
"as",
"ae",
":",
"if",
"BLOCKSTACK_TEST",
"or",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ae",
")",
"log",
".",
"warning",
"(",
"\"JWT at {} is malformed\"",
".",
"format",
"(",
"url",
")",
")",
"return",
"None",
"if",
"address",
"is",
"not",
"None",
":",
"public_key",
"=",
"str",
"(",
"jwt",
"[",
"'payload'",
"]",
"[",
"'issuer'",
"]",
"[",
"'publicKey'",
"]",
")",
"addrs",
"=",
"[",
"virtualchain",
".",
"address_reencode",
"(",
"virtualchain",
".",
"ecdsalib",
".",
"ecdsa_public_key",
"(",
"keylib",
".",
"key_formatting",
".",
"decompress",
"(",
"public_key",
")",
")",
".",
"address",
"(",
")",
")",
",",
"virtualchain",
".",
"address_reencode",
"(",
"virtualchain",
".",
"ecdsalib",
".",
"ecdsa_public_key",
"(",
"keylib",
".",
"key_formatting",
".",
"compress",
"(",
"public_key",
")",
")",
".",
"address",
"(",
")",
")",
"]",
"if",
"virtualchain",
".",
"address_reencode",
"(",
"address",
")",
"not",
"in",
"addrs",
":",
"# got a JWT, but it doesn't match the address",
"log",
".",
"warning",
"(",
"\"Found JWT at {}, but its public key has addresses {} and {} (expected {})\"",
".",
"format",
"(",
"url",
",",
"addrs",
"[",
"0",
"]",
",",
"addrs",
"[",
"1",
"]",
",",
"address",
")",
")",
"return",
"None",
"verifier",
"=",
"jsontokens",
".",
"TokenVerifier",
"(",
")",
"if",
"not",
"verifier",
".",
"verify",
"(",
"jwt_txt",
",",
"public_key",
")",
":",
"# got a JWT, and the address matches, but the signature does not",
"log",
".",
"warning",
"(",
"\"Found JWT at {}, but it was not signed by {} ({})\"",
".",
"format",
"(",
"url",
",",
"public_key",
",",
"address",
")",
")",
"return",
"None",
"return",
"jwt"
] | Given a URL, fetch and decode the JWT it points to.
If address is given, then authenticate the JWT with the address.
Return None if we could not fetch it, or unable to authenticate it.
NOTE: the URL must be usable by the requests library | [
"Given",
"a",
"URL",
"fetch",
"and",
"decode",
"the",
"JWT",
"it",
"points",
"to",
".",
"If",
"address",
"is",
"given",
"then",
"authenticate",
"the",
"JWT",
"with",
"the",
"address",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L3460-L3554 |
230,763 | blockstack/blockstack-core | blockstack/lib/client.py | decode_name_zonefile | def decode_name_zonefile(name, zonefile_txt):
"""
Decode a zone file for a name.
Must be either a well-formed DNS zone file, or a legacy Onename profile.
Return None on error
"""
user_zonefile = None
try:
# by default, it's a zonefile-formatted text file
user_zonefile_defaultdict = blockstack_zones.parse_zone_file(zonefile_txt)
# force dict
user_zonefile = dict(user_zonefile_defaultdict)
except (IndexError, ValueError, blockstack_zones.InvalidLineException):
# might be legacy profile
log.debug('WARN: failed to parse user zonefile; trying to import as legacy')
try:
user_zonefile = json.loads(zonefile_txt)
if not isinstance(user_zonefile, dict):
log.debug('Not a legacy user zonefile')
return None
except Exception as e:
log.error('Failed to parse non-standard zonefile')
return None
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
log.error('Failed to parse zonefile')
return None
if user_zonefile is None:
return None
return user_zonefile | python | def decode_name_zonefile(name, zonefile_txt):
"""
Decode a zone file for a name.
Must be either a well-formed DNS zone file, or a legacy Onename profile.
Return None on error
"""
user_zonefile = None
try:
# by default, it's a zonefile-formatted text file
user_zonefile_defaultdict = blockstack_zones.parse_zone_file(zonefile_txt)
# force dict
user_zonefile = dict(user_zonefile_defaultdict)
except (IndexError, ValueError, blockstack_zones.InvalidLineException):
# might be legacy profile
log.debug('WARN: failed to parse user zonefile; trying to import as legacy')
try:
user_zonefile = json.loads(zonefile_txt)
if not isinstance(user_zonefile, dict):
log.debug('Not a legacy user zonefile')
return None
except Exception as e:
log.error('Failed to parse non-standard zonefile')
return None
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
log.error('Failed to parse zonefile')
return None
if user_zonefile is None:
return None
return user_zonefile | [
"def",
"decode_name_zonefile",
"(",
"name",
",",
"zonefile_txt",
")",
":",
"user_zonefile",
"=",
"None",
"try",
":",
"# by default, it's a zonefile-formatted text file",
"user_zonefile_defaultdict",
"=",
"blockstack_zones",
".",
"parse_zone_file",
"(",
"zonefile_txt",
")",
"# force dict",
"user_zonefile",
"=",
"dict",
"(",
"user_zonefile_defaultdict",
")",
"except",
"(",
"IndexError",
",",
"ValueError",
",",
"blockstack_zones",
".",
"InvalidLineException",
")",
":",
"# might be legacy profile",
"log",
".",
"debug",
"(",
"'WARN: failed to parse user zonefile; trying to import as legacy'",
")",
"try",
":",
"user_zonefile",
"=",
"json",
".",
"loads",
"(",
"zonefile_txt",
")",
"if",
"not",
"isinstance",
"(",
"user_zonefile",
",",
"dict",
")",
":",
"log",
".",
"debug",
"(",
"'Not a legacy user zonefile'",
")",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Failed to parse non-standard zonefile'",
")",
"return",
"None",
"except",
"Exception",
"as",
"e",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"'Failed to parse zonefile'",
")",
"return",
"None",
"if",
"user_zonefile",
"is",
"None",
":",
"return",
"None",
"return",
"user_zonefile"
] | Decode a zone file for a name.
Must be either a well-formed DNS zone file, or a legacy Onename profile.
Return None on error | [
"Decode",
"a",
"zone",
"file",
"for",
"a",
"name",
".",
"Must",
"be",
"either",
"a",
"well",
"-",
"formed",
"DNS",
"zone",
"file",
"or",
"a",
"legacy",
"Onename",
"profile",
".",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L3738-L3776 |
230,764 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler._send_headers | def _send_headers(self, status_code=200, content_type='application/json', more_headers={}):
"""
Generate and reply headers
"""
self.send_response(status_code)
self.send_header('content-type', content_type)
self.send_header('Access-Control-Allow-Origin', '*') # CORS
for (hdr, val) in more_headers.items():
self.send_header(hdr, val)
self.end_headers() | python | def _send_headers(self, status_code=200, content_type='application/json', more_headers={}):
"""
Generate and reply headers
"""
self.send_response(status_code)
self.send_header('content-type', content_type)
self.send_header('Access-Control-Allow-Origin', '*') # CORS
for (hdr, val) in more_headers.items():
self.send_header(hdr, val)
self.end_headers() | [
"def",
"_send_headers",
"(",
"self",
",",
"status_code",
"=",
"200",
",",
"content_type",
"=",
"'application/json'",
",",
"more_headers",
"=",
"{",
"}",
")",
":",
"self",
".",
"send_response",
"(",
"status_code",
")",
"self",
".",
"send_header",
"(",
"'content-type'",
",",
"content_type",
")",
"self",
".",
"send_header",
"(",
"'Access-Control-Allow-Origin'",
",",
"'*'",
")",
"# CORS",
"for",
"(",
"hdr",
",",
"val",
")",
"in",
"more_headers",
".",
"items",
"(",
")",
":",
"self",
".",
"send_header",
"(",
"hdr",
",",
"val",
")",
"self",
".",
"end_headers",
"(",
")"
] | Generate and reply headers | [
"Generate",
"and",
"reply",
"headers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L124-L134 |
230,765 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler._reply_json | def _reply_json(self, json_payload, status_code=200):
"""
Return a JSON-serializable data structure
"""
self._send_headers(status_code=status_code)
json_str = json.dumps(json_payload)
self.wfile.write(json_str) | python | def _reply_json(self, json_payload, status_code=200):
"""
Return a JSON-serializable data structure
"""
self._send_headers(status_code=status_code)
json_str = json.dumps(json_payload)
self.wfile.write(json_str) | [
"def",
"_reply_json",
"(",
"self",
",",
"json_payload",
",",
"status_code",
"=",
"200",
")",
":",
"self",
".",
"_send_headers",
"(",
"status_code",
"=",
"status_code",
")",
"json_str",
"=",
"json",
".",
"dumps",
"(",
"json_payload",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"json_str",
")"
] | Return a JSON-serializable data structure | [
"Return",
"a",
"JSON",
"-",
"serializable",
"data",
"structure"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L137-L143 |
230,766 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler._read_json | def _read_json(self, schema=None, maxlen=JSONRPC_MAX_SIZE):
"""
Read a JSON payload from the requester
Return the parsed payload on success
Return None on error
"""
# JSON post?
request_type = self.headers.get('content-type', None)
client_address_str = "{}:{}".format(self.client_address[0], self.client_address[1])
if request_type != 'application/json':
log.error("Invalid request of type {} from {}".format(request_type, client_address_str))
return None
request_str = self._read_payload(maxlen=maxlen)
if request_str is None:
log.error("Failed to read request")
return None
# parse the payload
request = None
try:
request = json.loads( request_str )
if schema is not None:
jsonschema.validate( request, schema )
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
log.error("Validation error on request {}...".format(request_str[:15]))
if ve.validator == "maxLength":
return {"error" : "maxLength"}
except (TypeError, ValueError) as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
return None
return request | python | def _read_json(self, schema=None, maxlen=JSONRPC_MAX_SIZE):
"""
Read a JSON payload from the requester
Return the parsed payload on success
Return None on error
"""
# JSON post?
request_type = self.headers.get('content-type', None)
client_address_str = "{}:{}".format(self.client_address[0], self.client_address[1])
if request_type != 'application/json':
log.error("Invalid request of type {} from {}".format(request_type, client_address_str))
return None
request_str = self._read_payload(maxlen=maxlen)
if request_str is None:
log.error("Failed to read request")
return None
# parse the payload
request = None
try:
request = json.loads( request_str )
if schema is not None:
jsonschema.validate( request, schema )
except ValidationError as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
log.error("Validation error on request {}...".format(request_str[:15]))
if ve.validator == "maxLength":
return {"error" : "maxLength"}
except (TypeError, ValueError) as ve:
if BLOCKSTACK_DEBUG:
log.exception(ve)
return None
return request | [
"def",
"_read_json",
"(",
"self",
",",
"schema",
"=",
"None",
",",
"maxlen",
"=",
"JSONRPC_MAX_SIZE",
")",
":",
"# JSON post?",
"request_type",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"None",
")",
"client_address_str",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"self",
".",
"client_address",
"[",
"0",
"]",
",",
"self",
".",
"client_address",
"[",
"1",
"]",
")",
"if",
"request_type",
"!=",
"'application/json'",
":",
"log",
".",
"error",
"(",
"\"Invalid request of type {} from {}\"",
".",
"format",
"(",
"request_type",
",",
"client_address_str",
")",
")",
"return",
"None",
"request_str",
"=",
"self",
".",
"_read_payload",
"(",
"maxlen",
"=",
"maxlen",
")",
"if",
"request_str",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Failed to read request\"",
")",
"return",
"None",
"# parse the payload",
"request",
"=",
"None",
"try",
":",
"request",
"=",
"json",
".",
"loads",
"(",
"request_str",
")",
"if",
"schema",
"is",
"not",
"None",
":",
"jsonschema",
".",
"validate",
"(",
"request",
",",
"schema",
")",
"except",
"ValidationError",
"as",
"ve",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ve",
")",
"log",
".",
"error",
"(",
"\"Validation error on request {}...\"",
".",
"format",
"(",
"request_str",
"[",
":",
"15",
"]",
")",
")",
"if",
"ve",
".",
"validator",
"==",
"\"maxLength\"",
":",
"return",
"{",
"\"error\"",
":",
"\"maxLength\"",
"}",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"ve",
":",
"if",
"BLOCKSTACK_DEBUG",
":",
"log",
".",
"exception",
"(",
"ve",
")",
"return",
"None",
"return",
"request"
] | Read a JSON payload from the requester
Return the parsed payload on success
Return None on error | [
"Read",
"a",
"JSON",
"payload",
"from",
"the",
"requester",
"Return",
"the",
"parsed",
"payload",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L176-L217 |
230,767 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.parse_qs | def parse_qs(self, qs):
"""
Parse query string, but enforce one instance of each variable.
Return a dict with the variables on success
Return None on parse error
"""
qs_state = urllib2.urlparse.parse_qs(qs)
ret = {}
for qs_var, qs_value_list in qs_state.items():
if len(qs_value_list) > 1:
return None
ret[qs_var] = qs_value_list[0]
return ret | python | def parse_qs(self, qs):
"""
Parse query string, but enforce one instance of each variable.
Return a dict with the variables on success
Return None on parse error
"""
qs_state = urllib2.urlparse.parse_qs(qs)
ret = {}
for qs_var, qs_value_list in qs_state.items():
if len(qs_value_list) > 1:
return None
ret[qs_var] = qs_value_list[0]
return ret | [
"def",
"parse_qs",
"(",
"self",
",",
"qs",
")",
":",
"qs_state",
"=",
"urllib2",
".",
"urlparse",
".",
"parse_qs",
"(",
"qs",
")",
"ret",
"=",
"{",
"}",
"for",
"qs_var",
",",
"qs_value_list",
"in",
"qs_state",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"qs_value_list",
")",
">",
"1",
":",
"return",
"None",
"ret",
"[",
"qs_var",
"]",
"=",
"qs_value_list",
"[",
"0",
"]",
"return",
"ret"
] | Parse query string, but enforce one instance of each variable.
Return a dict with the variables on success
Return None on parse error | [
"Parse",
"query",
"string",
"but",
"enforce",
"one",
"instance",
"of",
"each",
"variable",
".",
"Return",
"a",
"dict",
"with",
"the",
"variables",
"on",
"success",
"Return",
"None",
"on",
"parse",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L220-L234 |
230,768 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.get_path_and_qs | def get_path_and_qs(self):
"""
Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error
"""
path_parts = self.path.split("?", 1)
if len(path_parts) > 1:
qs = path_parts[1].split("#", 1)[0]
else:
qs = ""
path = path_parts[0].split("#", 1)[0]
path = posixpath.normpath(urllib.unquote(path))
qs_values = self.parse_qs( qs )
if qs_values is None:
return {'error': 'Failed to parse query string'}
parts = path.strip('/').split('/')
return {'path': path, 'qs_values': qs_values, 'parts': parts} | python | def get_path_and_qs(self):
"""
Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error
"""
path_parts = self.path.split("?", 1)
if len(path_parts) > 1:
qs = path_parts[1].split("#", 1)[0]
else:
qs = ""
path = path_parts[0].split("#", 1)[0]
path = posixpath.normpath(urllib.unquote(path))
qs_values = self.parse_qs( qs )
if qs_values is None:
return {'error': 'Failed to parse query string'}
parts = path.strip('/').split('/')
return {'path': path, 'qs_values': qs_values, 'parts': parts} | [
"def",
"get_path_and_qs",
"(",
"self",
")",
":",
"path_parts",
"=",
"self",
".",
"path",
".",
"split",
"(",
"\"?\"",
",",
"1",
")",
"if",
"len",
"(",
"path_parts",
")",
">",
"1",
":",
"qs",
"=",
"path_parts",
"[",
"1",
"]",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"[",
"0",
"]",
"else",
":",
"qs",
"=",
"\"\"",
"path",
"=",
"path_parts",
"[",
"0",
"]",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"[",
"0",
"]",
"path",
"=",
"posixpath",
".",
"normpath",
"(",
"urllib",
".",
"unquote",
"(",
"path",
")",
")",
"qs_values",
"=",
"self",
".",
"parse_qs",
"(",
"qs",
")",
"if",
"qs_values",
"is",
"None",
":",
"return",
"{",
"'error'",
":",
"'Failed to parse query string'",
"}",
"parts",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"return",
"{",
"'path'",
":",
"path",
",",
"'qs_values'",
":",
"qs_values",
",",
"'parts'",
":",
"parts",
"}"
] | Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error | [
"Parse",
"and",
"obtain",
"the",
"path",
"and",
"query",
"values",
".",
"We",
"don",
"t",
"care",
"about",
"fragments",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L237-L261 |
230,769 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.OPTIONS_preflight | def OPTIONS_preflight( self, path_info ):
"""
Give back CORS preflight check headers
"""
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*') # CORS
self.send_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')
self.send_header('Access-Control-Allow-Headers', 'content-type, authorization, range')
self.send_header('Access-Control-Expose-Headers', 'content-length, content-range')
self.send_header('Access-Control-Max-Age', 21600)
self.end_headers()
return | python | def OPTIONS_preflight( self, path_info ):
"""
Give back CORS preflight check headers
"""
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*') # CORS
self.send_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')
self.send_header('Access-Control-Allow-Headers', 'content-type, authorization, range')
self.send_header('Access-Control-Expose-Headers', 'content-length, content-range')
self.send_header('Access-Control-Max-Age', 21600)
self.end_headers()
return | [
"def",
"OPTIONS_preflight",
"(",
"self",
",",
"path_info",
")",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Access-Control-Allow-Origin'",
",",
"'*'",
")",
"# CORS",
"self",
".",
"send_header",
"(",
"'Access-Control-Allow-Methods'",
",",
"'GET, PUT, POST, DELETE'",
")",
"self",
".",
"send_header",
"(",
"'Access-Control-Allow-Headers'",
",",
"'content-type, authorization, range'",
")",
"self",
".",
"send_header",
"(",
"'Access-Control-Expose-Headers'",
",",
"'content-length, content-range'",
")",
"self",
".",
"send_header",
"(",
"'Access-Control-Max-Age'",
",",
"21600",
")",
"self",
".",
"end_headers",
"(",
")",
"return"
] | Give back CORS preflight check headers | [
"Give",
"back",
"CORS",
"preflight",
"check",
"headers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L290-L301 |
230,770 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_names_owned_by_address | def GET_names_owned_by_address( self, path_info, blockchain, address ):
"""
Get all names owned by an address
Returns the list on success
Return 404 on unsupported blockchain
Return 502 on failure to get names for any non-specified reason
"""
if not check_address(address):
return self._reply_json({'error': 'Invalid address'}, status_code=400)
if blockchain != 'bitcoin':
return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
blockstackd_url = get_blockstackd_url()
address = str(address)
subdomain_names = blockstackd_client.get_subdomains_owned_by_address(address, hostport=blockstackd_url)
if json_is_error(subdomain_names):
log.error("Failed to fetch subdomains owned by address")
log.error(subdomain_names)
subdomain_names = []
# make sure we have the right encoding
new_addr = virtualchain.address_reencode(address)
if new_addr != address:
log.debug("Re-encode {} to {}".format(new_addr, address))
address = new_addr
res = blockstackd_client.get_names_owned_by_address(address, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to get names owned by address")
self._reply_json({'error': 'Failed to list names by address'}, status_code=res.get('http_status', 502))
return
self._reply_json({'names': res + subdomain_names})
return | python | def GET_names_owned_by_address( self, path_info, blockchain, address ):
"""
Get all names owned by an address
Returns the list on success
Return 404 on unsupported blockchain
Return 502 on failure to get names for any non-specified reason
"""
if not check_address(address):
return self._reply_json({'error': 'Invalid address'}, status_code=400)
if blockchain != 'bitcoin':
return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
blockstackd_url = get_blockstackd_url()
address = str(address)
subdomain_names = blockstackd_client.get_subdomains_owned_by_address(address, hostport=blockstackd_url)
if json_is_error(subdomain_names):
log.error("Failed to fetch subdomains owned by address")
log.error(subdomain_names)
subdomain_names = []
# make sure we have the right encoding
new_addr = virtualchain.address_reencode(address)
if new_addr != address:
log.debug("Re-encode {} to {}".format(new_addr, address))
address = new_addr
res = blockstackd_client.get_names_owned_by_address(address, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to get names owned by address")
self._reply_json({'error': 'Failed to list names by address'}, status_code=res.get('http_status', 502))
return
self._reply_json({'names': res + subdomain_names})
return | [
"def",
"GET_names_owned_by_address",
"(",
"self",
",",
"path_info",
",",
"blockchain",
",",
"address",
")",
":",
"if",
"not",
"check_address",
"(",
"address",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid address'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"blockchain",
"!=",
"'bitcoin'",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Unsupported blockchain'",
"}",
",",
"status_code",
"=",
"404",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"address",
"=",
"str",
"(",
"address",
")",
"subdomain_names",
"=",
"blockstackd_client",
".",
"get_subdomains_owned_by_address",
"(",
"address",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"subdomain_names",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to fetch subdomains owned by address\"",
")",
"log",
".",
"error",
"(",
"subdomain_names",
")",
"subdomain_names",
"=",
"[",
"]",
"# make sure we have the right encoding",
"new_addr",
"=",
"virtualchain",
".",
"address_reencode",
"(",
"address",
")",
"if",
"new_addr",
"!=",
"address",
":",
"log",
".",
"debug",
"(",
"\"Re-encode {} to {}\"",
".",
"format",
"(",
"new_addr",
",",
"address",
")",
")",
"address",
"=",
"new_addr",
"res",
"=",
"blockstackd_client",
".",
"get_names_owned_by_address",
"(",
"address",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"res",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to get names owned by address\"",
")",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Failed to list names by address'",
"}",
",",
"status_code",
"=",
"res",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'names'",
":",
"res",
"+",
"subdomain_names",
"}",
")",
"return"
] | Get all names owned by an address
Returns the list on success
Return 404 on unsupported blockchain
Return 502 on failure to get names for any non-specified reason | [
"Get",
"all",
"names",
"owned",
"by",
"an",
"address",
"Returns",
"the",
"list",
"on",
"success",
"Return",
"404",
"on",
"unsupported",
"blockchain",
"Return",
"502",
"on",
"failure",
"to",
"get",
"names",
"for",
"any",
"non",
"-",
"specified",
"reason"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L304-L339 |
230,771 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_account_record | def GET_account_record(self, path_info, account_addr, token_type):
"""
Get the state of a particular token account
Returns the account
"""
if not check_account_address(account_addr):
return self._reply_json({'error': 'Invalid address'}, status_code=400)
if not check_token_type(token_type):
return self._reply_json({'error': 'Invalid token type'}, status_code=400)
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_account_record(account_addr, token_type, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to get account state for {} {}: {}".format(account_addr, token_type, res['error']))
return self._reply_json({'error': 'Failed to get account record for {} {}: {}'.format(token_type, account_addr, res['error'])}, status_code=res.get('http_status', 500))
self._reply_json(res)
return | python | def GET_account_record(self, path_info, account_addr, token_type):
"""
Get the state of a particular token account
Returns the account
"""
if not check_account_address(account_addr):
return self._reply_json({'error': 'Invalid address'}, status_code=400)
if not check_token_type(token_type):
return self._reply_json({'error': 'Invalid token type'}, status_code=400)
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_account_record(account_addr, token_type, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to get account state for {} {}: {}".format(account_addr, token_type, res['error']))
return self._reply_json({'error': 'Failed to get account record for {} {}: {}'.format(token_type, account_addr, res['error'])}, status_code=res.get('http_status', 500))
self._reply_json(res)
return | [
"def",
"GET_account_record",
"(",
"self",
",",
"path_info",
",",
"account_addr",
",",
"token_type",
")",
":",
"if",
"not",
"check_account_address",
"(",
"account_addr",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid address'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"not",
"check_token_type",
"(",
"token_type",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid token type'",
"}",
",",
"status_code",
"=",
"400",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"res",
"=",
"blockstackd_client",
".",
"get_account_record",
"(",
"account_addr",
",",
"token_type",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"res",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to get account state for {} {}: {}\"",
".",
"format",
"(",
"account_addr",
",",
"token_type",
",",
"res",
"[",
"'error'",
"]",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Failed to get account record for {} {}: {}'",
".",
"format",
"(",
"token_type",
",",
"account_addr",
",",
"res",
"[",
"'error'",
"]",
")",
"}",
",",
"status_code",
"=",
"res",
".",
"get",
"(",
"'http_status'",
",",
"500",
")",
")",
"self",
".",
"_reply_json",
"(",
"res",
")",
"return"
] | Get the state of a particular token account
Returns the account | [
"Get",
"the",
"state",
"of",
"a",
"particular",
"token",
"account",
"Returns",
"the",
"account"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L360-L378 |
230,772 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_names | def GET_names( self, path_info ):
"""
Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names
"""
include_expired = False
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
log.error("Page required")
return self._reply_json({'error': 'page= argument required'}, status_code=400)
try:
page = int(page)
if page < 0:
raise ValueError("Page is negative")
except ValueError:
log.error("Invalid page")
return self._reply_json({'error': 'Invalid page= value'}, status_code=400)
if qs_values.get('all', '').lower() in ['1', 'true']:
include_expired = True
offset = page * 100
count = 100
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_all_names(offset, count, include_expired=include_expired, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to list all names (offset={}, count={}): {}".format(offset, count, res['error']))
return self._reply_json({'error': 'Failed to list all names'}, status_code=res.get('http_status', 502))
return self._reply_json(res) | python | def GET_names( self, path_info ):
"""
Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names
"""
include_expired = False
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
log.error("Page required")
return self._reply_json({'error': 'page= argument required'}, status_code=400)
try:
page = int(page)
if page < 0:
raise ValueError("Page is negative")
except ValueError:
log.error("Invalid page")
return self._reply_json({'error': 'Invalid page= value'}, status_code=400)
if qs_values.get('all', '').lower() in ['1', 'true']:
include_expired = True
offset = page * 100
count = 100
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_all_names(offset, count, include_expired=include_expired, hostport=blockstackd_url)
if json_is_error(res):
log.error("Failed to list all names (offset={}, count={}): {}".format(offset, count, res['error']))
return self._reply_json({'error': 'Failed to list all names'}, status_code=res.get('http_status', 502))
return self._reply_json(res) | [
"def",
"GET_names",
"(",
"self",
",",
"path_info",
")",
":",
"include_expired",
"=",
"False",
"qs_values",
"=",
"path_info",
"[",
"'qs_values'",
"]",
"page",
"=",
"qs_values",
".",
"get",
"(",
"'page'",
",",
"None",
")",
"if",
"page",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Page required\"",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'page= argument required'",
"}",
",",
"status_code",
"=",
"400",
")",
"try",
":",
"page",
"=",
"int",
"(",
"page",
")",
"if",
"page",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Page is negative\"",
")",
"except",
"ValueError",
":",
"log",
".",
"error",
"(",
"\"Invalid page\"",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid page= value'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"qs_values",
".",
"get",
"(",
"'all'",
",",
"''",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'1'",
",",
"'true'",
"]",
":",
"include_expired",
"=",
"True",
"offset",
"=",
"page",
"*",
"100",
"count",
"=",
"100",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"res",
"=",
"blockstackd_client",
".",
"get_all_names",
"(",
"offset",
",",
"count",
",",
"include_expired",
"=",
"include_expired",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"res",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to list all names (offset={}, count={}): {}\"",
".",
"format",
"(",
"offset",
",",
"count",
",",
"res",
"[",
"'error'",
"]",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Failed to list all names'",
"}",
",",
"status_code",
"=",
"res",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"res",
")"
] | Get all names in existence
If `all=true` is set, then include expired names.
Returns the list on success
Returns 400 on invalid arguments
Returns 502 on failure to get names | [
"Get",
"all",
"names",
"in",
"existence",
"If",
"all",
"=",
"true",
"is",
"set",
"then",
"include",
"expired",
"names",
".",
"Returns",
"the",
"list",
"on",
"success",
"Returns",
"400",
"on",
"invalid",
"arguments",
"Returns",
"502",
"on",
"failure",
"to",
"get",
"names"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L458-L496 |
230,773 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_name_history | def GET_name_history(self, path_info, name):
"""
Get the history of a name or subdomain.
Requires 'page' in the query string
return the history on success
return 400 on invalid start_block or end_block
return 502 on failure to query blockstack server
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
page = "0" # compatibility
try:
assert len(page) < 10
page = int(page)
assert page >= 0
assert page <= 2**32 - 1
except:
log.error("Invalid page")
self._reply_json({'error': 'Invalid page'}, status_code=400)
return
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_name_history_page(name, page, hostport=blockstackd_url)
if json_is_error(res):
log.error('Failed to get name history for {}: {}'.format(name, res['error']))
return self._reply_json({'error': res['error']}, status_code=res.get('http_status', 502))
return self._reply_json(res['history']) | python | def GET_name_history(self, path_info, name):
"""
Get the history of a name or subdomain.
Requires 'page' in the query string
return the history on success
return 400 on invalid start_block or end_block
return 502 on failure to query blockstack server
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
page = "0" # compatibility
try:
assert len(page) < 10
page = int(page)
assert page >= 0
assert page <= 2**32 - 1
except:
log.error("Invalid page")
self._reply_json({'error': 'Invalid page'}, status_code=400)
return
blockstackd_url = get_blockstackd_url()
res = blockstackd_client.get_name_history_page(name, page, hostport=blockstackd_url)
if json_is_error(res):
log.error('Failed to get name history for {}: {}'.format(name, res['error']))
return self._reply_json({'error': res['error']}, status_code=res.get('http_status', 502))
return self._reply_json(res['history']) | [
"def",
"GET_name_history",
"(",
"self",
",",
"path_info",
",",
"name",
")",
":",
"if",
"not",
"check_name",
"(",
"name",
")",
"and",
"not",
"check_subdomain",
"(",
"name",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid name or subdomain'",
"}",
",",
"status_code",
"=",
"400",
")",
"qs_values",
"=",
"path_info",
"[",
"'qs_values'",
"]",
"page",
"=",
"qs_values",
".",
"get",
"(",
"'page'",
",",
"None",
")",
"if",
"page",
"is",
"None",
":",
"page",
"=",
"\"0\"",
"# compatibility ",
"try",
":",
"assert",
"len",
"(",
"page",
")",
"<",
"10",
"page",
"=",
"int",
"(",
"page",
")",
"assert",
"page",
">=",
"0",
"assert",
"page",
"<=",
"2",
"**",
"32",
"-",
"1",
"except",
":",
"log",
".",
"error",
"(",
"\"Invalid page\"",
")",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid page'",
"}",
",",
"status_code",
"=",
"400",
")",
"return",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"res",
"=",
"blockstackd_client",
".",
"get_name_history_page",
"(",
"name",
",",
"page",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"res",
")",
":",
"log",
".",
"error",
"(",
"'Failed to get name history for {}: {}'",
".",
"format",
"(",
"name",
",",
"res",
"[",
"'error'",
"]",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"res",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"res",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"res",
"[",
"'history'",
"]",
")"
] | Get the history of a name or subdomain.
Requires 'page' in the query string
return the history on success
return 400 on invalid start_block or end_block
return 502 on failure to query blockstack server | [
"Get",
"the",
"history",
"of",
"a",
"name",
"or",
"subdomain",
".",
"Requires",
"page",
"in",
"the",
"query",
"string",
"return",
"the",
"history",
"on",
"success",
"return",
"400",
"on",
"invalid",
"start_block",
"or",
"end_block",
"return",
"502",
"on",
"failure",
"to",
"query",
"blockstack",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L650-L683 |
230,774 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_name_zonefile_by_hash | def GET_name_zonefile_by_hash( self, path_info, name, zonefile_hash ):
"""
Get a historic zonefile for a name
With `raw=1` on the query string, return the raw zone file
Reply 200 with {'zonefile': zonefile} on success
Reply 204 with {'error': ...} if the zone file is non-standard
Reply 404 on not found
Reply 502 on failure to fetch data
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
if not check_string(zonefile_hash, pattern=OP_ZONEFILE_HASH_PATTERN):
return self._reply_json({'error': 'Invalid zone file hash'}, status_code=400)
raw = path_info['qs_values'].get('raw', '')
raw = (raw.lower() in ['1', 'true'])
blockstack_hostport = get_blockstackd_url()
was_set = blockstackd_client.is_name_zonefile_hash(name, zonefile_hash, hostport=blockstack_hostport)
if json_is_error(was_set):
return self._reply_json({'error': was_set['error']}, status_code=was_set.get('http_status', 502))
if not was_set['result']:
self._reply_json({'error': 'No such zonefile'}, status_code=404)
return
resp = blockstackd_client.get_zonefiles(blockstack_hostport, [str(zonefile_hash)])
if json_is_error(resp):
self._reply_json({'error': resp['error']}, status_code=resp.get('http_status', 502))
return
if str(zonefile_hash) not in resp['zonefiles']:
return self._reply_json({'error': 'Blockstack does not have this zonefile. Try again later.'}, status_code=404)
if raw:
self._send_headers(status_code=200, content_type='application/octet-stream')
self.wfile.write(resp['zonefiles'][str(zonefile_hash)])
else:
# make sure it's valid
if str(zonefile_hash) not in resp['zonefiles']:
log.debug('Failed to find zonefile hash {}, possess {}'.format(
str(zonefile_hash), resp['zonefiles'].keys()))
return self._reply_json({'error': 'No such zonefile'}, status_code=404)
zonefile_txt = resp['zonefiles'][str(zonefile_hash)]
res = decode_name_zonefile(name, zonefile_txt)
if res is None:
log.error("Failed to parse zone file for {}".format(name))
self._reply_json({'error': 'Non-standard zone file for {}'.format(name)}, status_code=204)
return
self._reply_json({'zonefile': zonefile_txt})
return | python | def GET_name_zonefile_by_hash( self, path_info, name, zonefile_hash ):
"""
Get a historic zonefile for a name
With `raw=1` on the query string, return the raw zone file
Reply 200 with {'zonefile': zonefile} on success
Reply 204 with {'error': ...} if the zone file is non-standard
Reply 404 on not found
Reply 502 on failure to fetch data
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
if not check_string(zonefile_hash, pattern=OP_ZONEFILE_HASH_PATTERN):
return self._reply_json({'error': 'Invalid zone file hash'}, status_code=400)
raw = path_info['qs_values'].get('raw', '')
raw = (raw.lower() in ['1', 'true'])
blockstack_hostport = get_blockstackd_url()
was_set = blockstackd_client.is_name_zonefile_hash(name, zonefile_hash, hostport=blockstack_hostport)
if json_is_error(was_set):
return self._reply_json({'error': was_set['error']}, status_code=was_set.get('http_status', 502))
if not was_set['result']:
self._reply_json({'error': 'No such zonefile'}, status_code=404)
return
resp = blockstackd_client.get_zonefiles(blockstack_hostport, [str(zonefile_hash)])
if json_is_error(resp):
self._reply_json({'error': resp['error']}, status_code=resp.get('http_status', 502))
return
if str(zonefile_hash) not in resp['zonefiles']:
return self._reply_json({'error': 'Blockstack does not have this zonefile. Try again later.'}, status_code=404)
if raw:
self._send_headers(status_code=200, content_type='application/octet-stream')
self.wfile.write(resp['zonefiles'][str(zonefile_hash)])
else:
# make sure it's valid
if str(zonefile_hash) not in resp['zonefiles']:
log.debug('Failed to find zonefile hash {}, possess {}'.format(
str(zonefile_hash), resp['zonefiles'].keys()))
return self._reply_json({'error': 'No such zonefile'}, status_code=404)
zonefile_txt = resp['zonefiles'][str(zonefile_hash)]
res = decode_name_zonefile(name, zonefile_txt)
if res is None:
log.error("Failed to parse zone file for {}".format(name))
self._reply_json({'error': 'Non-standard zone file for {}'.format(name)}, status_code=204)
return
self._reply_json({'zonefile': zonefile_txt})
return | [
"def",
"GET_name_zonefile_by_hash",
"(",
"self",
",",
"path_info",
",",
"name",
",",
"zonefile_hash",
")",
":",
"if",
"not",
"check_name",
"(",
"name",
")",
"and",
"not",
"check_subdomain",
"(",
"name",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid name or subdomain'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"not",
"check_string",
"(",
"zonefile_hash",
",",
"pattern",
"=",
"OP_ZONEFILE_HASH_PATTERN",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid zone file hash'",
"}",
",",
"status_code",
"=",
"400",
")",
"raw",
"=",
"path_info",
"[",
"'qs_values'",
"]",
".",
"get",
"(",
"'raw'",
",",
"''",
")",
"raw",
"=",
"(",
"raw",
".",
"lower",
"(",
")",
"in",
"[",
"'1'",
",",
"'true'",
"]",
")",
"blockstack_hostport",
"=",
"get_blockstackd_url",
"(",
")",
"was_set",
"=",
"blockstackd_client",
".",
"is_name_zonefile_hash",
"(",
"name",
",",
"zonefile_hash",
",",
"hostport",
"=",
"blockstack_hostport",
")",
"if",
"json_is_error",
"(",
"was_set",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"was_set",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"was_set",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
")",
"if",
"not",
"was_set",
"[",
"'result'",
"]",
":",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'No such zonefile'",
"}",
",",
"status_code",
"=",
"404",
")",
"return",
"resp",
"=",
"blockstackd_client",
".",
"get_zonefiles",
"(",
"blockstack_hostport",
",",
"[",
"str",
"(",
"zonefile_hash",
")",
"]",
")",
"if",
"json_is_error",
"(",
"resp",
")",
":",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"resp",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"resp",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
")",
"return",
"if",
"str",
"(",
"zonefile_hash",
")",
"not",
"in",
"resp",
"[",
"'zonefiles'",
"]",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Blockstack does not have this zonefile. Try again later.'",
"}",
",",
"status_code",
"=",
"404",
")",
"if",
"raw",
":",
"self",
".",
"_send_headers",
"(",
"status_code",
"=",
"200",
",",
"content_type",
"=",
"'application/octet-stream'",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"resp",
"[",
"'zonefiles'",
"]",
"[",
"str",
"(",
"zonefile_hash",
")",
"]",
")",
"else",
":",
"# make sure it's valid",
"if",
"str",
"(",
"zonefile_hash",
")",
"not",
"in",
"resp",
"[",
"'zonefiles'",
"]",
":",
"log",
".",
"debug",
"(",
"'Failed to find zonefile hash {}, possess {}'",
".",
"format",
"(",
"str",
"(",
"zonefile_hash",
")",
",",
"resp",
"[",
"'zonefiles'",
"]",
".",
"keys",
"(",
")",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'No such zonefile'",
"}",
",",
"status_code",
"=",
"404",
")",
"zonefile_txt",
"=",
"resp",
"[",
"'zonefiles'",
"]",
"[",
"str",
"(",
"zonefile_hash",
")",
"]",
"res",
"=",
"decode_name_zonefile",
"(",
"name",
",",
"zonefile_txt",
")",
"if",
"res",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Failed to parse zone file for {}\"",
".",
"format",
"(",
"name",
")",
")",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Non-standard zone file for {}'",
".",
"format",
"(",
"name",
")",
"}",
",",
"status_code",
"=",
"204",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'zonefile'",
":",
"zonefile_txt",
"}",
")",
"return"
] | Get a historic zonefile for a name
With `raw=1` on the query string, return the raw zone file
Reply 200 with {'zonefile': zonefile} on success
Reply 204 with {'error': ...} if the zone file is non-standard
Reply 404 on not found
Reply 502 on failure to fetch data | [
"Get",
"a",
"historic",
"zonefile",
"for",
"a",
"name",
"With",
"raw",
"=",
"1",
"on",
"the",
"query",
"string",
"return",
"the",
"raw",
"zone",
"file"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L823-L879 |
230,775 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_namespaces | def GET_namespaces( self, path_info ):
"""
Get the list of all namespaces
Reply all existing namespaces
Reply 502 if we can't reach the server for whatever reason
"""
qs_values = path_info['qs_values']
offset = qs_values.get('offset', None)
count = qs_values.get('count', None)
blockstackd_url = get_blockstackd_url()
namespaces = blockstackd_client.get_all_namespaces(offset=offset, count=count, hostport=blockstackd_url)
if json_is_error(namespaces):
# error
status_code = namespaces.get('http_status', 502)
return self._reply_json({'error': namespaces['error']}, status_code=status_code)
self._reply_json(namespaces)
return | python | def GET_namespaces( self, path_info ):
"""
Get the list of all namespaces
Reply all existing namespaces
Reply 502 if we can't reach the server for whatever reason
"""
qs_values = path_info['qs_values']
offset = qs_values.get('offset', None)
count = qs_values.get('count', None)
blockstackd_url = get_blockstackd_url()
namespaces = blockstackd_client.get_all_namespaces(offset=offset, count=count, hostport=blockstackd_url)
if json_is_error(namespaces):
# error
status_code = namespaces.get('http_status', 502)
return self._reply_json({'error': namespaces['error']}, status_code=status_code)
self._reply_json(namespaces)
return | [
"def",
"GET_namespaces",
"(",
"self",
",",
"path_info",
")",
":",
"qs_values",
"=",
"path_info",
"[",
"'qs_values'",
"]",
"offset",
"=",
"qs_values",
".",
"get",
"(",
"'offset'",
",",
"None",
")",
"count",
"=",
"qs_values",
".",
"get",
"(",
"'count'",
",",
"None",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"namespaces",
"=",
"blockstackd_client",
".",
"get_all_namespaces",
"(",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"namespaces",
")",
":",
"# error",
"status_code",
"=",
"namespaces",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"namespaces",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"status_code",
")",
"self",
".",
"_reply_json",
"(",
"namespaces",
")",
"return"
] | Get the list of all namespaces
Reply all existing namespaces
Reply 502 if we can't reach the server for whatever reason | [
"Get",
"the",
"list",
"of",
"all",
"namespaces",
"Reply",
"all",
"existing",
"namespaces",
"Reply",
"502",
"if",
"we",
"can",
"t",
"reach",
"the",
"server",
"for",
"whatever",
"reason"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L980-L998 |
230,776 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_namespace_info | def GET_namespace_info( self, path_info, namespace_id ):
"""
Look up a namespace's info
Reply information about a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blocksatck server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
blockstackd_url = get_blockstackd_url()
namespace_rec = blockstackd_client.get_namespace_record(namespace_id, hostport=blockstackd_url)
if json_is_error(namespace_rec):
# error
status_code = namespace_rec.get('http_status', 502)
return self._reply_json({'error': namespace_rec['error']}, status_code=status_code)
self._reply_json(namespace_rec)
return | python | def GET_namespace_info( self, path_info, namespace_id ):
"""
Look up a namespace's info
Reply information about a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blocksatck server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
blockstackd_url = get_blockstackd_url()
namespace_rec = blockstackd_client.get_namespace_record(namespace_id, hostport=blockstackd_url)
if json_is_error(namespace_rec):
# error
status_code = namespace_rec.get('http_status', 502)
return self._reply_json({'error': namespace_rec['error']}, status_code=status_code)
self._reply_json(namespace_rec)
return | [
"def",
"GET_namespace_info",
"(",
"self",
",",
"path_info",
",",
"namespace_id",
")",
":",
"if",
"not",
"check_namespace",
"(",
"namespace_id",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid namespace'",
"}",
",",
"status_code",
"=",
"400",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"namespace_rec",
"=",
"blockstackd_client",
".",
"get_namespace_record",
"(",
"namespace_id",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"namespace_rec",
")",
":",
"# error",
"status_code",
"=",
"namespace_rec",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"namespace_rec",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"status_code",
")",
"self",
".",
"_reply_json",
"(",
"namespace_rec",
")",
"return"
] | Look up a namespace's info
Reply information about a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blocksatck server | [
"Look",
"up",
"a",
"namespace",
"s",
"info",
"Reply",
"information",
"about",
"a",
"namespace",
"Reply",
"404",
"if",
"the",
"namespace",
"doesn",
"t",
"exist",
"Reply",
"502",
"for",
"any",
"error",
"in",
"talking",
"to",
"the",
"blocksatck",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1001-L1019 |
230,777 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_namespace_num_names | def GET_namespace_num_names(self, path_info, namespace_id):
"""
Get the number of names in a namespace
Reply the number on success
Reply 404 if the namespace does not exist
Reply 502 on failure to talk to the blockstack server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
blockstackd_url = get_blockstackd_url()
name_count = blockstackd_client.get_num_names_in_namespace(namespace_id, hostport=blockstackd_url)
if json_is_error(name_count):
log.error("Failed to load namespace count for {}: {}".format(namespace_id, name_count['error']))
return self._reply_json({'error': 'Failed to load namespace count: {}'.format(name_count['error'])}, status_code=404)
self._reply_json({'names_count': name_count}) | python | def GET_namespace_num_names(self, path_info, namespace_id):
"""
Get the number of names in a namespace
Reply the number on success
Reply 404 if the namespace does not exist
Reply 502 on failure to talk to the blockstack server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
blockstackd_url = get_blockstackd_url()
name_count = blockstackd_client.get_num_names_in_namespace(namespace_id, hostport=blockstackd_url)
if json_is_error(name_count):
log.error("Failed to load namespace count for {}: {}".format(namespace_id, name_count['error']))
return self._reply_json({'error': 'Failed to load namespace count: {}'.format(name_count['error'])}, status_code=404)
self._reply_json({'names_count': name_count}) | [
"def",
"GET_namespace_num_names",
"(",
"self",
",",
"path_info",
",",
"namespace_id",
")",
":",
"if",
"not",
"check_namespace",
"(",
"namespace_id",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid namespace'",
"}",
",",
"status_code",
"=",
"400",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"name_count",
"=",
"blockstackd_client",
".",
"get_num_names_in_namespace",
"(",
"namespace_id",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"name_count",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to load namespace count for {}: {}\"",
".",
"format",
"(",
"namespace_id",
",",
"name_count",
"[",
"'error'",
"]",
")",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Failed to load namespace count: {}'",
".",
"format",
"(",
"name_count",
"[",
"'error'",
"]",
")",
"}",
",",
"status_code",
"=",
"404",
")",
"self",
".",
"_reply_json",
"(",
"{",
"'names_count'",
":",
"name_count",
"}",
")"
] | Get the number of names in a namespace
Reply the number on success
Reply 404 if the namespace does not exist
Reply 502 on failure to talk to the blockstack server | [
"Get",
"the",
"number",
"of",
"names",
"in",
"a",
"namespace",
"Reply",
"the",
"number",
"on",
"success",
"Reply",
"404",
"if",
"the",
"namespace",
"does",
"not",
"exist",
"Reply",
"502",
"on",
"failure",
"to",
"talk",
"to",
"the",
"blockstack",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1022-L1038 |
230,778 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_namespace_names | def GET_namespace_names( self, path_info, namespace_id ):
"""
Get the list of names in a namespace
Reply the list of names in a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blockstack server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
log.error("Page required")
return self._reply_json({'error': 'page= argument required'}, status_code=400)
try:
page = int(page)
if page < 0:
raise ValueError()
except ValueError:
log.error("Invalid page")
return self._reply_json({'error': 'Invalid page= value'}, status_code=400)
offset = page * 100
count = 100
blockstackd_url = get_blockstackd_url()
namespace_names = blockstackd_client.get_names_in_namespace(namespace_id, offset=offset, count=count, hostport=blockstackd_url)
if json_is_error(namespace_names):
# error
status_code = namespace_names.get('http_status', 502)
return self._reply_json({'error': namespace_names['error']}, status_code=status_code)
self._reply_json(namespace_names)
return | python | def GET_namespace_names( self, path_info, namespace_id ):
"""
Get the list of names in a namespace
Reply the list of names in a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blockstack server
"""
if not check_namespace(namespace_id):
return self._reply_json({'error': 'Invalid namespace'}, status_code=400)
qs_values = path_info['qs_values']
page = qs_values.get('page', None)
if page is None:
log.error("Page required")
return self._reply_json({'error': 'page= argument required'}, status_code=400)
try:
page = int(page)
if page < 0:
raise ValueError()
except ValueError:
log.error("Invalid page")
return self._reply_json({'error': 'Invalid page= value'}, status_code=400)
offset = page * 100
count = 100
blockstackd_url = get_blockstackd_url()
namespace_names = blockstackd_client.get_names_in_namespace(namespace_id, offset=offset, count=count, hostport=blockstackd_url)
if json_is_error(namespace_names):
# error
status_code = namespace_names.get('http_status', 502)
return self._reply_json({'error': namespace_names['error']}, status_code=status_code)
self._reply_json(namespace_names)
return | [
"def",
"GET_namespace_names",
"(",
"self",
",",
"path_info",
",",
"namespace_id",
")",
":",
"if",
"not",
"check_namespace",
"(",
"namespace_id",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid namespace'",
"}",
",",
"status_code",
"=",
"400",
")",
"qs_values",
"=",
"path_info",
"[",
"'qs_values'",
"]",
"page",
"=",
"qs_values",
".",
"get",
"(",
"'page'",
",",
"None",
")",
"if",
"page",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Page required\"",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'page= argument required'",
"}",
",",
"status_code",
"=",
"400",
")",
"try",
":",
"page",
"=",
"int",
"(",
"page",
")",
"if",
"page",
"<",
"0",
":",
"raise",
"ValueError",
"(",
")",
"except",
"ValueError",
":",
"log",
".",
"error",
"(",
"\"Invalid page\"",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid page= value'",
"}",
",",
"status_code",
"=",
"400",
")",
"offset",
"=",
"page",
"*",
"100",
"count",
"=",
"100",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"namespace_names",
"=",
"blockstackd_client",
".",
"get_names_in_namespace",
"(",
"namespace_id",
",",
"offset",
"=",
"offset",
",",
"count",
"=",
"count",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"namespace_names",
")",
":",
"# error",
"status_code",
"=",
"namespace_names",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"namespace_names",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"status_code",
")",
"self",
".",
"_reply_json",
"(",
"namespace_names",
")",
"return"
] | Get the list of names in a namespace
Reply the list of names in a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blockstack server | [
"Get",
"the",
"list",
"of",
"names",
"in",
"a",
"namespace",
"Reply",
"the",
"list",
"of",
"names",
"in",
"a",
"namespace",
"Reply",
"404",
"if",
"the",
"namespace",
"doesn",
"t",
"exist",
"Reply",
"502",
"for",
"any",
"error",
"in",
"talking",
"to",
"the",
"blockstack",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1041-L1077 |
230,779 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_blockchain_ops | def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ):
"""
Get the name's historic name operations
Reply the list of nameops at the given block height
Reply 404 for blockchains other than those supported
Reply 502 for any error we have in talking to the blockstack server
"""
try:
blockheight = int(blockheight)
assert check_block(blockheight)
except:
return self._reply_json({'error': 'Invalid block'}, status_code=400)
if blockchain_name != 'bitcoin':
# not supported
return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
blockstackd_url = get_blockstackd_url()
nameops = blockstackd_client.get_blockstack_transactions_at(int(blockheight), hostport=blockstackd_url)
if json_is_error(nameops):
# error
status_code = nameops.get('http_status', 502)
return self._reply_json({'error': nameops['error']}, status_code=status_code)
self._reply_json(nameops)
return | python | def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ):
"""
Get the name's historic name operations
Reply the list of nameops at the given block height
Reply 404 for blockchains other than those supported
Reply 502 for any error we have in talking to the blockstack server
"""
try:
blockheight = int(blockheight)
assert check_block(blockheight)
except:
return self._reply_json({'error': 'Invalid block'}, status_code=400)
if blockchain_name != 'bitcoin':
# not supported
return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
blockstackd_url = get_blockstackd_url()
nameops = blockstackd_client.get_blockstack_transactions_at(int(blockheight), hostport=blockstackd_url)
if json_is_error(nameops):
# error
status_code = nameops.get('http_status', 502)
return self._reply_json({'error': nameops['error']}, status_code=status_code)
self._reply_json(nameops)
return | [
"def",
"GET_blockchain_ops",
"(",
"self",
",",
"path_info",
",",
"blockchain_name",
",",
"blockheight",
")",
":",
"try",
":",
"blockheight",
"=",
"int",
"(",
"blockheight",
")",
"assert",
"check_block",
"(",
"blockheight",
")",
"except",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid block'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"blockchain_name",
"!=",
"'bitcoin'",
":",
"# not supported",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Unsupported blockchain'",
"}",
",",
"status_code",
"=",
"404",
")",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"nameops",
"=",
"blockstackd_client",
".",
"get_blockstack_transactions_at",
"(",
"int",
"(",
"blockheight",
")",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"nameops",
")",
":",
"# error",
"status_code",
"=",
"nameops",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"nameops",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"status_code",
")",
"self",
".",
"_reply_json",
"(",
"nameops",
")",
"return"
] | Get the name's historic name operations
Reply the list of nameops at the given block height
Reply 404 for blockchains other than those supported
Reply 502 for any error we have in talking to the blockstack server | [
"Get",
"the",
"name",
"s",
"historic",
"name",
"operations",
"Reply",
"the",
"list",
"of",
"nameops",
"at",
"the",
"given",
"block",
"height",
"Reply",
"404",
"for",
"blockchains",
"other",
"than",
"those",
"supported",
"Reply",
"502",
"for",
"any",
"error",
"we",
"have",
"in",
"talking",
"to",
"the",
"blockstack",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1080-L1105 |
230,780 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler.GET_blockchain_name_record | def GET_blockchain_name_record( self, path_info, blockchain_name, name ):
"""
Get the name's blockchain record in full
Reply the raw blockchain record on success
Reply 404 if the name is not found
Reply 502 if we have an error talking to the server
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
if blockchain_name != 'bitcoin':
# not supported
self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
return
blockstackd_url = get_blockstackd_url()
name_rec = blockstackd_client.get_name_record(name, include_history=False, hostport=blockstackd_url)
if json_is_error(name_rec):
# error
status_code = name_rec.get('http_status', 502)
return self._reply_json({'error': name_rec['error']}, status_code=status_code)
return self._reply_json(name_rec) | python | def GET_blockchain_name_record( self, path_info, blockchain_name, name ):
"""
Get the name's blockchain record in full
Reply the raw blockchain record on success
Reply 404 if the name is not found
Reply 502 if we have an error talking to the server
"""
if not check_name(name) and not check_subdomain(name):
return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)
if blockchain_name != 'bitcoin':
# not supported
self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
return
blockstackd_url = get_blockstackd_url()
name_rec = blockstackd_client.get_name_record(name, include_history=False, hostport=blockstackd_url)
if json_is_error(name_rec):
# error
status_code = name_rec.get('http_status', 502)
return self._reply_json({'error': name_rec['error']}, status_code=status_code)
return self._reply_json(name_rec) | [
"def",
"GET_blockchain_name_record",
"(",
"self",
",",
"path_info",
",",
"blockchain_name",
",",
"name",
")",
":",
"if",
"not",
"check_name",
"(",
"name",
")",
"and",
"not",
"check_subdomain",
"(",
"name",
")",
":",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Invalid name or subdomain'",
"}",
",",
"status_code",
"=",
"400",
")",
"if",
"blockchain_name",
"!=",
"'bitcoin'",
":",
"# not supported",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"'Unsupported blockchain'",
"}",
",",
"status_code",
"=",
"404",
")",
"return",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"name_rec",
"=",
"blockstackd_client",
".",
"get_name_record",
"(",
"name",
",",
"include_history",
"=",
"False",
",",
"hostport",
"=",
"blockstackd_url",
")",
"if",
"json_is_error",
"(",
"name_rec",
")",
":",
"# error",
"status_code",
"=",
"name_rec",
".",
"get",
"(",
"'http_status'",
",",
"502",
")",
"return",
"self",
".",
"_reply_json",
"(",
"{",
"'error'",
":",
"name_rec",
"[",
"'error'",
"]",
"}",
",",
"status_code",
"=",
"status_code",
")",
"return",
"self",
".",
"_reply_json",
"(",
"name_rec",
")"
] | Get the name's blockchain record in full
Reply the raw blockchain record on success
Reply 404 if the name is not found
Reply 502 if we have an error talking to the server | [
"Get",
"the",
"name",
"s",
"blockchain",
"record",
"in",
"full",
"Reply",
"the",
"raw",
"blockchain",
"record",
"on",
"success",
"Reply",
"404",
"if",
"the",
"name",
"is",
"not",
"found",
"Reply",
"502",
"if",
"we",
"have",
"an",
"error",
"talking",
"to",
"the",
"server"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1108-L1130 |
230,781 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpointHandler._get_balance | def _get_balance( self, get_address, min_confs ):
"""
Works only in test mode!
Get the confirmed balance for an address
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_passwd']
bitcoind = create_bitcoind_service_proxy(bitcoind_user, bitcoind_passwd, server=bitcoind_host, port=bitcoind_port)
address = virtualchain.address_reencode(get_address)
try:
unspents = get_unspents(address, bitcoind)
except Exception as e:
log.exception(e)
return {'error': 'Failed to get unspents for {}'.format(get_address)}
satoshis_confirmed = sum(confirmed_utxo['value'] for confirmed_utxo in
filter(lambda utxo: utxo['confirmations'] >= min_confs, unspents))
return {'balance': satoshis_confirmed} | python | def _get_balance( self, get_address, min_confs ):
"""
Works only in test mode!
Get the confirmed balance for an address
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_passwd']
bitcoind = create_bitcoind_service_proxy(bitcoind_user, bitcoind_passwd, server=bitcoind_host, port=bitcoind_port)
address = virtualchain.address_reencode(get_address)
try:
unspents = get_unspents(address, bitcoind)
except Exception as e:
log.exception(e)
return {'error': 'Failed to get unspents for {}'.format(get_address)}
satoshis_confirmed = sum(confirmed_utxo['value'] for confirmed_utxo in
filter(lambda utxo: utxo['confirmations'] >= min_confs, unspents))
return {'balance': satoshis_confirmed} | [
"def",
"_get_balance",
"(",
"self",
",",
"get_address",
",",
"min_confs",
")",
":",
"bitcoind_opts",
"=",
"get_bitcoin_opts",
"(",
")",
"bitcoind_host",
"=",
"bitcoind_opts",
"[",
"'bitcoind_server'",
"]",
"bitcoind_port",
"=",
"bitcoind_opts",
"[",
"'bitcoind_port'",
"]",
"bitcoind_user",
"=",
"bitcoind_opts",
"[",
"'bitcoind_user'",
"]",
"bitcoind_passwd",
"=",
"bitcoind_opts",
"[",
"'bitcoind_passwd'",
"]",
"bitcoind",
"=",
"create_bitcoind_service_proxy",
"(",
"bitcoind_user",
",",
"bitcoind_passwd",
",",
"server",
"=",
"bitcoind_host",
",",
"port",
"=",
"bitcoind_port",
")",
"address",
"=",
"virtualchain",
".",
"address_reencode",
"(",
"get_address",
")",
"try",
":",
"unspents",
"=",
"get_unspents",
"(",
"address",
",",
"bitcoind",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"{",
"'error'",
":",
"'Failed to get unspents for {}'",
".",
"format",
"(",
"get_address",
")",
"}",
"satoshis_confirmed",
"=",
"sum",
"(",
"confirmed_utxo",
"[",
"'value'",
"]",
"for",
"confirmed_utxo",
"in",
"filter",
"(",
"lambda",
"utxo",
":",
"utxo",
"[",
"'confirmations'",
"]",
">=",
"min_confs",
",",
"unspents",
")",
")",
"return",
"{",
"'balance'",
":",
"satoshis_confirmed",
"}"
] | Works only in test mode!
Get the confirmed balance for an address | [
"Works",
"only",
"in",
"test",
"mode!",
"Get",
"the",
"confirmed",
"balance",
"for",
"an",
"address"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1210-L1233 |
230,782 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpoint.bind | def bind(self):
"""
Bind to our port
"""
log.debug("Set SO_REUSADDR")
self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
# we want daemon threads, so we join on abrupt shutdown (applies if multithreaded)
self.daemon_threads = True
self.server_bind()
self.server_activate() | python | def bind(self):
"""
Bind to our port
"""
log.debug("Set SO_REUSADDR")
self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
# we want daemon threads, so we join on abrupt shutdown (applies if multithreaded)
self.daemon_threads = True
self.server_bind()
self.server_activate() | [
"def",
"bind",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Set SO_REUSADDR\"",
")",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"# we want daemon threads, so we join on abrupt shutdown (applies if multithreaded) ",
"self",
".",
"daemon_threads",
"=",
"True",
"self",
".",
"server_bind",
"(",
")",
"self",
".",
"server_activate",
"(",
")"
] | Bind to our port | [
"Bind",
"to",
"our",
"port"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1624-L1635 |
230,783 | blockstack/blockstack-core | blockstack/lib/rpc.py | BlockstackAPIEndpoint.overloaded | def overloaded(self, client_addr):
"""
Deflect if we have too many inbound requests
"""
overloaded_txt = 'HTTP/1.0 429 Too Many Requests\r\nServer: BaseHTTP/0.3 Python/2.7.14+\r\nContent-type: text/plain\r\nContent-length: 17\r\n\r\nToo many requests'
if BLOCKSTACK_TEST:
log.warn('Too many requests; deflecting {}'.format(client_addr))
return overloaded_txt | python | def overloaded(self, client_addr):
"""
Deflect if we have too many inbound requests
"""
overloaded_txt = 'HTTP/1.0 429 Too Many Requests\r\nServer: BaseHTTP/0.3 Python/2.7.14+\r\nContent-type: text/plain\r\nContent-length: 17\r\n\r\nToo many requests'
if BLOCKSTACK_TEST:
log.warn('Too many requests; deflecting {}'.format(client_addr))
return overloaded_txt | [
"def",
"overloaded",
"(",
"self",
",",
"client_addr",
")",
":",
"overloaded_txt",
"=",
"'HTTP/1.0 429 Too Many Requests\\r\\nServer: BaseHTTP/0.3 Python/2.7.14+\\r\\nContent-type: text/plain\\r\\nContent-length: 17\\r\\n\\r\\nToo many requests'",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"warn",
"(",
"'Too many requests; deflecting {}'",
".",
"format",
"(",
"client_addr",
")",
")",
"return",
"overloaded_txt"
] | Deflect if we have too many inbound requests | [
"Deflect",
"if",
"we",
"have",
"too",
"many",
"inbound",
"requests"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L1638-L1646 |
230,784 | ansible/ansible-container | container/utils/_text.py | to_bytes | def to_bytes(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a byte string
:arg obj: An object to make sure is a byte string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a text string to
a byte string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the text string is not
encodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. There are three additional error strategies
specifically aimed at helping people to port code. The first two are:
:surrogate_or_strict: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``strict``
:surrogate_or_replace: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``replace``.
Because ``surrogateescape`` was added in Python3 this usually means that
Python3 will use ``surrogateescape`` and Python2 will use the fallback
error handler. Note that the code checks for ``surrogateescape`` when the
module is imported. If you have a backport of ``surrogateescape`` for
Python2, be sure to register the error handler prior to importing this
module.
The last error handler is:
:surrogate_then_replace: Will use ``surrogateescape`` if it is a valid
handler. If encoding with ``surrogateescape`` would traceback,
surrogates are first replaced with a replacement characters
and then the string is encoded using ``replace`` (which replaces
the rest of the nonencodable bytes). If ``surrogateescape`` is
not present it will simply use ``replace``. (Added in Ansible 2.3)
This strategy is designed to never traceback when it attempts
to encode a string.
The default until Ansible-2.2 was ``surrogate_or_replace``
From Ansible-2.3 onwards, the default is ``surrogate_then_replace``.
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the bytes version of that string.
:empty: Return an empty byte string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a byte string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a text string.
.. note:: If passed a byte string, this function does not check that the
string is valid in the specified encoding. If it's important that the
byte string is in the specified encoding do::
encoded_string = to_bytes(to_text(input_string, 'latin-1'), 'utf-8')
.. version_changed:: 2.3
Added the ``surrogate_then_replace`` error handler and made it the default error handler.
"""
if isinstance(obj, binary_type):
return obj
# We're given a text string
# If it has surrogates, we know because it will decode
original_errors = errors
if errors in _COMPOSED_ERROR_HANDLERS:
if HAS_SURROGATEESCAPE:
errors = 'surrogateescape'
elif errors == 'surrogate_or_strict':
errors = 'strict'
else:
errors = 'replace'
if isinstance(obj, text_type):
try:
# Try this first as it's the fastest
return obj.encode(encoding, errors)
except UnicodeEncodeError:
if original_errors in (None, 'surrogate_then_replace'):
# Slow but works
return_string = obj.encode('utf-8', 'surrogateescape')
return_string = return_string.decode('utf-8', 'replace')
return return_string.encode(encoding, 'replace')
raise
# Note: We do these last even though we have to call to_bytes again on the
# value because we're optimizing the common case
if nonstring == 'simplerepr':
try:
value = str(obj)
except UnicodeError:
try:
value = repr(obj)
except UnicodeError:
# Giving up
return to_bytes('')
elif nonstring == 'passthru':
return obj
elif nonstring == 'empty':
# python2.4 doesn't have b''
return to_bytes('')
elif nonstring == 'strict':
raise TypeError('obj must be a string type')
else:
raise TypeError('Invalid value %s for to_bytes\' nonstring parameter' % nonstring)
return to_bytes(value, encoding, errors) | python | def to_bytes(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a byte string
:arg obj: An object to make sure is a byte string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a text string to
a byte string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the text string is not
encodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. There are three additional error strategies
specifically aimed at helping people to port code. The first two are:
:surrogate_or_strict: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``strict``
:surrogate_or_replace: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``replace``.
Because ``surrogateescape`` was added in Python3 this usually means that
Python3 will use ``surrogateescape`` and Python2 will use the fallback
error handler. Note that the code checks for ``surrogateescape`` when the
module is imported. If you have a backport of ``surrogateescape`` for
Python2, be sure to register the error handler prior to importing this
module.
The last error handler is:
:surrogate_then_replace: Will use ``surrogateescape`` if it is a valid
handler. If encoding with ``surrogateescape`` would traceback,
surrogates are first replaced with a replacement characters
and then the string is encoded using ``replace`` (which replaces
the rest of the nonencodable bytes). If ``surrogateescape`` is
not present it will simply use ``replace``. (Added in Ansible 2.3)
This strategy is designed to never traceback when it attempts
to encode a string.
The default until Ansible-2.2 was ``surrogate_or_replace``
From Ansible-2.3 onwards, the default is ``surrogate_then_replace``.
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the bytes version of that string.
:empty: Return an empty byte string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a byte string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a text string.
.. note:: If passed a byte string, this function does not check that the
string is valid in the specified encoding. If it's important that the
byte string is in the specified encoding do::
encoded_string = to_bytes(to_text(input_string, 'latin-1'), 'utf-8')
.. version_changed:: 2.3
Added the ``surrogate_then_replace`` error handler and made it the default error handler.
"""
if isinstance(obj, binary_type):
return obj
# We're given a text string
# If it has surrogates, we know because it will decode
original_errors = errors
if errors in _COMPOSED_ERROR_HANDLERS:
if HAS_SURROGATEESCAPE:
errors = 'surrogateescape'
elif errors == 'surrogate_or_strict':
errors = 'strict'
else:
errors = 'replace'
if isinstance(obj, text_type):
try:
# Try this first as it's the fastest
return obj.encode(encoding, errors)
except UnicodeEncodeError:
if original_errors in (None, 'surrogate_then_replace'):
# Slow but works
return_string = obj.encode('utf-8', 'surrogateescape')
return_string = return_string.decode('utf-8', 'replace')
return return_string.encode(encoding, 'replace')
raise
# Note: We do these last even though we have to call to_bytes again on the
# value because we're optimizing the common case
if nonstring == 'simplerepr':
try:
value = str(obj)
except UnicodeError:
try:
value = repr(obj)
except UnicodeError:
# Giving up
return to_bytes('')
elif nonstring == 'passthru':
return obj
elif nonstring == 'empty':
# python2.4 doesn't have b''
return to_bytes('')
elif nonstring == 'strict':
raise TypeError('obj must be a string type')
else:
raise TypeError('Invalid value %s for to_bytes\' nonstring parameter' % nonstring)
return to_bytes(value, encoding, errors) | [
"def",
"to_bytes",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"None",
",",
"nonstring",
"=",
"'simplerepr'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"return",
"obj",
"# We're given a text string",
"# If it has surrogates, we know because it will decode",
"original_errors",
"=",
"errors",
"if",
"errors",
"in",
"_COMPOSED_ERROR_HANDLERS",
":",
"if",
"HAS_SURROGATEESCAPE",
":",
"errors",
"=",
"'surrogateescape'",
"elif",
"errors",
"==",
"'surrogate_or_strict'",
":",
"errors",
"=",
"'strict'",
"else",
":",
"errors",
"=",
"'replace'",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"try",
":",
"# Try this first as it's the fastest",
"return",
"obj",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"except",
"UnicodeEncodeError",
":",
"if",
"original_errors",
"in",
"(",
"None",
",",
"'surrogate_then_replace'",
")",
":",
"# Slow but works",
"return_string",
"=",
"obj",
".",
"encode",
"(",
"'utf-8'",
",",
"'surrogateescape'",
")",
"return_string",
"=",
"return_string",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"return",
"return_string",
".",
"encode",
"(",
"encoding",
",",
"'replace'",
")",
"raise",
"# Note: We do these last even though we have to call to_bytes again on the",
"# value because we're optimizing the common case",
"if",
"nonstring",
"==",
"'simplerepr'",
":",
"try",
":",
"value",
"=",
"str",
"(",
"obj",
")",
"except",
"UnicodeError",
":",
"try",
":",
"value",
"=",
"repr",
"(",
"obj",
")",
"except",
"UnicodeError",
":",
"# Giving up",
"return",
"to_bytes",
"(",
"''",
")",
"elif",
"nonstring",
"==",
"'passthru'",
":",
"return",
"obj",
"elif",
"nonstring",
"==",
"'empty'",
":",
"# python2.4 doesn't have b''",
"return",
"to_bytes",
"(",
"''",
")",
"elif",
"nonstring",
"==",
"'strict'",
":",
"raise",
"TypeError",
"(",
"'obj must be a string type'",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid value %s for to_bytes\\' nonstring parameter'",
"%",
"nonstring",
")",
"return",
"to_bytes",
"(",
"value",
",",
"encoding",
",",
"errors",
")"
] | Make sure that a string is a byte string
:arg obj: An object to make sure is a byte string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a text string to
a byte string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the text string is not
encodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. There are three additional error strategies
specifically aimed at helping people to port code. The first two are:
:surrogate_or_strict: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``strict``
:surrogate_or_replace: Will use ``surrogateescape`` if it is a valid
handler, otherwise it will use ``replace``.
Because ``surrogateescape`` was added in Python3 this usually means that
Python3 will use ``surrogateescape`` and Python2 will use the fallback
error handler. Note that the code checks for ``surrogateescape`` when the
module is imported. If you have a backport of ``surrogateescape`` for
Python2, be sure to register the error handler prior to importing this
module.
The last error handler is:
:surrogate_then_replace: Will use ``surrogateescape`` if it is a valid
handler. If encoding with ``surrogateescape`` would traceback,
surrogates are first replaced with a replacement characters
and then the string is encoded using ``replace`` (which replaces
the rest of the nonencodable bytes). If ``surrogateescape`` is
not present it will simply use ``replace``. (Added in Ansible 2.3)
This strategy is designed to never traceback when it attempts
to encode a string.
The default until Ansible-2.2 was ``surrogate_or_replace``
From Ansible-2.3 onwards, the default is ``surrogate_then_replace``.
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the bytes version of that string.
:empty: Return an empty byte string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a byte string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a text string.
.. note:: If passed a byte string, this function does not check that the
string is valid in the specified encoding. If it's important that the
byte string is in the specified encoding do::
encoded_string = to_bytes(to_text(input_string, 'latin-1'), 'utf-8')
.. version_changed:: 2.3
Added the ``surrogate_then_replace`` error handler and made it the default error handler. | [
"Make",
"sure",
"that",
"a",
"string",
"is",
"a",
"byte",
"string"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/utils/_text.py#L52-L163 |
230,785 | ansible/ansible-container | container/utils/_text.py | to_text | def to_text(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. We support three additional error strategies
specifically aimed at helping people to port code:
:surrogate_or_strict: Will use surrogateescape if it is a valid
handler, otherwise it will use strict
:surrogate_or_replace: Will use surrogateescape if it is a valid
handler, otherwise it will use replace.
:surrogate_then_replace: Does the same as surrogate_or_replace but
`was added for symmetry with the error handlers in
:func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3)
Because surrogateescape was added in Python3 this usually means that
Python3 will use `surrogateescape` and Python2 will use the fallback
error handler. Note that the code checks for surrogateescape when the
module is imported. If you have a backport of `surrogateescape` for
python2, be sure to register the error handler prior to importing this
module.
The default until Ansible-2.2 was `surrogate_or_replace`
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry
with :func:`ansible.module_utils._text.to_bytes` .
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the text version of that string.
:empty: Return an empty text string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a text string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a byte string.
From Ansible-2.3 onwards, the default is `surrogate_then_replace`.
.. version_changed:: 2.3
Added the surrogate_then_replace error handler and made it the default error handler.
"""
if isinstance(obj, text_type):
return obj
if errors in _COMPOSED_ERROR_HANDLERS:
if HAS_SURROGATEESCAPE:
errors = 'surrogateescape'
elif errors == 'surrogate_or_strict':
errors = 'strict'
else:
errors = 'replace'
if isinstance(obj, binary_type):
# Note: We don't need special handling for surrogate_then_replace
# because all bytes will either be made into surrogates or are valid
# to decode.
return obj.decode(encoding, errors)
# Note: We do these last even though we have to call to_text again on the
# value because we're optimizing the common case
if nonstring == 'simplerepr':
try:
value = str(obj)
except UnicodeError:
try:
value = repr(obj)
except UnicodeError:
# Giving up
return u''
elif nonstring == 'passthru':
return obj
elif nonstring == 'empty':
return u''
elif nonstring == 'strict':
raise TypeError('obj must be a string type')
else:
raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring)
return to_text(value, encoding, errors) | python | def to_text(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. We support three additional error strategies
specifically aimed at helping people to port code:
:surrogate_or_strict: Will use surrogateescape if it is a valid
handler, otherwise it will use strict
:surrogate_or_replace: Will use surrogateescape if it is a valid
handler, otherwise it will use replace.
:surrogate_then_replace: Does the same as surrogate_or_replace but
`was added for symmetry with the error handlers in
:func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3)
Because surrogateescape was added in Python3 this usually means that
Python3 will use `surrogateescape` and Python2 will use the fallback
error handler. Note that the code checks for surrogateescape when the
module is imported. If you have a backport of `surrogateescape` for
python2, be sure to register the error handler prior to importing this
module.
The default until Ansible-2.2 was `surrogate_or_replace`
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry
with :func:`ansible.module_utils._text.to_bytes` .
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the text version of that string.
:empty: Return an empty text string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a text string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a byte string.
From Ansible-2.3 onwards, the default is `surrogate_then_replace`.
.. version_changed:: 2.3
Added the surrogate_then_replace error handler and made it the default error handler.
"""
if isinstance(obj, text_type):
return obj
if errors in _COMPOSED_ERROR_HANDLERS:
if HAS_SURROGATEESCAPE:
errors = 'surrogateescape'
elif errors == 'surrogate_or_strict':
errors = 'strict'
else:
errors = 'replace'
if isinstance(obj, binary_type):
# Note: We don't need special handling for surrogate_then_replace
# because all bytes will either be made into surrogates or are valid
# to decode.
return obj.decode(encoding, errors)
# Note: We do these last even though we have to call to_text again on the
# value because we're optimizing the common case
if nonstring == 'simplerepr':
try:
value = str(obj)
except UnicodeError:
try:
value = repr(obj)
except UnicodeError:
# Giving up
return u''
elif nonstring == 'passthru':
return obj
elif nonstring == 'empty':
return u''
elif nonstring == 'strict':
raise TypeError('obj must be a string type')
else:
raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring)
return to_text(value, encoding, errors) | [
"def",
"to_text",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"None",
",",
"nonstring",
"=",
"'simplerepr'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"return",
"obj",
"if",
"errors",
"in",
"_COMPOSED_ERROR_HANDLERS",
":",
"if",
"HAS_SURROGATEESCAPE",
":",
"errors",
"=",
"'surrogateescape'",
"elif",
"errors",
"==",
"'surrogate_or_strict'",
":",
"errors",
"=",
"'strict'",
"else",
":",
"errors",
"=",
"'replace'",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"# Note: We don't need special handling for surrogate_then_replace",
"# because all bytes will either be made into surrogates or are valid",
"# to decode.",
"return",
"obj",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"# Note: We do these last even though we have to call to_text again on the",
"# value because we're optimizing the common case",
"if",
"nonstring",
"==",
"'simplerepr'",
":",
"try",
":",
"value",
"=",
"str",
"(",
"obj",
")",
"except",
"UnicodeError",
":",
"try",
":",
"value",
"=",
"repr",
"(",
"obj",
")",
"except",
"UnicodeError",
":",
"# Giving up",
"return",
"u''",
"elif",
"nonstring",
"==",
"'passthru'",
":",
"return",
"obj",
"elif",
"nonstring",
"==",
"'empty'",
":",
"return",
"u''",
"elif",
"nonstring",
"==",
"'strict'",
":",
"raise",
"TypeError",
"(",
"'obj must be a string type'",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid value %s for to_text\\'s nonstring parameter'",
"%",
"nonstring",
")",
"return",
"to_text",
"(",
"value",
",",
"encoding",
",",
"errors",
")"
] | Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used as a traceback-free
version of ``str(obj)``.
:kwarg encoding: The encoding to use to transform from a byte string to
a text string. Defaults to using 'utf-8'.
:kwarg errors: The error handler to use if the byte string is not
decodable using the specified encoding. Any valid `codecs error
handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_
may be specified. We support three additional error strategies
specifically aimed at helping people to port code:
:surrogate_or_strict: Will use surrogateescape if it is a valid
handler, otherwise it will use strict
:surrogate_or_replace: Will use surrogateescape if it is a valid
handler, otherwise it will use replace.
:surrogate_then_replace: Does the same as surrogate_or_replace but
`was added for symmetry with the error handlers in
:func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3)
Because surrogateescape was added in Python3 this usually means that
Python3 will use `surrogateescape` and Python2 will use the fallback
error handler. Note that the code checks for surrogateescape when the
module is imported. If you have a backport of `surrogateescape` for
python2, be sure to register the error handler prior to importing this
module.
The default until Ansible-2.2 was `surrogate_or_replace`
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry
with :func:`ansible.module_utils._text.to_bytes` .
:kwarg nonstring: The strategy to use if a nonstring is specified in
``obj``. Default is 'simplerepr'. Valid values are:
:simplerepr: The default. This takes the ``str`` of the object and
then returns the text version of that string.
:empty: Return an empty text string
:passthru: Return the object passed in
:strict: Raise a :exc:`TypeError`
:returns: Typically this returns a text string. If a nonstring object is
passed in this may be a different type depending on the strategy
specified by nonstring. This will never return a byte string.
From Ansible-2.3 onwards, the default is `surrogate_then_replace`.
.. version_changed:: 2.3
Added the surrogate_then_replace error handler and made it the default error handler. | [
"Make",
"sure",
"that",
"a",
"string",
"is",
"a",
"text",
"string"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/utils/_text.py#L166-L254 |
230,786 | ansible/ansible-container | container/core.py | push_images | def push_images(base_path, image_namespace, engine_obj, config, **kwargs):
""" Pushes images to a Docker registry. Returns dict containing attributes used to push images. """
config_path = kwargs.get('config_path', engine_obj.auth_config_path)
username = kwargs.get('username')
password = kwargs.get('password')
push_to = kwargs.get('push_to')
url = engine_obj.default_registry_url
registry_name = engine_obj.default_registry_name
namespace = image_namespace
save_conductor = config.save_conductor
repository_prefix = None
pull_from_url = None
if push_to:
if config.get('registries', dict()).get(push_to):
url = config['registries'][push_to].get('url')
namespace = config['registries'][push_to].get('namespace', namespace)
repository_prefix = config['registries'][push_to].get('repository_prefix')
pull_from_url = config['registries'][push_to].get('pull_from_url')
if not url:
raise AnsibleContainerRegistryAttributeException(
u"Registry {} missing required attribute 'url'".format(push_to)
)
else:
url, namespace = resolve_push_to(push_to, engine_obj.default_registry_url, namespace)
if username and not password:
# If a username was supplied without a password, prompt for it
if url != engine_obj.default_registry_url:
registry_name = url
while not password:
password = getpass.getpass(u"Enter password for {0} at {1}: ".format(username, registry_name))
if config_path:
# Make sure the config_path exists
# - gives us a chance to create the file with correct permissions, if it does not exists
# - makes sure we mount a path to the conductor for a specific file
config_path = os.path.normpath(os.path.expanduser(config_path))
if os.path.exists(config_path) and os.path.isdir(config_path):
raise AnsibleContainerException(
u"Expecting --config-path to be a path to a file, not a directory"
)
elif not os.path.exists(config_path):
# Make sure the directory path exists
if not os.path.exists(os.path.dirname(config_path)):
try:
os.makedirs(os.path.dirname(config_path), 0o750)
except OSError:
raise AnsibleContainerException(
u"Failed to create the requested the path {}".format(os.path.dirname(config_path))
)
# Touch the file
open(config_path, 'w').close()
# If you ran build with --save-build-container, then you're broken without first removing
# the old build container.
remove_existing_container(engine_obj, 'conductor', remove_volumes=True)
push_params = {}
push_params.update(kwargs)
push_params['config_path'] = config_path
push_params['password'] = password
push_params['url'] = url
push_params['namespace'] = namespace
push_params['repository_prefix'] = repository_prefix
push_params['pull_from_url'] = pull_from_url
# Push
engine_obj.await_conductor_command('push', dict(config), base_path, push_params, save_container=save_conductor)
return {'url': url,
'namespace': namespace,
'repository_prefix': repository_prefix,
'pull_from_url': pull_from_url } | python | def push_images(base_path, image_namespace, engine_obj, config, **kwargs):
""" Pushes images to a Docker registry. Returns dict containing attributes used to push images. """
config_path = kwargs.get('config_path', engine_obj.auth_config_path)
username = kwargs.get('username')
password = kwargs.get('password')
push_to = kwargs.get('push_to')
url = engine_obj.default_registry_url
registry_name = engine_obj.default_registry_name
namespace = image_namespace
save_conductor = config.save_conductor
repository_prefix = None
pull_from_url = None
if push_to:
if config.get('registries', dict()).get(push_to):
url = config['registries'][push_to].get('url')
namespace = config['registries'][push_to].get('namespace', namespace)
repository_prefix = config['registries'][push_to].get('repository_prefix')
pull_from_url = config['registries'][push_to].get('pull_from_url')
if not url:
raise AnsibleContainerRegistryAttributeException(
u"Registry {} missing required attribute 'url'".format(push_to)
)
else:
url, namespace = resolve_push_to(push_to, engine_obj.default_registry_url, namespace)
if username and not password:
# If a username was supplied without a password, prompt for it
if url != engine_obj.default_registry_url:
registry_name = url
while not password:
password = getpass.getpass(u"Enter password for {0} at {1}: ".format(username, registry_name))
if config_path:
# Make sure the config_path exists
# - gives us a chance to create the file with correct permissions, if it does not exists
# - makes sure we mount a path to the conductor for a specific file
config_path = os.path.normpath(os.path.expanduser(config_path))
if os.path.exists(config_path) and os.path.isdir(config_path):
raise AnsibleContainerException(
u"Expecting --config-path to be a path to a file, not a directory"
)
elif not os.path.exists(config_path):
# Make sure the directory path exists
if not os.path.exists(os.path.dirname(config_path)):
try:
os.makedirs(os.path.dirname(config_path), 0o750)
except OSError:
raise AnsibleContainerException(
u"Failed to create the requested the path {}".format(os.path.dirname(config_path))
)
# Touch the file
open(config_path, 'w').close()
# If you ran build with --save-build-container, then you're broken without first removing
# the old build container.
remove_existing_container(engine_obj, 'conductor', remove_volumes=True)
push_params = {}
push_params.update(kwargs)
push_params['config_path'] = config_path
push_params['password'] = password
push_params['url'] = url
push_params['namespace'] = namespace
push_params['repository_prefix'] = repository_prefix
push_params['pull_from_url'] = pull_from_url
# Push
engine_obj.await_conductor_command('push', dict(config), base_path, push_params, save_container=save_conductor)
return {'url': url,
'namespace': namespace,
'repository_prefix': repository_prefix,
'pull_from_url': pull_from_url } | [
"def",
"push_images",
"(",
"base_path",
",",
"image_namespace",
",",
"engine_obj",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"config_path",
"=",
"kwargs",
".",
"get",
"(",
"'config_path'",
",",
"engine_obj",
".",
"auth_config_path",
")",
"username",
"=",
"kwargs",
".",
"get",
"(",
"'username'",
")",
"password",
"=",
"kwargs",
".",
"get",
"(",
"'password'",
")",
"push_to",
"=",
"kwargs",
".",
"get",
"(",
"'push_to'",
")",
"url",
"=",
"engine_obj",
".",
"default_registry_url",
"registry_name",
"=",
"engine_obj",
".",
"default_registry_name",
"namespace",
"=",
"image_namespace",
"save_conductor",
"=",
"config",
".",
"save_conductor",
"repository_prefix",
"=",
"None",
"pull_from_url",
"=",
"None",
"if",
"push_to",
":",
"if",
"config",
".",
"get",
"(",
"'registries'",
",",
"dict",
"(",
")",
")",
".",
"get",
"(",
"push_to",
")",
":",
"url",
"=",
"config",
"[",
"'registries'",
"]",
"[",
"push_to",
"]",
".",
"get",
"(",
"'url'",
")",
"namespace",
"=",
"config",
"[",
"'registries'",
"]",
"[",
"push_to",
"]",
".",
"get",
"(",
"'namespace'",
",",
"namespace",
")",
"repository_prefix",
"=",
"config",
"[",
"'registries'",
"]",
"[",
"push_to",
"]",
".",
"get",
"(",
"'repository_prefix'",
")",
"pull_from_url",
"=",
"config",
"[",
"'registries'",
"]",
"[",
"push_to",
"]",
".",
"get",
"(",
"'pull_from_url'",
")",
"if",
"not",
"url",
":",
"raise",
"AnsibleContainerRegistryAttributeException",
"(",
"u\"Registry {} missing required attribute 'url'\"",
".",
"format",
"(",
"push_to",
")",
")",
"else",
":",
"url",
",",
"namespace",
"=",
"resolve_push_to",
"(",
"push_to",
",",
"engine_obj",
".",
"default_registry_url",
",",
"namespace",
")",
"if",
"username",
"and",
"not",
"password",
":",
"# If a username was supplied without a password, prompt for it",
"if",
"url",
"!=",
"engine_obj",
".",
"default_registry_url",
":",
"registry_name",
"=",
"url",
"while",
"not",
"password",
":",
"password",
"=",
"getpass",
".",
"getpass",
"(",
"u\"Enter password for {0} at {1}: \"",
".",
"format",
"(",
"username",
",",
"registry_name",
")",
")",
"if",
"config_path",
":",
"# Make sure the config_path exists",
"# - gives us a chance to create the file with correct permissions, if it does not exists",
"# - makes sure we mount a path to the conductor for a specific file",
"config_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"config_path",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"config_path",
")",
":",
"raise",
"AnsibleContainerException",
"(",
"u\"Expecting --config-path to be a path to a file, not a directory\"",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"# Make sure the directory path exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_path",
")",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_path",
")",
",",
"0o750",
")",
"except",
"OSError",
":",
"raise",
"AnsibleContainerException",
"(",
"u\"Failed to create the requested the path {}\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_path",
")",
")",
")",
"# Touch the file",
"open",
"(",
"config_path",
",",
"'w'",
")",
".",
"close",
"(",
")",
"# If you ran build with --save-build-container, then you're broken without first removing",
"# the old build container.",
"remove_existing_container",
"(",
"engine_obj",
",",
"'conductor'",
",",
"remove_volumes",
"=",
"True",
")",
"push_params",
"=",
"{",
"}",
"push_params",
".",
"update",
"(",
"kwargs",
")",
"push_params",
"[",
"'config_path'",
"]",
"=",
"config_path",
"push_params",
"[",
"'password'",
"]",
"=",
"password",
"push_params",
"[",
"'url'",
"]",
"=",
"url",
"push_params",
"[",
"'namespace'",
"]",
"=",
"namespace",
"push_params",
"[",
"'repository_prefix'",
"]",
"=",
"repository_prefix",
"push_params",
"[",
"'pull_from_url'",
"]",
"=",
"pull_from_url",
"# Push",
"engine_obj",
".",
"await_conductor_command",
"(",
"'push'",
",",
"dict",
"(",
"config",
")",
",",
"base_path",
",",
"push_params",
",",
"save_container",
"=",
"save_conductor",
")",
"return",
"{",
"'url'",
":",
"url",
",",
"'namespace'",
":",
"namespace",
",",
"'repository_prefix'",
":",
"repository_prefix",
",",
"'pull_from_url'",
":",
"pull_from_url",
"}"
] | Pushes images to a Docker registry. Returns dict containing attributes used to push images. | [
"Pushes",
"images",
"to",
"a",
"Docker",
"registry",
".",
"Returns",
"dict",
"containing",
"attributes",
"used",
"to",
"push",
"images",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/core.py#L394-L467 |
230,787 | ansible/ansible-container | container/core.py | remove_existing_container | def remove_existing_container(engine_obj, service_name, remove_volumes=False):
"""
Remove a container for an existing service. Handy for removing an existing conductor.
"""
conductor_container_id = engine_obj.get_container_id_for_service(service_name)
if engine_obj.service_is_running(service_name):
engine_obj.stop_container(conductor_container_id, forcefully=True)
if conductor_container_id:
engine_obj.delete_container(conductor_container_id, remove_volumes=remove_volumes) | python | def remove_existing_container(engine_obj, service_name, remove_volumes=False):
"""
Remove a container for an existing service. Handy for removing an existing conductor.
"""
conductor_container_id = engine_obj.get_container_id_for_service(service_name)
if engine_obj.service_is_running(service_name):
engine_obj.stop_container(conductor_container_id, forcefully=True)
if conductor_container_id:
engine_obj.delete_container(conductor_container_id, remove_volumes=remove_volumes) | [
"def",
"remove_existing_container",
"(",
"engine_obj",
",",
"service_name",
",",
"remove_volumes",
"=",
"False",
")",
":",
"conductor_container_id",
"=",
"engine_obj",
".",
"get_container_id_for_service",
"(",
"service_name",
")",
"if",
"engine_obj",
".",
"service_is_running",
"(",
"service_name",
")",
":",
"engine_obj",
".",
"stop_container",
"(",
"conductor_container_id",
",",
"forcefully",
"=",
"True",
")",
"if",
"conductor_container_id",
":",
"engine_obj",
".",
"delete_container",
"(",
"conductor_container_id",
",",
"remove_volumes",
"=",
"remove_volumes",
")"
] | Remove a container for an existing service. Handy for removing an existing conductor. | [
"Remove",
"a",
"container",
"for",
"an",
"existing",
"service",
".",
"Handy",
"for",
"removing",
"an",
"existing",
"conductor",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/core.py#L510-L518 |
230,788 | ansible/ansible-container | container/core.py | resolve_push_to | def resolve_push_to(push_to, default_url, default_namespace):
'''
Given a push-to value, return the registry and namespace.
:param push_to: string: User supplied --push-to value.
:param default_url: string: Container engine's default_index value (e.g. docker.io).
:return: tuple: registry_url, namespace
'''
protocol = 'http://' if push_to.startswith('http://') else 'https://'
url = push_to = REMOVE_HTTP.sub('', push_to)
namespace = default_namespace
parts = url.split('/', 1)
special_set = {'.', ':'}
char_set = set([c for c in parts[0]])
if len(parts) == 1:
if not special_set.intersection(char_set) and parts[0] != 'localhost':
registry_url = default_url
namespace = push_to
else:
registry_url = protocol + parts[0]
else:
registry_url = protocol + parts[0]
namespace = parts[1]
return registry_url, namespace | python | def resolve_push_to(push_to, default_url, default_namespace):
'''
Given a push-to value, return the registry and namespace.
:param push_to: string: User supplied --push-to value.
:param default_url: string: Container engine's default_index value (e.g. docker.io).
:return: tuple: registry_url, namespace
'''
protocol = 'http://' if push_to.startswith('http://') else 'https://'
url = push_to = REMOVE_HTTP.sub('', push_to)
namespace = default_namespace
parts = url.split('/', 1)
special_set = {'.', ':'}
char_set = set([c for c in parts[0]])
if len(parts) == 1:
if not special_set.intersection(char_set) and parts[0] != 'localhost':
registry_url = default_url
namespace = push_to
else:
registry_url = protocol + parts[0]
else:
registry_url = protocol + parts[0]
namespace = parts[1]
return registry_url, namespace | [
"def",
"resolve_push_to",
"(",
"push_to",
",",
"default_url",
",",
"default_namespace",
")",
":",
"protocol",
"=",
"'http://'",
"if",
"push_to",
".",
"startswith",
"(",
"'http://'",
")",
"else",
"'https://'",
"url",
"=",
"push_to",
"=",
"REMOVE_HTTP",
".",
"sub",
"(",
"''",
",",
"push_to",
")",
"namespace",
"=",
"default_namespace",
"parts",
"=",
"url",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"special_set",
"=",
"{",
"'.'",
",",
"':'",
"}",
"char_set",
"=",
"set",
"(",
"[",
"c",
"for",
"c",
"in",
"parts",
"[",
"0",
"]",
"]",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"if",
"not",
"special_set",
".",
"intersection",
"(",
"char_set",
")",
"and",
"parts",
"[",
"0",
"]",
"!=",
"'localhost'",
":",
"registry_url",
"=",
"default_url",
"namespace",
"=",
"push_to",
"else",
":",
"registry_url",
"=",
"protocol",
"+",
"parts",
"[",
"0",
"]",
"else",
":",
"registry_url",
"=",
"protocol",
"+",
"parts",
"[",
"0",
"]",
"namespace",
"=",
"parts",
"[",
"1",
"]",
"return",
"registry_url",
",",
"namespace"
] | Given a push-to value, return the registry and namespace.
:param push_to: string: User supplied --push-to value.
:param default_url: string: Container engine's default_index value (e.g. docker.io).
:return: tuple: registry_url, namespace | [
"Given",
"a",
"push",
"-",
"to",
"value",
"return",
"the",
"registry",
"and",
"namespace",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/core.py#L522-L546 |
230,789 | ansible/ansible-container | container/core.py | conductorcmd_push | def conductorcmd_push(engine_name, project_name, services, **kwargs):
""" Push images to a registry """
username = kwargs.pop('username')
password = kwargs.pop('password')
email = kwargs.pop('email')
url = kwargs.pop('url')
namespace = kwargs.pop('namespace')
tag = kwargs.pop('tag')
config_path = kwargs.pop('config_path')
repository_prefix =kwargs.pop('repository_prefix')
engine = load_engine(['PUSH', 'LOGIN'], engine_name, project_name, services)
logger.info(u'Engine integration loaded. Preparing push.',
engine=engine.display_name)
# Verify that we can authenticate with the registry
username, password = engine.login(username, password, email, url, config_path)
# Push each image that has been built using Ansible roles
for name, service in iteritems(services):
if service.get('containers'):
for c in service['containers']:
if 'roles' in c:
cname = '%s-%s' % (name, c['container_name'])
image_id = engine.get_latest_image_id_for_service(cname)
engine.push(image_id, cname, url=url, tag=tag, namespace=namespace, username=username,
password=password, repository_prefix=repository_prefix)
elif 'roles' in service:
# if the service has roles, it's an image we should push
image_id = engine.get_latest_image_id_for_service(name)
engine.push(image_id, name, url=url, tag=tag, namespace=namespace, username=username,
password=password, repository_prefix=repository_prefix) | python | def conductorcmd_push(engine_name, project_name, services, **kwargs):
""" Push images to a registry """
username = kwargs.pop('username')
password = kwargs.pop('password')
email = kwargs.pop('email')
url = kwargs.pop('url')
namespace = kwargs.pop('namespace')
tag = kwargs.pop('tag')
config_path = kwargs.pop('config_path')
repository_prefix =kwargs.pop('repository_prefix')
engine = load_engine(['PUSH', 'LOGIN'], engine_name, project_name, services)
logger.info(u'Engine integration loaded. Preparing push.',
engine=engine.display_name)
# Verify that we can authenticate with the registry
username, password = engine.login(username, password, email, url, config_path)
# Push each image that has been built using Ansible roles
for name, service in iteritems(services):
if service.get('containers'):
for c in service['containers']:
if 'roles' in c:
cname = '%s-%s' % (name, c['container_name'])
image_id = engine.get_latest_image_id_for_service(cname)
engine.push(image_id, cname, url=url, tag=tag, namespace=namespace, username=username,
password=password, repository_prefix=repository_prefix)
elif 'roles' in service:
# if the service has roles, it's an image we should push
image_id = engine.get_latest_image_id_for_service(name)
engine.push(image_id, name, url=url, tag=tag, namespace=namespace, username=username,
password=password, repository_prefix=repository_prefix) | [
"def",
"conductorcmd_push",
"(",
"engine_name",
",",
"project_name",
",",
"services",
",",
"*",
"*",
"kwargs",
")",
":",
"username",
"=",
"kwargs",
".",
"pop",
"(",
"'username'",
")",
"password",
"=",
"kwargs",
".",
"pop",
"(",
"'password'",
")",
"email",
"=",
"kwargs",
".",
"pop",
"(",
"'email'",
")",
"url",
"=",
"kwargs",
".",
"pop",
"(",
"'url'",
")",
"namespace",
"=",
"kwargs",
".",
"pop",
"(",
"'namespace'",
")",
"tag",
"=",
"kwargs",
".",
"pop",
"(",
"'tag'",
")",
"config_path",
"=",
"kwargs",
".",
"pop",
"(",
"'config_path'",
")",
"repository_prefix",
"=",
"kwargs",
".",
"pop",
"(",
"'repository_prefix'",
")",
"engine",
"=",
"load_engine",
"(",
"[",
"'PUSH'",
",",
"'LOGIN'",
"]",
",",
"engine_name",
",",
"project_name",
",",
"services",
")",
"logger",
".",
"info",
"(",
"u'Engine integration loaded. Preparing push.'",
",",
"engine",
"=",
"engine",
".",
"display_name",
")",
"# Verify that we can authenticate with the registry",
"username",
",",
"password",
"=",
"engine",
".",
"login",
"(",
"username",
",",
"password",
",",
"email",
",",
"url",
",",
"config_path",
")",
"# Push each image that has been built using Ansible roles",
"for",
"name",
",",
"service",
"in",
"iteritems",
"(",
"services",
")",
":",
"if",
"service",
".",
"get",
"(",
"'containers'",
")",
":",
"for",
"c",
"in",
"service",
"[",
"'containers'",
"]",
":",
"if",
"'roles'",
"in",
"c",
":",
"cname",
"=",
"'%s-%s'",
"%",
"(",
"name",
",",
"c",
"[",
"'container_name'",
"]",
")",
"image_id",
"=",
"engine",
".",
"get_latest_image_id_for_service",
"(",
"cname",
")",
"engine",
".",
"push",
"(",
"image_id",
",",
"cname",
",",
"url",
"=",
"url",
",",
"tag",
"=",
"tag",
",",
"namespace",
"=",
"namespace",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"repository_prefix",
"=",
"repository_prefix",
")",
"elif",
"'roles'",
"in",
"service",
":",
"# if the service has roles, it's an image we should push",
"image_id",
"=",
"engine",
".",
"get_latest_image_id_for_service",
"(",
"name",
")",
"engine",
".",
"push",
"(",
"image_id",
",",
"name",
",",
"url",
"=",
"url",
",",
"tag",
"=",
"tag",
",",
"namespace",
"=",
"namespace",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"repository_prefix",
"=",
"repository_prefix",
")"
] | Push images to a registry | [
"Push",
"images",
"to",
"a",
"registry"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/core.py#L1038-L1069 |
230,790 | ansible/ansible-container | container/openshift/deploy.py | Deploy.get_route_templates | def get_route_templates(self):
"""
Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml
represents an externally exposed port.
"""
def _get_published_ports(service_config):
result = []
for port in service_config.get('ports', []):
protocol = 'TCP'
if isinstance(port, string_types) and '/' in port:
port, protocol = port.split('/')
if isinstance(port, string_types) and ':' in port:
host, container = port.split(':')
else:
host = port
result.append({'port': host, 'protocol': protocol.lower()})
return result
templates = []
for name, service_config in self._services.items():
state = service_config.get(self.CONFIG_KEY, {}).get('state', 'present')
force = service_config.get(self.CONFIG_KEY, {}).get('force', False)
published_ports = _get_published_ports(service_config)
if state != 'present':
continue
for port in published_ports:
route_name = "%s-%s" % (name, port['port'])
labels = dict(
app=self._namespace_name,
service=name
)
template = CommentedMap()
template['apiVersion'] = self.DEFAULT_API_VERSION
template['kind'] = 'Route'
template['force'] = force
template['metadata'] = CommentedMap([
('name', route_name),
('namespace', self._namespace_name),
('labels', labels.copy())
])
template['spec'] = CommentedMap([
('to', CommentedMap([
('kind', 'Service'),
('name', name)
])),
('port', CommentedMap([
('targetPort', 'port-{}-{}'.format(port['port'], port['protocol']))
]))
])
if service_config.get(self.CONFIG_KEY, {}).get('routes'):
for route in service_config[self.CONFIG_KEY]['routes']:
if str(route.get('port')) == str(port['port']):
for key, value in route.items():
if key not in ('force', 'port'):
self.copy_attribute(template['spec'], key, value)
templates.append(template)
return templates | python | def get_route_templates(self):
"""
Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml
represents an externally exposed port.
"""
def _get_published_ports(service_config):
result = []
for port in service_config.get('ports', []):
protocol = 'TCP'
if isinstance(port, string_types) and '/' in port:
port, protocol = port.split('/')
if isinstance(port, string_types) and ':' in port:
host, container = port.split(':')
else:
host = port
result.append({'port': host, 'protocol': protocol.lower()})
return result
templates = []
for name, service_config in self._services.items():
state = service_config.get(self.CONFIG_KEY, {}).get('state', 'present')
force = service_config.get(self.CONFIG_KEY, {}).get('force', False)
published_ports = _get_published_ports(service_config)
if state != 'present':
continue
for port in published_ports:
route_name = "%s-%s" % (name, port['port'])
labels = dict(
app=self._namespace_name,
service=name
)
template = CommentedMap()
template['apiVersion'] = self.DEFAULT_API_VERSION
template['kind'] = 'Route'
template['force'] = force
template['metadata'] = CommentedMap([
('name', route_name),
('namespace', self._namespace_name),
('labels', labels.copy())
])
template['spec'] = CommentedMap([
('to', CommentedMap([
('kind', 'Service'),
('name', name)
])),
('port', CommentedMap([
('targetPort', 'port-{}-{}'.format(port['port'], port['protocol']))
]))
])
if service_config.get(self.CONFIG_KEY, {}).get('routes'):
for route in service_config[self.CONFIG_KEY]['routes']:
if str(route.get('port')) == str(port['port']):
for key, value in route.items():
if key not in ('force', 'port'):
self.copy_attribute(template['spec'], key, value)
templates.append(template)
return templates | [
"def",
"get_route_templates",
"(",
"self",
")",
":",
"def",
"_get_published_ports",
"(",
"service_config",
")",
":",
"result",
"=",
"[",
"]",
"for",
"port",
"in",
"service_config",
".",
"get",
"(",
"'ports'",
",",
"[",
"]",
")",
":",
"protocol",
"=",
"'TCP'",
"if",
"isinstance",
"(",
"port",
",",
"string_types",
")",
"and",
"'/'",
"in",
"port",
":",
"port",
",",
"protocol",
"=",
"port",
".",
"split",
"(",
"'/'",
")",
"if",
"isinstance",
"(",
"port",
",",
"string_types",
")",
"and",
"':'",
"in",
"port",
":",
"host",
",",
"container",
"=",
"port",
".",
"split",
"(",
"':'",
")",
"else",
":",
"host",
"=",
"port",
"result",
".",
"append",
"(",
"{",
"'port'",
":",
"host",
",",
"'protocol'",
":",
"protocol",
".",
"lower",
"(",
")",
"}",
")",
"return",
"result",
"templates",
"=",
"[",
"]",
"for",
"name",
",",
"service_config",
"in",
"self",
".",
"_services",
".",
"items",
"(",
")",
":",
"state",
"=",
"service_config",
".",
"get",
"(",
"self",
".",
"CONFIG_KEY",
",",
"{",
"}",
")",
".",
"get",
"(",
"'state'",
",",
"'present'",
")",
"force",
"=",
"service_config",
".",
"get",
"(",
"self",
".",
"CONFIG_KEY",
",",
"{",
"}",
")",
".",
"get",
"(",
"'force'",
",",
"False",
")",
"published_ports",
"=",
"_get_published_ports",
"(",
"service_config",
")",
"if",
"state",
"!=",
"'present'",
":",
"continue",
"for",
"port",
"in",
"published_ports",
":",
"route_name",
"=",
"\"%s-%s\"",
"%",
"(",
"name",
",",
"port",
"[",
"'port'",
"]",
")",
"labels",
"=",
"dict",
"(",
"app",
"=",
"self",
".",
"_namespace_name",
",",
"service",
"=",
"name",
")",
"template",
"=",
"CommentedMap",
"(",
")",
"template",
"[",
"'apiVersion'",
"]",
"=",
"self",
".",
"DEFAULT_API_VERSION",
"template",
"[",
"'kind'",
"]",
"=",
"'Route'",
"template",
"[",
"'force'",
"]",
"=",
"force",
"template",
"[",
"'metadata'",
"]",
"=",
"CommentedMap",
"(",
"[",
"(",
"'name'",
",",
"route_name",
")",
",",
"(",
"'namespace'",
",",
"self",
".",
"_namespace_name",
")",
",",
"(",
"'labels'",
",",
"labels",
".",
"copy",
"(",
")",
")",
"]",
")",
"template",
"[",
"'spec'",
"]",
"=",
"CommentedMap",
"(",
"[",
"(",
"'to'",
",",
"CommentedMap",
"(",
"[",
"(",
"'kind'",
",",
"'Service'",
")",
",",
"(",
"'name'",
",",
"name",
")",
"]",
")",
")",
",",
"(",
"'port'",
",",
"CommentedMap",
"(",
"[",
"(",
"'targetPort'",
",",
"'port-{}-{}'",
".",
"format",
"(",
"port",
"[",
"'port'",
"]",
",",
"port",
"[",
"'protocol'",
"]",
")",
")",
"]",
")",
")",
"]",
")",
"if",
"service_config",
".",
"get",
"(",
"self",
".",
"CONFIG_KEY",
",",
"{",
"}",
")",
".",
"get",
"(",
"'routes'",
")",
":",
"for",
"route",
"in",
"service_config",
"[",
"self",
".",
"CONFIG_KEY",
"]",
"[",
"'routes'",
"]",
":",
"if",
"str",
"(",
"route",
".",
"get",
"(",
"'port'",
")",
")",
"==",
"str",
"(",
"port",
"[",
"'port'",
"]",
")",
":",
"for",
"key",
",",
"value",
"in",
"route",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'force'",
",",
"'port'",
")",
":",
"self",
".",
"copy_attribute",
"(",
"template",
"[",
"'spec'",
"]",
",",
"key",
",",
"value",
")",
"templates",
".",
"append",
"(",
"template",
")",
"return",
"templates"
] | Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml
represents an externally exposed port. | [
"Generate",
"Openshift",
"route",
"templates",
"or",
"playbook",
"tasks",
".",
"Each",
"port",
"on",
"a",
"service",
"definition",
"found",
"in",
"container",
".",
"yml",
"represents",
"an",
"externally",
"exposed",
"port",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/openshift/deploy.py#L56-L117 |
230,791 | ansible/ansible-container | container/docker/importer.py | DockerfileParser.preparse_iter | def preparse_iter(self):
"""
Comments can be anywhere. So break apart the Dockerfile into significant
lines and any comments that precede them. And if a line is a carryover
from the previous via an escaped-newline, bring the directive with it.
"""
to_yield = {}
last_directive = None
lines_processed = 0
for line in self.lines_iter():
if not line:
continue
if line.startswith(u'#'):
comment = line.lstrip('#').strip()
# Directives have to precede any instructions
if lines_processed == 1:
if comment.startswith(u'escape='):
self.escape_char = comment.split(u'=', 1)[1]
continue
to_yield.setdefault('comments', []).append(comment)
else:
# last_directive being set means the previous line ended with a
# newline escape
if last_directive:
directive, payload = last_directive, line
else:
directive, payload = line.split(u' ', 1)
if line.endswith(self.escape_char):
payload = payload.rstrip(self.escape_char)
last_directive = directive
else:
last_directive = None
to_yield['directive'] = directive
to_yield['payload'] = payload.strip()
yield to_yield
to_yield = {} | python | def preparse_iter(self):
"""
Comments can be anywhere. So break apart the Dockerfile into significant
lines and any comments that precede them. And if a line is a carryover
from the previous via an escaped-newline, bring the directive with it.
"""
to_yield = {}
last_directive = None
lines_processed = 0
for line in self.lines_iter():
if not line:
continue
if line.startswith(u'#'):
comment = line.lstrip('#').strip()
# Directives have to precede any instructions
if lines_processed == 1:
if comment.startswith(u'escape='):
self.escape_char = comment.split(u'=', 1)[1]
continue
to_yield.setdefault('comments', []).append(comment)
else:
# last_directive being set means the previous line ended with a
# newline escape
if last_directive:
directive, payload = last_directive, line
else:
directive, payload = line.split(u' ', 1)
if line.endswith(self.escape_char):
payload = payload.rstrip(self.escape_char)
last_directive = directive
else:
last_directive = None
to_yield['directive'] = directive
to_yield['payload'] = payload.strip()
yield to_yield
to_yield = {} | [
"def",
"preparse_iter",
"(",
"self",
")",
":",
"to_yield",
"=",
"{",
"}",
"last_directive",
"=",
"None",
"lines_processed",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"lines_iter",
"(",
")",
":",
"if",
"not",
"line",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",
"u'#'",
")",
":",
"comment",
"=",
"line",
".",
"lstrip",
"(",
"'#'",
")",
".",
"strip",
"(",
")",
"# Directives have to precede any instructions",
"if",
"lines_processed",
"==",
"1",
":",
"if",
"comment",
".",
"startswith",
"(",
"u'escape='",
")",
":",
"self",
".",
"escape_char",
"=",
"comment",
".",
"split",
"(",
"u'='",
",",
"1",
")",
"[",
"1",
"]",
"continue",
"to_yield",
".",
"setdefault",
"(",
"'comments'",
",",
"[",
"]",
")",
".",
"append",
"(",
"comment",
")",
"else",
":",
"# last_directive being set means the previous line ended with a",
"# newline escape",
"if",
"last_directive",
":",
"directive",
",",
"payload",
"=",
"last_directive",
",",
"line",
"else",
":",
"directive",
",",
"payload",
"=",
"line",
".",
"split",
"(",
"u' '",
",",
"1",
")",
"if",
"line",
".",
"endswith",
"(",
"self",
".",
"escape_char",
")",
":",
"payload",
"=",
"payload",
".",
"rstrip",
"(",
"self",
".",
"escape_char",
")",
"last_directive",
"=",
"directive",
"else",
":",
"last_directive",
"=",
"None",
"to_yield",
"[",
"'directive'",
"]",
"=",
"directive",
"to_yield",
"[",
"'payload'",
"]",
"=",
"payload",
".",
"strip",
"(",
")",
"yield",
"to_yield",
"to_yield",
"=",
"{",
"}"
] | Comments can be anywhere. So break apart the Dockerfile into significant
lines and any comments that precede them. And if a line is a carryover
from the previous via an escaped-newline, bring the directive with it. | [
"Comments",
"can",
"be",
"anywhere",
".",
"So",
"break",
"apart",
"the",
"Dockerfile",
"into",
"significant",
"lines",
"and",
"any",
"comments",
"that",
"precede",
"them",
".",
"And",
"if",
"a",
"line",
"is",
"a",
"carryover",
"from",
"the",
"previous",
"via",
"an",
"escaped",
"-",
"newline",
"bring",
"the",
"directive",
"with",
"it",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/importer.py#L120-L155 |
230,792 | ansible/ansible-container | container/docker/engine.py | Engine.run_container | def run_container(self, image_id, service_name, **kwargs):
"""Run a particular container. The kwargs argument contains individual
parameter overrides from the service definition."""
run_kwargs = self.run_kwargs_for_service(service_name)
run_kwargs.update(kwargs, relax=True)
logger.debug('Running container in docker', image=image_id, params=run_kwargs)
container_obj = self.client.containers.run(
image=image_id,
detach=True,
**run_kwargs
)
log_iter = container_obj.logs(stdout=True, stderr=True, stream=True)
mux = logmux.LogMultiplexer()
mux.add_iterator(log_iter, plainLogger)
return container_obj.id | python | def run_container(self, image_id, service_name, **kwargs):
"""Run a particular container. The kwargs argument contains individual
parameter overrides from the service definition."""
run_kwargs = self.run_kwargs_for_service(service_name)
run_kwargs.update(kwargs, relax=True)
logger.debug('Running container in docker', image=image_id, params=run_kwargs)
container_obj = self.client.containers.run(
image=image_id,
detach=True,
**run_kwargs
)
log_iter = container_obj.logs(stdout=True, stderr=True, stream=True)
mux = logmux.LogMultiplexer()
mux.add_iterator(log_iter, plainLogger)
return container_obj.id | [
"def",
"run_container",
"(",
"self",
",",
"image_id",
",",
"service_name",
",",
"*",
"*",
"kwargs",
")",
":",
"run_kwargs",
"=",
"self",
".",
"run_kwargs_for_service",
"(",
"service_name",
")",
"run_kwargs",
".",
"update",
"(",
"kwargs",
",",
"relax",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"'Running container in docker'",
",",
"image",
"=",
"image_id",
",",
"params",
"=",
"run_kwargs",
")",
"container_obj",
"=",
"self",
".",
"client",
".",
"containers",
".",
"run",
"(",
"image",
"=",
"image_id",
",",
"detach",
"=",
"True",
",",
"*",
"*",
"run_kwargs",
")",
"log_iter",
"=",
"container_obj",
".",
"logs",
"(",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stream",
"=",
"True",
")",
"mux",
"=",
"logmux",
".",
"LogMultiplexer",
"(",
")",
"mux",
".",
"add_iterator",
"(",
"log_iter",
",",
"plainLogger",
")",
"return",
"container_obj",
".",
"id"
] | Run a particular container. The kwargs argument contains individual
parameter overrides from the service definition. | [
"Run",
"a",
"particular",
"container",
".",
"The",
"kwargs",
"argument",
"contains",
"individual",
"parameter",
"overrides",
"from",
"the",
"service",
"definition",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/engine.py#L265-L281 |
230,793 | ansible/ansible-container | container/docker/engine.py | Engine.push | def push(self, image_id, service_name, tag=None, namespace=None, url=None, username=None, password=None,
repository_prefix=None, **kwargs):
"""
Push an image to a remote registry.
"""
auth_config = {
'username': username,
'password': password
}
build_stamp = self.get_build_stamp_for_image(image_id)
tag = tag or build_stamp
if repository_prefix:
image_name = "{}-{}".format(repository_prefix, service_name)
elif repository_prefix is None:
image_name = "{}-{}".format(self.project_name, service_name)
elif repository_prefix == '':
image_name = service_name
repository = "{}/{}".format(namespace, image_name)
if url != self.default_registry_url:
url = REMOVE_HTTP.sub('', url)
repository = "%s/%s" % (url.rstrip('/'), repository)
logger.info('Tagging %s' % repository)
self.client.api.tag(image_id, repository, tag=tag)
logger.info('Pushing %s:%s...' % (repository, tag))
stream = self.client.api.push(repository, tag=tag, stream=True, auth_config=auth_config)
last_status = None
for data in stream:
data = data.splitlines()
for line in data:
line = json.loads(line)
if type(line) is dict and 'error' in line:
plainLogger.error(line['error'])
raise exceptions.AnsibleContainerException(
"Failed to push image. {}".format(line['error'])
)
elif type(line) is dict and 'status' in line:
if line['status'] != last_status:
plainLogger.info(line['status'])
last_status = line['status']
else:
plainLogger.debug(line) | python | def push(self, image_id, service_name, tag=None, namespace=None, url=None, username=None, password=None,
repository_prefix=None, **kwargs):
"""
Push an image to a remote registry.
"""
auth_config = {
'username': username,
'password': password
}
build_stamp = self.get_build_stamp_for_image(image_id)
tag = tag or build_stamp
if repository_prefix:
image_name = "{}-{}".format(repository_prefix, service_name)
elif repository_prefix is None:
image_name = "{}-{}".format(self.project_name, service_name)
elif repository_prefix == '':
image_name = service_name
repository = "{}/{}".format(namespace, image_name)
if url != self.default_registry_url:
url = REMOVE_HTTP.sub('', url)
repository = "%s/%s" % (url.rstrip('/'), repository)
logger.info('Tagging %s' % repository)
self.client.api.tag(image_id, repository, tag=tag)
logger.info('Pushing %s:%s...' % (repository, tag))
stream = self.client.api.push(repository, tag=tag, stream=True, auth_config=auth_config)
last_status = None
for data in stream:
data = data.splitlines()
for line in data:
line = json.loads(line)
if type(line) is dict and 'error' in line:
plainLogger.error(line['error'])
raise exceptions.AnsibleContainerException(
"Failed to push image. {}".format(line['error'])
)
elif type(line) is dict and 'status' in line:
if line['status'] != last_status:
plainLogger.info(line['status'])
last_status = line['status']
else:
plainLogger.debug(line) | [
"def",
"push",
"(",
"self",
",",
"image_id",
",",
"service_name",
",",
"tag",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"url",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"repository_prefix",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_config",
"=",
"{",
"'username'",
":",
"username",
",",
"'password'",
":",
"password",
"}",
"build_stamp",
"=",
"self",
".",
"get_build_stamp_for_image",
"(",
"image_id",
")",
"tag",
"=",
"tag",
"or",
"build_stamp",
"if",
"repository_prefix",
":",
"image_name",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"repository_prefix",
",",
"service_name",
")",
"elif",
"repository_prefix",
"is",
"None",
":",
"image_name",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"self",
".",
"project_name",
",",
"service_name",
")",
"elif",
"repository_prefix",
"==",
"''",
":",
"image_name",
"=",
"service_name",
"repository",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"namespace",
",",
"image_name",
")",
"if",
"url",
"!=",
"self",
".",
"default_registry_url",
":",
"url",
"=",
"REMOVE_HTTP",
".",
"sub",
"(",
"''",
",",
"url",
")",
"repository",
"=",
"\"%s/%s\"",
"%",
"(",
"url",
".",
"rstrip",
"(",
"'/'",
")",
",",
"repository",
")",
"logger",
".",
"info",
"(",
"'Tagging %s'",
"%",
"repository",
")",
"self",
".",
"client",
".",
"api",
".",
"tag",
"(",
"image_id",
",",
"repository",
",",
"tag",
"=",
"tag",
")",
"logger",
".",
"info",
"(",
"'Pushing %s:%s...'",
"%",
"(",
"repository",
",",
"tag",
")",
")",
"stream",
"=",
"self",
".",
"client",
".",
"api",
".",
"push",
"(",
"repository",
",",
"tag",
"=",
"tag",
",",
"stream",
"=",
"True",
",",
"auth_config",
"=",
"auth_config",
")",
"last_status",
"=",
"None",
"for",
"data",
"in",
"stream",
":",
"data",
"=",
"data",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"data",
":",
"line",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"if",
"type",
"(",
"line",
")",
"is",
"dict",
"and",
"'error'",
"in",
"line",
":",
"plainLogger",
".",
"error",
"(",
"line",
"[",
"'error'",
"]",
")",
"raise",
"exceptions",
".",
"AnsibleContainerException",
"(",
"\"Failed to push image. {}\"",
".",
"format",
"(",
"line",
"[",
"'error'",
"]",
")",
")",
"elif",
"type",
"(",
"line",
")",
"is",
"dict",
"and",
"'status'",
"in",
"line",
":",
"if",
"line",
"[",
"'status'",
"]",
"!=",
"last_status",
":",
"plainLogger",
".",
"info",
"(",
"line",
"[",
"'status'",
"]",
")",
"last_status",
"=",
"line",
"[",
"'status'",
"]",
"else",
":",
"plainLogger",
".",
"debug",
"(",
"line",
")"
] | Push an image to a remote registry. | [
"Push",
"an",
"image",
"to",
"a",
"remote",
"registry",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/engine.py#L895-L941 |
230,794 | ansible/ansible-container | container/docker/engine.py | Engine.login | def login(self, username, password, email, url, config_path):
"""
If username and password are provided, authenticate with the registry.
Otherwise, check the config file for existing authentication data.
"""
if username and password:
try:
self.client.login(username=username, password=password, email=email,
registry=url, reauth=True)
except docker_errors.APIError as exc:
raise exceptions.AnsibleContainerConductorException(
u"Error logging into registry: {}".format(exc)
)
except Exception:
raise
self._update_config_file(username, password, email, url, config_path)
username, password = self._get_registry_auth(url, config_path)
if not username:
raise exceptions.AnsibleContainerConductorException(
u'Please provide login credentials for registry {}.'.format(url))
return username, password | python | def login(self, username, password, email, url, config_path):
"""
If username and password are provided, authenticate with the registry.
Otherwise, check the config file for existing authentication data.
"""
if username and password:
try:
self.client.login(username=username, password=password, email=email,
registry=url, reauth=True)
except docker_errors.APIError as exc:
raise exceptions.AnsibleContainerConductorException(
u"Error logging into registry: {}".format(exc)
)
except Exception:
raise
self._update_config_file(username, password, email, url, config_path)
username, password = self._get_registry_auth(url, config_path)
if not username:
raise exceptions.AnsibleContainerConductorException(
u'Please provide login credentials for registry {}.'.format(url))
return username, password | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"email",
",",
"url",
",",
"config_path",
")",
":",
"if",
"username",
"and",
"password",
":",
"try",
":",
"self",
".",
"client",
".",
"login",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"email",
"=",
"email",
",",
"registry",
"=",
"url",
",",
"reauth",
"=",
"True",
")",
"except",
"docker_errors",
".",
"APIError",
"as",
"exc",
":",
"raise",
"exceptions",
".",
"AnsibleContainerConductorException",
"(",
"u\"Error logging into registry: {}\"",
".",
"format",
"(",
"exc",
")",
")",
"except",
"Exception",
":",
"raise",
"self",
".",
"_update_config_file",
"(",
"username",
",",
"password",
",",
"email",
",",
"url",
",",
"config_path",
")",
"username",
",",
"password",
"=",
"self",
".",
"_get_registry_auth",
"(",
"url",
",",
"config_path",
")",
"if",
"not",
"username",
":",
"raise",
"exceptions",
".",
"AnsibleContainerConductorException",
"(",
"u'Please provide login credentials for registry {}.'",
".",
"format",
"(",
"url",
")",
")",
"return",
"username",
",",
"password"
] | If username and password are provided, authenticate with the registry.
Otherwise, check the config file for existing authentication data. | [
"If",
"username",
"and",
"password",
"are",
"provided",
"authenticate",
"with",
"the",
"registry",
".",
"Otherwise",
"check",
"the",
"config",
"file",
"for",
"existing",
"authentication",
"data",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/engine.py#L1186-L1208 |
230,795 | ansible/ansible-container | container/docker/engine.py | Engine._update_config_file | def _update_config_file(username, password, email, url, config_path):
"""Update the config file with the authorization."""
try:
# read the existing config
config = json.load(open(config_path, "r"))
except ValueError:
config = dict()
if not config.get('auths'):
config['auths'] = dict()
if not config['auths'].get(url):
config['auths'][url] = dict()
encoded_credentials = dict(
auth=base64.b64encode(username + b':' + password),
email=email
)
config['auths'][url] = encoded_credentials
try:
json.dump(config, open(config_path, "w"), indent=5, sort_keys=True)
except Exception as exc:
raise exceptions.AnsibleContainerConductorException(
u"Failed to write registry config to {0} - {1}".format(config_path, exc)
) | python | def _update_config_file(username, password, email, url, config_path):
"""Update the config file with the authorization."""
try:
# read the existing config
config = json.load(open(config_path, "r"))
except ValueError:
config = dict()
if not config.get('auths'):
config['auths'] = dict()
if not config['auths'].get(url):
config['auths'][url] = dict()
encoded_credentials = dict(
auth=base64.b64encode(username + b':' + password),
email=email
)
config['auths'][url] = encoded_credentials
try:
json.dump(config, open(config_path, "w"), indent=5, sort_keys=True)
except Exception as exc:
raise exceptions.AnsibleContainerConductorException(
u"Failed to write registry config to {0} - {1}".format(config_path, exc)
) | [
"def",
"_update_config_file",
"(",
"username",
",",
"password",
",",
"email",
",",
"url",
",",
"config_path",
")",
":",
"try",
":",
"# read the existing config",
"config",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"config_path",
",",
"\"r\"",
")",
")",
"except",
"ValueError",
":",
"config",
"=",
"dict",
"(",
")",
"if",
"not",
"config",
".",
"get",
"(",
"'auths'",
")",
":",
"config",
"[",
"'auths'",
"]",
"=",
"dict",
"(",
")",
"if",
"not",
"config",
"[",
"'auths'",
"]",
".",
"get",
"(",
"url",
")",
":",
"config",
"[",
"'auths'",
"]",
"[",
"url",
"]",
"=",
"dict",
"(",
")",
"encoded_credentials",
"=",
"dict",
"(",
"auth",
"=",
"base64",
".",
"b64encode",
"(",
"username",
"+",
"b':'",
"+",
"password",
")",
",",
"email",
"=",
"email",
")",
"config",
"[",
"'auths'",
"]",
"[",
"url",
"]",
"=",
"encoded_credentials",
"try",
":",
"json",
".",
"dump",
"(",
"config",
",",
"open",
"(",
"config_path",
",",
"\"w\"",
")",
",",
"indent",
"=",
"5",
",",
"sort_keys",
"=",
"True",
")",
"except",
"Exception",
"as",
"exc",
":",
"raise",
"exceptions",
".",
"AnsibleContainerConductorException",
"(",
"u\"Failed to write registry config to {0} - {1}\"",
".",
"format",
"(",
"config_path",
",",
"exc",
")",
")"
] | Update the config file with the authorization. | [
"Update",
"the",
"config",
"file",
"with",
"the",
"authorization",
"."
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/engine.py#L1212-L1235 |
230,796 | ansible/ansible-container | container/docker/engine.py | Engine._get_registry_auth | def _get_registry_auth(registry_url, config_path):
"""
Retrieve from the config file the current authentication for a given URL, and
return the username, password
"""
username = None
password = None
try:
docker_config = json.load(open(config_path))
except ValueError:
# The configuration file is empty
return username, password
if docker_config.get('auths'):
docker_config = docker_config['auths']
auth_key = docker_config.get(registry_url, {}).get('auth', None)
if auth_key:
username, password = base64.b64decode(auth_key).split(':', 1)
return username, password | python | def _get_registry_auth(registry_url, config_path):
"""
Retrieve from the config file the current authentication for a given URL, and
return the username, password
"""
username = None
password = None
try:
docker_config = json.load(open(config_path))
except ValueError:
# The configuration file is empty
return username, password
if docker_config.get('auths'):
docker_config = docker_config['auths']
auth_key = docker_config.get(registry_url, {}).get('auth', None)
if auth_key:
username, password = base64.b64decode(auth_key).split(':', 1)
return username, password | [
"def",
"_get_registry_auth",
"(",
"registry_url",
",",
"config_path",
")",
":",
"username",
"=",
"None",
"password",
"=",
"None",
"try",
":",
"docker_config",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"config_path",
")",
")",
"except",
"ValueError",
":",
"# The configuration file is empty",
"return",
"username",
",",
"password",
"if",
"docker_config",
".",
"get",
"(",
"'auths'",
")",
":",
"docker_config",
"=",
"docker_config",
"[",
"'auths'",
"]",
"auth_key",
"=",
"docker_config",
".",
"get",
"(",
"registry_url",
",",
"{",
"}",
")",
".",
"get",
"(",
"'auth'",
",",
"None",
")",
"if",
"auth_key",
":",
"username",
",",
"password",
"=",
"base64",
".",
"b64decode",
"(",
"auth_key",
")",
".",
"split",
"(",
"':'",
",",
"1",
")",
"return",
"username",
",",
"password"
] | Retrieve from the config file the current authentication for a given URL, and
return the username, password | [
"Retrieve",
"from",
"the",
"config",
"file",
"the",
"current",
"authentication",
"for",
"a",
"given",
"URL",
"and",
"return",
"the",
"username",
"password"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/engine.py#L1239-L1256 |
230,797 | ansible/ansible-container | container/utils/__init__.py | resolve_role_to_path | def resolve_role_to_path(role):
"""
Given a role definition from a service's list of roles, returns the file path to the role
"""
loader = DataLoader()
try:
variable_manager = VariableManager(loader=loader)
except TypeError:
# If Ansible prior to ansible/ansible@8f97aef1a365
variable_manager = VariableManager()
role_obj = RoleInclude.load(data=role, play=None,
variable_manager=variable_manager,
loader=loader)
return role_obj._role_path | python | def resolve_role_to_path(role):
"""
Given a role definition from a service's list of roles, returns the file path to the role
"""
loader = DataLoader()
try:
variable_manager = VariableManager(loader=loader)
except TypeError:
# If Ansible prior to ansible/ansible@8f97aef1a365
variable_manager = VariableManager()
role_obj = RoleInclude.load(data=role, play=None,
variable_manager=variable_manager,
loader=loader)
return role_obj._role_path | [
"def",
"resolve_role_to_path",
"(",
"role",
")",
":",
"loader",
"=",
"DataLoader",
"(",
")",
"try",
":",
"variable_manager",
"=",
"VariableManager",
"(",
"loader",
"=",
"loader",
")",
"except",
"TypeError",
":",
"# If Ansible prior to ansible/ansible@8f97aef1a365",
"variable_manager",
"=",
"VariableManager",
"(",
")",
"role_obj",
"=",
"RoleInclude",
".",
"load",
"(",
"data",
"=",
"role",
",",
"play",
"=",
"None",
",",
"variable_manager",
"=",
"variable_manager",
",",
"loader",
"=",
"loader",
")",
"return",
"role_obj",
".",
"_role_path"
] | Given a role definition from a service's list of roles, returns the file path to the role | [
"Given",
"a",
"role",
"definition",
"from",
"a",
"service",
"s",
"list",
"of",
"roles",
"returns",
"the",
"file",
"path",
"to",
"the",
"role"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/utils/__init__.py#L225-L238 |
230,798 | ansible/ansible-container | container/utils/__init__.py | get_role_fingerprint | def get_role_fingerprint(role, service_name, config_vars):
"""
Given a role definition from a service's list of roles, returns a hexdigest based on the role definition,
the role contents, and the hexdigest of each dependency
"""
def hash_file(hash_obj, file_path):
blocksize = 64 * 1024
with open(file_path, 'rb') as ifs:
while True:
data = ifs.read(blocksize)
if not data:
break
hash_obj.update(data)
hash_obj.update('::')
def hash_dir(hash_obj, dir_path):
for root, dirs, files in os.walk(dir_path, topdown=True):
for file_path in files:
abs_file_path = os.path.join(root, file_path)
hash_obj.update(abs_file_path.encode('utf-8'))
hash_obj.update('::')
hash_file(hash_obj, abs_file_path)
def hash_role(hash_obj, role_path):
# Role content is easy to hash - the hash of the role content with the
# hash of any role dependencies it has
hash_dir(hash_obj, role_path)
for dependency in get_dependencies_for_role(role_path):
if dependency:
dependency_path = resolve_role_to_path(dependency)
hash_role(hash_obj, dependency_path)
# However tasks within that role might reference files outside of the
# role, like source code
loader = DataLoader()
var_man = VariableManager(loader=loader)
play = Play.load(generate_playbook_for_role(service_name, config_vars, role)[0],
variable_manager=var_man, loader=loader)
play_context = PlayContext(play=play)
inv_man = InventoryManager(loader, sources=['%s,' % service_name])
host = Host(service_name)
iterator = PlayIterator(inv_man, play, play_context, var_man, config_vars)
while True:
_, task = iterator.get_next_task_for_host(host)
if task is None: break
if task.action in FILE_COPY_MODULES:
src = task.args.get('src')
if src is not None:
if not os.path.exists(src) or not src.startswith(('/', '..')): continue
src = os.path.realpath(src)
if os.path.isfile(src):
hash_file(hash_obj, src)
else:
hash_dir(hash_obj, src)
def get_dependencies_for_role(role_path):
meta_main_path = os.path.join(role_path, 'meta', 'main.yml')
if os.path.exists(meta_main_path):
meta_main = yaml.safe_load(open(meta_main_path))
if meta_main:
for dependency in meta_main.get('dependencies', []):
yield dependency.get('role', None)
hash_obj = hashlib.sha256()
# Account for variables passed to the role by including the invocation string
hash_obj.update((json.dumps(role) if not isinstance(role, string_types) else role) + '::')
# Add each of the role's files and directories
hash_role(hash_obj, resolve_role_to_path(role))
return hash_obj.hexdigest() | python | def get_role_fingerprint(role, service_name, config_vars):
"""
Given a role definition from a service's list of roles, returns a hexdigest based on the role definition,
the role contents, and the hexdigest of each dependency
"""
def hash_file(hash_obj, file_path):
blocksize = 64 * 1024
with open(file_path, 'rb') as ifs:
while True:
data = ifs.read(blocksize)
if not data:
break
hash_obj.update(data)
hash_obj.update('::')
def hash_dir(hash_obj, dir_path):
for root, dirs, files in os.walk(dir_path, topdown=True):
for file_path in files:
abs_file_path = os.path.join(root, file_path)
hash_obj.update(abs_file_path.encode('utf-8'))
hash_obj.update('::')
hash_file(hash_obj, abs_file_path)
def hash_role(hash_obj, role_path):
# Role content is easy to hash - the hash of the role content with the
# hash of any role dependencies it has
hash_dir(hash_obj, role_path)
for dependency in get_dependencies_for_role(role_path):
if dependency:
dependency_path = resolve_role_to_path(dependency)
hash_role(hash_obj, dependency_path)
# However tasks within that role might reference files outside of the
# role, like source code
loader = DataLoader()
var_man = VariableManager(loader=loader)
play = Play.load(generate_playbook_for_role(service_name, config_vars, role)[0],
variable_manager=var_man, loader=loader)
play_context = PlayContext(play=play)
inv_man = InventoryManager(loader, sources=['%s,' % service_name])
host = Host(service_name)
iterator = PlayIterator(inv_man, play, play_context, var_man, config_vars)
while True:
_, task = iterator.get_next_task_for_host(host)
if task is None: break
if task.action in FILE_COPY_MODULES:
src = task.args.get('src')
if src is not None:
if not os.path.exists(src) or not src.startswith(('/', '..')): continue
src = os.path.realpath(src)
if os.path.isfile(src):
hash_file(hash_obj, src)
else:
hash_dir(hash_obj, src)
def get_dependencies_for_role(role_path):
meta_main_path = os.path.join(role_path, 'meta', 'main.yml')
if os.path.exists(meta_main_path):
meta_main = yaml.safe_load(open(meta_main_path))
if meta_main:
for dependency in meta_main.get('dependencies', []):
yield dependency.get('role', None)
hash_obj = hashlib.sha256()
# Account for variables passed to the role by including the invocation string
hash_obj.update((json.dumps(role) if not isinstance(role, string_types) else role) + '::')
# Add each of the role's files and directories
hash_role(hash_obj, resolve_role_to_path(role))
return hash_obj.hexdigest() | [
"def",
"get_role_fingerprint",
"(",
"role",
",",
"service_name",
",",
"config_vars",
")",
":",
"def",
"hash_file",
"(",
"hash_obj",
",",
"file_path",
")",
":",
"blocksize",
"=",
"64",
"*",
"1024",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"ifs",
":",
"while",
"True",
":",
"data",
"=",
"ifs",
".",
"read",
"(",
"blocksize",
")",
"if",
"not",
"data",
":",
"break",
"hash_obj",
".",
"update",
"(",
"data",
")",
"hash_obj",
".",
"update",
"(",
"'::'",
")",
"def",
"hash_dir",
"(",
"hash_obj",
",",
"dir_path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir_path",
",",
"topdown",
"=",
"True",
")",
":",
"for",
"file_path",
"in",
"files",
":",
"abs_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file_path",
")",
"hash_obj",
".",
"update",
"(",
"abs_file_path",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"hash_obj",
".",
"update",
"(",
"'::'",
")",
"hash_file",
"(",
"hash_obj",
",",
"abs_file_path",
")",
"def",
"hash_role",
"(",
"hash_obj",
",",
"role_path",
")",
":",
"# Role content is easy to hash - the hash of the role content with the",
"# hash of any role dependencies it has",
"hash_dir",
"(",
"hash_obj",
",",
"role_path",
")",
"for",
"dependency",
"in",
"get_dependencies_for_role",
"(",
"role_path",
")",
":",
"if",
"dependency",
":",
"dependency_path",
"=",
"resolve_role_to_path",
"(",
"dependency",
")",
"hash_role",
"(",
"hash_obj",
",",
"dependency_path",
")",
"# However tasks within that role might reference files outside of the",
"# role, like source code",
"loader",
"=",
"DataLoader",
"(",
")",
"var_man",
"=",
"VariableManager",
"(",
"loader",
"=",
"loader",
")",
"play",
"=",
"Play",
".",
"load",
"(",
"generate_playbook_for_role",
"(",
"service_name",
",",
"config_vars",
",",
"role",
")",
"[",
"0",
"]",
",",
"variable_manager",
"=",
"var_man",
",",
"loader",
"=",
"loader",
")",
"play_context",
"=",
"PlayContext",
"(",
"play",
"=",
"play",
")",
"inv_man",
"=",
"InventoryManager",
"(",
"loader",
",",
"sources",
"=",
"[",
"'%s,'",
"%",
"service_name",
"]",
")",
"host",
"=",
"Host",
"(",
"service_name",
")",
"iterator",
"=",
"PlayIterator",
"(",
"inv_man",
",",
"play",
",",
"play_context",
",",
"var_man",
",",
"config_vars",
")",
"while",
"True",
":",
"_",
",",
"task",
"=",
"iterator",
".",
"get_next_task_for_host",
"(",
"host",
")",
"if",
"task",
"is",
"None",
":",
"break",
"if",
"task",
".",
"action",
"in",
"FILE_COPY_MODULES",
":",
"src",
"=",
"task",
".",
"args",
".",
"get",
"(",
"'src'",
")",
"if",
"src",
"is",
"not",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"src",
")",
"or",
"not",
"src",
".",
"startswith",
"(",
"(",
"'/'",
",",
"'..'",
")",
")",
":",
"continue",
"src",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"src",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"src",
")",
":",
"hash_file",
"(",
"hash_obj",
",",
"src",
")",
"else",
":",
"hash_dir",
"(",
"hash_obj",
",",
"src",
")",
"def",
"get_dependencies_for_role",
"(",
"role_path",
")",
":",
"meta_main_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"role_path",
",",
"'meta'",
",",
"'main.yml'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"meta_main_path",
")",
":",
"meta_main",
"=",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"meta_main_path",
")",
")",
"if",
"meta_main",
":",
"for",
"dependency",
"in",
"meta_main",
".",
"get",
"(",
"'dependencies'",
",",
"[",
"]",
")",
":",
"yield",
"dependency",
".",
"get",
"(",
"'role'",
",",
"None",
")",
"hash_obj",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"# Account for variables passed to the role by including the invocation string",
"hash_obj",
".",
"update",
"(",
"(",
"json",
".",
"dumps",
"(",
"role",
")",
"if",
"not",
"isinstance",
"(",
"role",
",",
"string_types",
")",
"else",
"role",
")",
"+",
"'::'",
")",
"# Add each of the role's files and directories",
"hash_role",
"(",
"hash_obj",
",",
"resolve_role_to_path",
"(",
"role",
")",
")",
"return",
"hash_obj",
".",
"hexdigest",
"(",
")"
] | Given a role definition from a service's list of roles, returns a hexdigest based on the role definition,
the role contents, and the hexdigest of each dependency | [
"Given",
"a",
"role",
"definition",
"from",
"a",
"service",
"s",
"list",
"of",
"roles",
"returns",
"a",
"hexdigest",
"based",
"on",
"the",
"role",
"definition",
"the",
"role",
"contents",
"and",
"the",
"hexdigest",
"of",
"each",
"dependency"
] | d031c1a6133d5482a5d054fcbdbecafb923f8b4b | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/utils/__init__.py#L256-L323 |
230,799 | litl/backoff | backoff/_decorator.py | on_predicate | def on_predicate(wait_gen,
predicate=operator.not_,
max_tries=None,
max_time=None,
jitter=full_jitter,
on_success=None,
on_backoff=None,
on_giveup=None,
logger='backoff',
**wait_gen_kwargs):
"""Returns decorator for backoff and retry triggered by predicate.
Args:
wait_gen: A generator yielding successive wait times in
seconds.
predicate: A function which when called on the return value of
the target function will trigger backoff when considered
truthily. If not specified, the default behavior is to
backoff on falsey return values.
max_tries: The maximum number of attempts to make before giving
up. In the case of failure, the result of the last attempt
will be returned. The default value of None means there
is no limit to the number of tries. If a callable is passed,
it will be evaluated at runtime and its return value used.
max_time: The maximum total amount of time to try for before
giving up. If this time expires, the result of the last
attempt will be returned. If a callable is passed, it will
be evaluated at runtime and its return value used.
jitter: A function of the value yielded by wait_gen returning
the actual time to wait. This distributes wait times
stochastically in order to avoid timing collisions across
concurrent clients. Wait times are jittered by default
using the full_jitter function. Jittering may be disabled
altogether by passing jitter=None.
on_success: Callable (or iterable of callables) with a unary
signature to be called in the event of success. The
parameter is a dict containing details about the invocation.
on_backoff: Callable (or iterable of callables) with a unary
signature to be called in the event of a backoff. The
parameter is a dict containing details about the invocation.
on_giveup: Callable (or iterable of callables) with a unary
signature to be called in the event that max_tries
is exceeded. The parameter is a dict containing details
about the invocation.
logger: Name of logger or Logger object to log to. Defaults to
'backoff'.
**wait_gen_kwargs: Any additional keyword args specified will be
passed to wait_gen when it is initialized. Any callable
args will first be evaluated and their return values passed.
This is useful for runtime configuration.
"""
def decorate(target):
# change names because python 2.x doesn't have nonlocal
logger_ = logger
if isinstance(logger_, basestring):
logger_ = logging.getLogger(logger_)
on_success_ = _config_handlers(on_success)
on_backoff_ = _config_handlers(on_backoff, _log_backoff, logger_)
on_giveup_ = _config_handlers(on_giveup, _log_giveup, logger_)
retry = None
if sys.version_info >= (3, 5): # pragma: python=3.5
import asyncio
if asyncio.iscoroutinefunction(target):
import backoff._async
retry = backoff._async.retry_predicate
elif _is_event_loop() and _is_current_task():
# Verify that sync version is not being run from coroutine
# (that would lead to event loop hiccups).
raise TypeError(
"backoff.on_predicate applied to a regular function "
"inside coroutine, this will lead to event loop "
"hiccups. Use backoff.on_predicate on coroutines in "
"asynchronous code.")
if retry is None:
retry = _sync.retry_predicate
return retry(target, wait_gen, predicate,
max_tries, max_time, jitter,
on_success_, on_backoff_, on_giveup_,
wait_gen_kwargs)
# Return a function which decorates a target with a retry loop.
return decorate | python | def on_predicate(wait_gen,
predicate=operator.not_,
max_tries=None,
max_time=None,
jitter=full_jitter,
on_success=None,
on_backoff=None,
on_giveup=None,
logger='backoff',
**wait_gen_kwargs):
"""Returns decorator for backoff and retry triggered by predicate.
Args:
wait_gen: A generator yielding successive wait times in
seconds.
predicate: A function which when called on the return value of
the target function will trigger backoff when considered
truthily. If not specified, the default behavior is to
backoff on falsey return values.
max_tries: The maximum number of attempts to make before giving
up. In the case of failure, the result of the last attempt
will be returned. The default value of None means there
is no limit to the number of tries. If a callable is passed,
it will be evaluated at runtime and its return value used.
max_time: The maximum total amount of time to try for before
giving up. If this time expires, the result of the last
attempt will be returned. If a callable is passed, it will
be evaluated at runtime and its return value used.
jitter: A function of the value yielded by wait_gen returning
the actual time to wait. This distributes wait times
stochastically in order to avoid timing collisions across
concurrent clients. Wait times are jittered by default
using the full_jitter function. Jittering may be disabled
altogether by passing jitter=None.
on_success: Callable (or iterable of callables) with a unary
signature to be called in the event of success. The
parameter is a dict containing details about the invocation.
on_backoff: Callable (or iterable of callables) with a unary
signature to be called in the event of a backoff. The
parameter is a dict containing details about the invocation.
on_giveup: Callable (or iterable of callables) with a unary
signature to be called in the event that max_tries
is exceeded. The parameter is a dict containing details
about the invocation.
logger: Name of logger or Logger object to log to. Defaults to
'backoff'.
**wait_gen_kwargs: Any additional keyword args specified will be
passed to wait_gen when it is initialized. Any callable
args will first be evaluated and their return values passed.
This is useful for runtime configuration.
"""
def decorate(target):
# change names because python 2.x doesn't have nonlocal
logger_ = logger
if isinstance(logger_, basestring):
logger_ = logging.getLogger(logger_)
on_success_ = _config_handlers(on_success)
on_backoff_ = _config_handlers(on_backoff, _log_backoff, logger_)
on_giveup_ = _config_handlers(on_giveup, _log_giveup, logger_)
retry = None
if sys.version_info >= (3, 5): # pragma: python=3.5
import asyncio
if asyncio.iscoroutinefunction(target):
import backoff._async
retry = backoff._async.retry_predicate
elif _is_event_loop() and _is_current_task():
# Verify that sync version is not being run from coroutine
# (that would lead to event loop hiccups).
raise TypeError(
"backoff.on_predicate applied to a regular function "
"inside coroutine, this will lead to event loop "
"hiccups. Use backoff.on_predicate on coroutines in "
"asynchronous code.")
if retry is None:
retry = _sync.retry_predicate
return retry(target, wait_gen, predicate,
max_tries, max_time, jitter,
on_success_, on_backoff_, on_giveup_,
wait_gen_kwargs)
# Return a function which decorates a target with a retry loop.
return decorate | [
"def",
"on_predicate",
"(",
"wait_gen",
",",
"predicate",
"=",
"operator",
".",
"not_",
",",
"max_tries",
"=",
"None",
",",
"max_time",
"=",
"None",
",",
"jitter",
"=",
"full_jitter",
",",
"on_success",
"=",
"None",
",",
"on_backoff",
"=",
"None",
",",
"on_giveup",
"=",
"None",
",",
"logger",
"=",
"'backoff'",
",",
"*",
"*",
"wait_gen_kwargs",
")",
":",
"def",
"decorate",
"(",
"target",
")",
":",
"# change names because python 2.x doesn't have nonlocal",
"logger_",
"=",
"logger",
"if",
"isinstance",
"(",
"logger_",
",",
"basestring",
")",
":",
"logger_",
"=",
"logging",
".",
"getLogger",
"(",
"logger_",
")",
"on_success_",
"=",
"_config_handlers",
"(",
"on_success",
")",
"on_backoff_",
"=",
"_config_handlers",
"(",
"on_backoff",
",",
"_log_backoff",
",",
"logger_",
")",
"on_giveup_",
"=",
"_config_handlers",
"(",
"on_giveup",
",",
"_log_giveup",
",",
"logger_",
")",
"retry",
"=",
"None",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
")",
":",
"# pragma: python=3.5",
"import",
"asyncio",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"target",
")",
":",
"import",
"backoff",
".",
"_async",
"retry",
"=",
"backoff",
".",
"_async",
".",
"retry_predicate",
"elif",
"_is_event_loop",
"(",
")",
"and",
"_is_current_task",
"(",
")",
":",
"# Verify that sync version is not being run from coroutine",
"# (that would lead to event loop hiccups).",
"raise",
"TypeError",
"(",
"\"backoff.on_predicate applied to a regular function \"",
"\"inside coroutine, this will lead to event loop \"",
"\"hiccups. Use backoff.on_predicate on coroutines in \"",
"\"asynchronous code.\"",
")",
"if",
"retry",
"is",
"None",
":",
"retry",
"=",
"_sync",
".",
"retry_predicate",
"return",
"retry",
"(",
"target",
",",
"wait_gen",
",",
"predicate",
",",
"max_tries",
",",
"max_time",
",",
"jitter",
",",
"on_success_",
",",
"on_backoff_",
",",
"on_giveup_",
",",
"wait_gen_kwargs",
")",
"# Return a function which decorates a target with a retry loop.",
"return",
"decorate"
] | Returns decorator for backoff and retry triggered by predicate.
Args:
wait_gen: A generator yielding successive wait times in
seconds.
predicate: A function which when called on the return value of
the target function will trigger backoff when considered
truthily. If not specified, the default behavior is to
backoff on falsey return values.
max_tries: The maximum number of attempts to make before giving
up. In the case of failure, the result of the last attempt
will be returned. The default value of None means there
is no limit to the number of tries. If a callable is passed,
it will be evaluated at runtime and its return value used.
max_time: The maximum total amount of time to try for before
giving up. If this time expires, the result of the last
attempt will be returned. If a callable is passed, it will
be evaluated at runtime and its return value used.
jitter: A function of the value yielded by wait_gen returning
the actual time to wait. This distributes wait times
stochastically in order to avoid timing collisions across
concurrent clients. Wait times are jittered by default
using the full_jitter function. Jittering may be disabled
altogether by passing jitter=None.
on_success: Callable (or iterable of callables) with a unary
signature to be called in the event of success. The
parameter is a dict containing details about the invocation.
on_backoff: Callable (or iterable of callables) with a unary
signature to be called in the event of a backoff. The
parameter is a dict containing details about the invocation.
on_giveup: Callable (or iterable of callables) with a unary
signature to be called in the event that max_tries
is exceeded. The parameter is a dict containing details
about the invocation.
logger: Name of logger or Logger object to log to. Defaults to
'backoff'.
**wait_gen_kwargs: Any additional keyword args specified will be
passed to wait_gen when it is initialized. Any callable
args will first be evaluated and their return values passed.
This is useful for runtime configuration. | [
"Returns",
"decorator",
"for",
"backoff",
"and",
"retry",
"triggered",
"by",
"predicate",
"."
] | 229d30adce4128f093550a1761c49594c78df4b4 | https://github.com/litl/backoff/blob/229d30adce4128f093550a1761c49594c78df4b4/backoff/_decorator.py#L20-L106 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.