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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
blockstack/blockstack-core | blockstack/lib/scripts.py | check_account_address | def check_account_address(address):
"""
verify that a string is a valid account address.
Can be a b58-check address, a c32-check address, as well as the string "treasury" or "unallocated" or a string starting with 'not_distributed_'
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_account_address('treasury')
True
>>> check_account_address('unallocated')
True
>>> check_account_address('neither')
False
>>> check_account_address('not_distributed')
False
>>> check_account_address('not_distributed_')
False
>>> check_account_address('not_distributed_asdfasdfasdfasdf')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ8')
False
"""
if address == 'treasury' or address == 'unallocated':
return True
if address.startswith('not_distributed_') and len(address) > len('not_distributed_'):
return True
if re.match(OP_C32CHECK_PATTERN, address):
try:
c32addressDecode(address)
return True
except:
pass
return check_address(address) | python | def check_account_address(address):
"""
verify that a string is a valid account address.
Can be a b58-check address, a c32-check address, as well as the string "treasury" or "unallocated" or a string starting with 'not_distributed_'
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_account_address('treasury')
True
>>> check_account_address('unallocated')
True
>>> check_account_address('neither')
False
>>> check_account_address('not_distributed')
False
>>> check_account_address('not_distributed_')
False
>>> check_account_address('not_distributed_asdfasdfasdfasdf')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ8')
False
"""
if address == 'treasury' or address == 'unallocated':
return True
if address.startswith('not_distributed_') and len(address) > len('not_distributed_'):
return True
if re.match(OP_C32CHECK_PATTERN, address):
try:
c32addressDecode(address)
return True
except:
pass
return check_address(address) | [
"def",
"check_account_address",
"(",
"address",
")",
":",
"if",
"address",
"==",
"'treasury'",
"or",
"address",
"==",
"'unallocated'",
":",
"return",
"True",
"if",
"address",
".",
"startswith",
"(",
"'not_distributed_'",
")",
"and",
"len",
"(",
"address",
")",... | verify that a string is a valid account address.
Can be a b58-check address, a c32-check address, as well as the string "treasury" or "unallocated" or a string starting with 'not_distributed_'
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_account_address('treasury')
True
>>> check_account_address('unallocated')
True
>>> check_account_address('neither')
False
>>> check_account_address('not_distributed')
False
>>> check_account_address('not_distributed_')
False
>>> check_account_address('not_distributed_asdfasdfasdfasdf')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
True
>>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ8')
False | [
"verify",
"that",
"a",
"string",
"is",
"a",
"valid",
"account",
"address",
".",
"Can",
"be",
"a",
"b58",
"-",
"check",
"address",
"a",
"c32",
"-",
"check",
"address",
"as",
"well",
"as",
"the",
"string",
"treasury",
"or",
"unallocated",
"or",
"a",
"str... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L692-L731 | train | 225,500 |
blockstack/blockstack-core | blockstack/lib/scripts.py | check_tx_output_types | def check_tx_output_types(outputs, block_height):
"""
Verify that the list of transaction outputs are acceptable
"""
# for now, we do not allow nonstandard outputs (all outputs must be p2pkh or p2sh outputs)
# this excludes bech32 outputs, for example.
supported_output_types = get_epoch_btc_script_types(block_height)
for out in outputs:
out_type = virtualchain.btc_script_classify(out['script'])
if out_type not in supported_output_types:
log.warning('Unsupported output type {} ({})'.format(out_type, out['script']))
return False
return True | python | def check_tx_output_types(outputs, block_height):
"""
Verify that the list of transaction outputs are acceptable
"""
# for now, we do not allow nonstandard outputs (all outputs must be p2pkh or p2sh outputs)
# this excludes bech32 outputs, for example.
supported_output_types = get_epoch_btc_script_types(block_height)
for out in outputs:
out_type = virtualchain.btc_script_classify(out['script'])
if out_type not in supported_output_types:
log.warning('Unsupported output type {} ({})'.format(out_type, out['script']))
return False
return True | [
"def",
"check_tx_output_types",
"(",
"outputs",
",",
"block_height",
")",
":",
"# for now, we do not allow nonstandard outputs (all outputs must be p2pkh or p2sh outputs)",
"# this excludes bech32 outputs, for example.",
"supported_output_types",
"=",
"get_epoch_btc_script_types",
"(",
"... | Verify that the list of transaction outputs are acceptable | [
"Verify",
"that",
"the",
"list",
"of",
"transaction",
"outputs",
"are",
"acceptable"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L734-L747 | train | 225,501 |
blockstack/blockstack-core | blockstack/lib/scripts.py | address_as_b58 | def address_as_b58(addr):
"""
Given a b58check or c32check address,
return the b58check encoding
"""
if is_c32_address(addr):
return c32ToB58(addr)
else:
if check_address(addr):
return addr
else:
raise ValueError('Address {} is not b58 or c32'.format(addr)) | python | def address_as_b58(addr):
"""
Given a b58check or c32check address,
return the b58check encoding
"""
if is_c32_address(addr):
return c32ToB58(addr)
else:
if check_address(addr):
return addr
else:
raise ValueError('Address {} is not b58 or c32'.format(addr)) | [
"def",
"address_as_b58",
"(",
"addr",
")",
":",
"if",
"is_c32_address",
"(",
"addr",
")",
":",
"return",
"c32ToB58",
"(",
"addr",
")",
"else",
":",
"if",
"check_address",
"(",
"addr",
")",
":",
"return",
"addr",
"else",
":",
"raise",
"ValueError",
"(",
... | Given a b58check or c32check address,
return the b58check encoding | [
"Given",
"a",
"b58check",
"or",
"c32check",
"address",
"return",
"the",
"b58check",
"encoding"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L770-L782 | train | 225,502 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | verify | def verify(address, plaintext, scriptSigb64):
"""
Verify that a given plaintext is signed by the given scriptSig, given the address
"""
assert isinstance(address, str)
assert isinstance(scriptSigb64, str)
scriptSig = base64.b64decode(scriptSigb64)
hash_hex = hashlib.sha256(plaintext).hexdigest()
vb = keylib.b58check.b58check_version_byte(address)
if vb == bitcoin_blockchain.version_byte:
return verify_singlesig(address, hash_hex, scriptSig)
elif vb == bitcoin_blockchain.multisig_version_byte:
return verify_multisig(address, hash_hex, scriptSig)
else:
log.warning("Unrecognized address version byte {}".format(vb))
raise NotImplementedError("Addresses must be single-sig (version-byte = 0) or multi-sig (version-byte = 5)") | python | def verify(address, plaintext, scriptSigb64):
"""
Verify that a given plaintext is signed by the given scriptSig, given the address
"""
assert isinstance(address, str)
assert isinstance(scriptSigb64, str)
scriptSig = base64.b64decode(scriptSigb64)
hash_hex = hashlib.sha256(plaintext).hexdigest()
vb = keylib.b58check.b58check_version_byte(address)
if vb == bitcoin_blockchain.version_byte:
return verify_singlesig(address, hash_hex, scriptSig)
elif vb == bitcoin_blockchain.multisig_version_byte:
return verify_multisig(address, hash_hex, scriptSig)
else:
log.warning("Unrecognized address version byte {}".format(vb))
raise NotImplementedError("Addresses must be single-sig (version-byte = 0) or multi-sig (version-byte = 5)") | [
"def",
"verify",
"(",
"address",
",",
"plaintext",
",",
"scriptSigb64",
")",
":",
"assert",
"isinstance",
"(",
"address",
",",
"str",
")",
"assert",
"isinstance",
"(",
"scriptSigb64",
",",
"str",
")",
"scriptSig",
"=",
"base64",
".",
"b64decode",
"(",
"scr... | Verify that a given plaintext is signed by the given scriptSig, given the address | [
"Verify",
"that",
"a",
"given",
"plaintext",
"is",
"signed",
"by",
"the",
"given",
"scriptSig",
"given",
"the",
"address"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1727-L1745 | train | 225,503 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | verify_singlesig | def verify_singlesig(address, hash_hex, scriptSig):
"""
Verify that a p2pkh address is signed by the given pay-to-pubkey-hash scriptsig
"""
try:
sighex, pubkey_hex = virtualchain.btc_script_deserialize(scriptSig)
except:
log.warn("Wrong signature structure for {}".format(address))
return False
# verify pubkey_hex corresponds to address
if virtualchain.address_reencode(keylib.public_key_to_address(pubkey_hex)) != virtualchain.address_reencode(address):
log.warn(("Address {} does not match signature script {}".format(address, scriptSig.encode('hex'))))
return False
sig64 = base64.b64encode(binascii.unhexlify(sighex))
return virtualchain.ecdsalib.verify_digest(hash_hex, pubkey_hex, sig64) | python | def verify_singlesig(address, hash_hex, scriptSig):
"""
Verify that a p2pkh address is signed by the given pay-to-pubkey-hash scriptsig
"""
try:
sighex, pubkey_hex = virtualchain.btc_script_deserialize(scriptSig)
except:
log.warn("Wrong signature structure for {}".format(address))
return False
# verify pubkey_hex corresponds to address
if virtualchain.address_reencode(keylib.public_key_to_address(pubkey_hex)) != virtualchain.address_reencode(address):
log.warn(("Address {} does not match signature script {}".format(address, scriptSig.encode('hex'))))
return False
sig64 = base64.b64encode(binascii.unhexlify(sighex))
return virtualchain.ecdsalib.verify_digest(hash_hex, pubkey_hex, sig64) | [
"def",
"verify_singlesig",
"(",
"address",
",",
"hash_hex",
",",
"scriptSig",
")",
":",
"try",
":",
"sighex",
",",
"pubkey_hex",
"=",
"virtualchain",
".",
"btc_script_deserialize",
"(",
"scriptSig",
")",
"except",
":",
"log",
".",
"warn",
"(",
"\"Wrong signatu... | Verify that a p2pkh address is signed by the given pay-to-pubkey-hash scriptsig | [
"Verify",
"that",
"a",
"p2pkh",
"address",
"is",
"signed",
"by",
"the",
"given",
"pay",
"-",
"to",
"-",
"pubkey",
"-",
"hash",
"scriptsig"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1748-L1764 | train | 225,504 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | verify_multisig | def verify_multisig(address, hash_hex, scriptSig):
"""
verify that a p2sh address is signed by the given scriptsig
"""
script_parts = virtualchain.btc_script_deserialize(scriptSig)
if len(script_parts) < 2:
log.warn("Verfiying multisig failed, couldn't grab script parts")
return False
redeem_script = script_parts[-1]
script_sigs = script_parts[1:-1]
if virtualchain.address_reencode(virtualchain.btc_make_p2sh_address(redeem_script)) != virtualchain.address_reencode(address):
log.warn(("Address {} does not match redeem script {}".format(address, redeem_script)))
return False
m, pubk_hexes = virtualchain.parse_multisig_redeemscript(redeem_script)
if len(script_sigs) != m:
log.warn("Failed to validate multi-sig, not correct number of signatures: have {}, require {}".format(
len(script_sigs), m))
return False
cur_pubk = 0
for cur_sig in script_sigs:
sig64 = base64.b64encode(binascii.unhexlify(cur_sig))
sig_passed = False
while not sig_passed:
if cur_pubk >= len(pubk_hexes):
log.warn("Failed to validate multi-signature, ran out of public keys to check")
return False
sig_passed = virtualchain.ecdsalib.verify_digest(hash_hex, pubk_hexes[cur_pubk], sig64)
cur_pubk += 1
return True | python | def verify_multisig(address, hash_hex, scriptSig):
"""
verify that a p2sh address is signed by the given scriptsig
"""
script_parts = virtualchain.btc_script_deserialize(scriptSig)
if len(script_parts) < 2:
log.warn("Verfiying multisig failed, couldn't grab script parts")
return False
redeem_script = script_parts[-1]
script_sigs = script_parts[1:-1]
if virtualchain.address_reencode(virtualchain.btc_make_p2sh_address(redeem_script)) != virtualchain.address_reencode(address):
log.warn(("Address {} does not match redeem script {}".format(address, redeem_script)))
return False
m, pubk_hexes = virtualchain.parse_multisig_redeemscript(redeem_script)
if len(script_sigs) != m:
log.warn("Failed to validate multi-sig, not correct number of signatures: have {}, require {}".format(
len(script_sigs), m))
return False
cur_pubk = 0
for cur_sig in script_sigs:
sig64 = base64.b64encode(binascii.unhexlify(cur_sig))
sig_passed = False
while not sig_passed:
if cur_pubk >= len(pubk_hexes):
log.warn("Failed to validate multi-signature, ran out of public keys to check")
return False
sig_passed = virtualchain.ecdsalib.verify_digest(hash_hex, pubk_hexes[cur_pubk], sig64)
cur_pubk += 1
return True | [
"def",
"verify_multisig",
"(",
"address",
",",
"hash_hex",
",",
"scriptSig",
")",
":",
"script_parts",
"=",
"virtualchain",
".",
"btc_script_deserialize",
"(",
"scriptSig",
")",
"if",
"len",
"(",
"script_parts",
")",
"<",
"2",
":",
"log",
".",
"warn",
"(",
... | verify that a p2sh address is signed by the given scriptsig | [
"verify",
"that",
"a",
"p2sh",
"address",
"is",
"signed",
"by",
"the",
"given",
"scriptsig"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1767-L1800 | train | 225,505 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | is_subdomain_missing_zonefiles_record | def is_subdomain_missing_zonefiles_record(rec):
"""
Does a given parsed zone file TXT record encode a missing-zonefile vector?
Return True if so
Return False if not
"""
if rec['name'] != SUBDOMAIN_TXT_RR_MISSING:
return False
txt_entry = rec['txt']
if isinstance(txt_entry, list):
return False
missing = txt_entry.split(',')
try:
for m in missing:
m = int(m)
except ValueError:
return False
return True | python | def is_subdomain_missing_zonefiles_record(rec):
"""
Does a given parsed zone file TXT record encode a missing-zonefile vector?
Return True if so
Return False if not
"""
if rec['name'] != SUBDOMAIN_TXT_RR_MISSING:
return False
txt_entry = rec['txt']
if isinstance(txt_entry, list):
return False
missing = txt_entry.split(',')
try:
for m in missing:
m = int(m)
except ValueError:
return False
return True | [
"def",
"is_subdomain_missing_zonefiles_record",
"(",
"rec",
")",
":",
"if",
"rec",
"[",
"'name'",
"]",
"!=",
"SUBDOMAIN_TXT_RR_MISSING",
":",
"return",
"False",
"txt_entry",
"=",
"rec",
"[",
"'txt'",
"]",
"if",
"isinstance",
"(",
"txt_entry",
",",
"list",
")",... | Does a given parsed zone file TXT record encode a missing-zonefile vector?
Return True if so
Return False if not | [
"Does",
"a",
"given",
"parsed",
"zone",
"file",
"TXT",
"record",
"encode",
"a",
"missing",
"-",
"zonefile",
"vector?",
"Return",
"True",
"if",
"so",
"Return",
"False",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1810-L1830 | train | 225,506 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | is_subdomain_record | def is_subdomain_record(rec):
"""
Does a given parsed zone file TXT record (@rec) encode a subdomain?
Return True if so
Return False if not
"""
txt_entry = rec['txt']
if not isinstance(txt_entry, list):
return False
has_parts_entry = False
has_pk_entry = False
has_seqn_entry = False
for entry in txt_entry:
if entry.startswith(SUBDOMAIN_ZF_PARTS + "="):
has_parts_entry = True
if entry.startswith(SUBDOMAIN_PUBKEY + "="):
has_pk_entry = True
if entry.startswith(SUBDOMAIN_N + "="):
has_seqn_entry = True
return (has_parts_entry and has_pk_entry and has_seqn_entry) | python | def is_subdomain_record(rec):
"""
Does a given parsed zone file TXT record (@rec) encode a subdomain?
Return True if so
Return False if not
"""
txt_entry = rec['txt']
if not isinstance(txt_entry, list):
return False
has_parts_entry = False
has_pk_entry = False
has_seqn_entry = False
for entry in txt_entry:
if entry.startswith(SUBDOMAIN_ZF_PARTS + "="):
has_parts_entry = True
if entry.startswith(SUBDOMAIN_PUBKEY + "="):
has_pk_entry = True
if entry.startswith(SUBDOMAIN_N + "="):
has_seqn_entry = True
return (has_parts_entry and has_pk_entry and has_seqn_entry) | [
"def",
"is_subdomain_record",
"(",
"rec",
")",
":",
"txt_entry",
"=",
"rec",
"[",
"'txt'",
"]",
"if",
"not",
"isinstance",
"(",
"txt_entry",
",",
"list",
")",
":",
"return",
"False",
"has_parts_entry",
"=",
"False",
"has_pk_entry",
"=",
"False",
"has_seqn_en... | Does a given parsed zone file TXT record (@rec) encode a subdomain?
Return True if so
Return False if not | [
"Does",
"a",
"given",
"parsed",
"zone",
"file",
"TXT",
"record",
"("
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1833-L1854 | train | 225,507 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_info | def get_subdomain_info(fqn, db_path=None, atlasdb_path=None, zonefiles_dir=None, check_pending=False, include_did=False):
"""
Static method for getting the state of a subdomain, given its fully-qualified name.
Return the subdomain record on success.
Return None if not found.
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
if atlasdb_path is None:
atlasdb_path = opts['atlasdb_path']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_subdomain_entry(fqn)
except SubdomainNotFound:
log.warn("No such subdomain: {}".format(fqn))
return None
if check_pending:
# make sure that all of the zone files between this subdomain's
# domain's creation and this subdomain's zone file index are present,
# minus the ones that are allowed to be missing.
subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)
if include_did:
# include the DID
subrec.did_info = db.get_subdomain_DID_info(fqn)
return subrec | python | def get_subdomain_info(fqn, db_path=None, atlasdb_path=None, zonefiles_dir=None, check_pending=False, include_did=False):
"""
Static method for getting the state of a subdomain, given its fully-qualified name.
Return the subdomain record on success.
Return None if not found.
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
if atlasdb_path is None:
atlasdb_path = opts['atlasdb_path']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_subdomain_entry(fqn)
except SubdomainNotFound:
log.warn("No such subdomain: {}".format(fqn))
return None
if check_pending:
# make sure that all of the zone files between this subdomain's
# domain's creation and this subdomain's zone file index are present,
# minus the ones that are allowed to be missing.
subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)
if include_did:
# include the DID
subrec.did_info = db.get_subdomain_DID_info(fqn)
return subrec | [
"def",
"get_subdomain_info",
"(",
"fqn",
",",
"db_path",
"=",
"None",
",",
"atlasdb_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
",",
"check_pending",
"=",
"False",
",",
"include_did",
"=",
"False",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"("... | Static method for getting the state of a subdomain, given its fully-qualified name.
Return the subdomain record on success.
Return None if not found. | [
"Static",
"method",
"for",
"getting",
"the",
"state",
"of",
"a",
"subdomain",
"given",
"its",
"fully",
"-",
"qualified",
"name",
".",
"Return",
"the",
"subdomain",
"record",
"on",
"success",
".",
"Return",
"None",
"if",
"not",
"found",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1857-L1894 | train | 225,508 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_resolver | def get_subdomain_resolver(name, db_path=None, zonefiles_dir=None):
"""
Static method for determining the last-known resolver for a domain name.
Returns the resolver URL on success
Returns None on error
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
resolver_url = db.get_domain_resolver(name)
return resolver_url | python | def get_subdomain_resolver(name, db_path=None, zonefiles_dir=None):
"""
Static method for determining the last-known resolver for a domain name.
Returns the resolver URL on success
Returns None on error
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
resolver_url = db.get_domain_resolver(name)
return resolver_url | [
"def",
"get_subdomain_resolver",
"(",
"name",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"log",
".",
"warn",
"(",
"\"S... | Static method for determining the last-known resolver for a domain name.
Returns the resolver URL on success
Returns None on error | [
"Static",
"method",
"for",
"determining",
"the",
"last",
"-",
"known",
"resolver",
"for",
"a",
"domain",
"name",
".",
"Returns",
"the",
"resolver",
"URL",
"on",
"success",
"Returns",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1897-L1917 | train | 225,509 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomains_count | def get_subdomains_count(db_path=None, zonefiles_dir=None):
"""
Static method for getting count of all subdomains
Return number of subdomains on success
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomains_count() | python | def get_subdomains_count(db_path=None, zonefiles_dir=None):
"""
Static method for getting count of all subdomains
Return number of subdomains on success
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomains_count() | [
"def",
"get_subdomains_count",
"(",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"log",
".",
"warn",
"(",
"\"Subdomain support is... | Static method for getting count of all subdomains
Return number of subdomains on success | [
"Static",
"method",
"for",
"getting",
"count",
"of",
"all",
"subdomains",
"Return",
"number",
"of",
"subdomains",
"on",
"success"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1920-L1937 | train | 225,510 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_DID_info | def get_subdomain_DID_info(fqn, db_path=None, zonefiles_dir=None):
"""
Get a subdomain's DID info.
Return None if not found
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_subdomain_entry(fqn)
except SubdomainNotFound:
log.warn("No such subdomain: {}".format(fqn))
return None
try:
return db.get_subdomain_DID_info(fqn)
except SubdomainNotFound:
return None | python | def get_subdomain_DID_info(fqn, db_path=None, zonefiles_dir=None):
"""
Get a subdomain's DID info.
Return None if not found
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_subdomain_entry(fqn)
except SubdomainNotFound:
log.warn("No such subdomain: {}".format(fqn))
return None
try:
return db.get_subdomain_DID_info(fqn)
except SubdomainNotFound:
return None | [
"def",
"get_subdomain_DID_info",
"(",
"fqn",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"log",
".",
"warn",
"(",
"\"Su... | Get a subdomain's DID info.
Return None if not found | [
"Get",
"a",
"subdomain",
"s",
"DID",
"info",
".",
"Return",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1940-L1966 | train | 225,511 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_DID_subdomain | def get_DID_subdomain(did, db_path=None, zonefiles_dir=None, atlasdb_path=None, check_pending=False):
"""
Static method for resolving a DID to a subdomain
Return the subdomain record on success
Return None on error
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
if atlasdb_path is None:
atlasdb_path = opts['atlasdb_path']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_DID_subdomain(did)
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
log.warn("Failed to load subdomain for {}".format(did))
return None
if check_pending:
# make sure that all of the zone files between this subdomain's
# domain's creation and this subdomain's zone file index are present,
# minus the ones that are allowed to be missing.
subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)
return subrec | python | def get_DID_subdomain(did, db_path=None, zonefiles_dir=None, atlasdb_path=None, check_pending=False):
"""
Static method for resolving a DID to a subdomain
Return the subdomain record on success
Return None on error
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
if atlasdb_path is None:
atlasdb_path = opts['atlasdb_path']
db = SubdomainDB(db_path, zonefiles_dir)
try:
subrec = db.get_DID_subdomain(did)
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
log.warn("Failed to load subdomain for {}".format(did))
return None
if check_pending:
# make sure that all of the zone files between this subdomain's
# domain's creation and this subdomain's zone file index are present,
# minus the ones that are allowed to be missing.
subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)
return subrec | [
"def",
"get_DID_subdomain",
"(",
"did",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
",",
"atlasdb_path",
"=",
"None",
",",
"check_pending",
"=",
"False",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_... | Static method for resolving a DID to a subdomain
Return the subdomain record on success
Return None on error | [
"Static",
"method",
"for",
"resolving",
"a",
"DID",
"to",
"a",
"subdomain",
"Return",
"the",
"subdomain",
"record",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1969-L2005 | train | 225,512 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | is_subdomain_zonefile_hash | def is_subdomain_zonefile_hash(fqn, zonefile_hash, db_path=None, zonefiles_dir=None):
"""
Static method for getting all historic zone file hashes for a subdomain
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
zonefile_hashes = db.is_subdomain_zonefile_hash(fqn, zonefile_hash)
return zonefile_hashes | python | def is_subdomain_zonefile_hash(fqn, zonefile_hash, db_path=None, zonefiles_dir=None):
"""
Static method for getting all historic zone file hashes for a subdomain
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
zonefile_hashes = db.is_subdomain_zonefile_hash(fqn, zonefile_hash)
return zonefile_hashes | [
"def",
"is_subdomain_zonefile_hash",
"(",
"fqn",
",",
"zonefile_hash",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"return"... | Static method for getting all historic zone file hashes for a subdomain | [
"Static",
"method",
"for",
"getting",
"all",
"historic",
"zone",
"file",
"hashes",
"for",
"a",
"subdomain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2008-L2024 | train | 225,513 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_history | def get_subdomain_history(fqn, offset=None, count=None, reverse=False, db_path=None, zonefiles_dir=None, json=False):
"""
Static method for getting all historic operations on a subdomain
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
recs = db.get_subdomain_history(fqn, offset=offset, count=count)
if json:
recs = [rec.to_json() for rec in recs]
ret = {}
for rec in recs:
if rec['block_number'] not in ret:
ret[rec['block_number']] = []
ret[rec['block_number']].append(rec)
if reverse:
for block_height in ret:
ret[block_height].sort(lambda r1, r2: -1 if r1['parent_zonefile_index'] > r2['parent_zonefile_index'] or
(r1['parent_zonefile_index'] == r2['parent_zonefile_index'] and r1['zonefile_offset'] > r2['zonefile_offset']) else
1 if r1['parent_zonefile_index'] < r2['parent_zonefile_index'] or
(r1['parent_zonefile_index'] == r2['parent_zonefile_index'] and r1['zonefile_offset'] < r2['zonefile_offset']) else
0)
return ret
else:
return recs | python | def get_subdomain_history(fqn, offset=None, count=None, reverse=False, db_path=None, zonefiles_dir=None, json=False):
"""
Static method for getting all historic operations on a subdomain
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
recs = db.get_subdomain_history(fqn, offset=offset, count=count)
if json:
recs = [rec.to_json() for rec in recs]
ret = {}
for rec in recs:
if rec['block_number'] not in ret:
ret[rec['block_number']] = []
ret[rec['block_number']].append(rec)
if reverse:
for block_height in ret:
ret[block_height].sort(lambda r1, r2: -1 if r1['parent_zonefile_index'] > r2['parent_zonefile_index'] or
(r1['parent_zonefile_index'] == r2['parent_zonefile_index'] and r1['zonefile_offset'] > r2['zonefile_offset']) else
1 if r1['parent_zonefile_index'] < r2['parent_zonefile_index'] or
(r1['parent_zonefile_index'] == r2['parent_zonefile_index'] and r1['zonefile_offset'] < r2['zonefile_offset']) else
0)
return ret
else:
return recs | [
"def",
"get_subdomain_history",
"(",
"fqn",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
",",
"json",
"=",
"False",
")",
":",
"opts",
"=",
"get_bloc... | Static method for getting all historic operations on a subdomain | [
"Static",
"method",
"for",
"getting",
"all",
"historic",
"operations",
"on",
"a",
"subdomain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2027-L2063 | train | 225,514 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_all_subdomains | def get_all_subdomains(offset=None, count=None, min_sequence=None, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of all subdomains
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_all_subdomains(offset=offset, count=count, min_sequence=None) | python | def get_all_subdomains(offset=None, count=None, min_sequence=None, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of all subdomains
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_all_subdomains(offset=offset, count=count, min_sequence=None) | [
"def",
"get_all_subdomains",
"(",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"min_sequence",
"=",
"None",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is... | Static method for getting the list of all subdomains | [
"Static",
"method",
"for",
"getting",
"the",
"list",
"of",
"all",
"subdomains"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2066-L2081 | train | 225,515 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_ops_at_txid | def get_subdomain_ops_at_txid(txid, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomain operations accepted at a given txid.
Includes unaccepted subdomain operations
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomain_ops_at_txid(txid) | python | def get_subdomain_ops_at_txid(txid, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomain operations accepted at a given txid.
Includes unaccepted subdomain operations
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomain_ops_at_txid(txid) | [
"def",
"get_subdomain_ops_at_txid",
"(",
"txid",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"return",
"[",
"]",
"if",
... | Static method for getting the list of subdomain operations accepted at a given txid.
Includes unaccepted subdomain operations | [
"Static",
"method",
"for",
"getting",
"the",
"list",
"of",
"subdomain",
"operations",
"accepted",
"at",
"a",
"given",
"txid",
".",
"Includes",
"unaccepted",
"subdomain",
"operations"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2084-L2100 | train | 225,516 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomains_owned_by_address | def get_subdomains_owned_by_address(address, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomains for a given address
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomains_owned_by_address(address) | python | def get_subdomains_owned_by_address(address, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomains for a given address
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_subdomains_owned_by_address(address) | [
"def",
"get_subdomains_owned_by_address",
"(",
"address",
",",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"return",
"[",
"]",
... | Static method for getting the list of subdomains for a given address | [
"Static",
"method",
"for",
"getting",
"the",
"list",
"of",
"subdomains",
"for",
"a",
"given",
"address"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2103-L2118 | train | 225,517 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | get_subdomain_last_sequence | def get_subdomain_last_sequence(db_path=None, zonefiles_dir=None):
"""
Static method for getting the last sequence number in the database
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_last_sequence() | python | def get_subdomain_last_sequence(db_path=None, zonefiles_dir=None):
"""
Static method for getting the last sequence number in the database
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb_path']
if zonefiles_dir is None:
zonefiles_dir = opts['zonefiles']
db = SubdomainDB(db_path, zonefiles_dir)
return db.get_last_sequence() | [
"def",
"get_subdomain_last_sequence",
"(",
"db_path",
"=",
"None",
",",
"zonefiles_dir",
"=",
"None",
")",
":",
"opts",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_subdomains_enabled",
"(",
"opts",
")",
":",
"return",
"[",
"]",
"if",
"db_path",
"i... | Static method for getting the last sequence number in the database | [
"Static",
"method",
"for",
"getting",
"the",
"last",
"sequence",
"number",
"in",
"the",
"database"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2121-L2136 | train | 225,518 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | sign | def sign(privkey_bundle, plaintext):
"""
Sign a subdomain plaintext with a private key bundle
Returns the base64-encoded scriptsig
"""
if virtualchain.is_singlesig(privkey_bundle):
return sign_singlesig(privkey_bundle, plaintext)
elif virtualchain.is_multisig(privkey_bundle):
return sign_multisig(privkey_bundle, plaintext)
else:
raise ValueError("private key bundle is neither a singlesig nor multisig bundle") | python | def sign(privkey_bundle, plaintext):
"""
Sign a subdomain plaintext with a private key bundle
Returns the base64-encoded scriptsig
"""
if virtualchain.is_singlesig(privkey_bundle):
return sign_singlesig(privkey_bundle, plaintext)
elif virtualchain.is_multisig(privkey_bundle):
return sign_multisig(privkey_bundle, plaintext)
else:
raise ValueError("private key bundle is neither a singlesig nor multisig bundle") | [
"def",
"sign",
"(",
"privkey_bundle",
",",
"plaintext",
")",
":",
"if",
"virtualchain",
".",
"is_singlesig",
"(",
"privkey_bundle",
")",
":",
"return",
"sign_singlesig",
"(",
"privkey_bundle",
",",
"plaintext",
")",
"elif",
"virtualchain",
".",
"is_multisig",
"(... | Sign a subdomain plaintext with a private key bundle
Returns the base64-encoded scriptsig | [
"Sign",
"a",
"subdomain",
"plaintext",
"with",
"a",
"private",
"key",
"bundle",
"Returns",
"the",
"base64",
"-",
"encoded",
"scriptsig"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2152-L2162 | train | 225,519 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | subdomains_init | def subdomains_init(blockstack_opts, working_dir, atlas_state):
"""
Set up subdomain state
Returns a SubdomainIndex object that has been successfully connected to Atlas
"""
if not is_subdomains_enabled(blockstack_opts):
return None
subdomain_state = SubdomainIndex(blockstack_opts['subdomaindb_path'], blockstack_opts=blockstack_opts)
atlas_node_add_callback(atlas_state, 'store_zonefile', subdomain_state.enqueue_zonefile)
return subdomain_state | python | def subdomains_init(blockstack_opts, working_dir, atlas_state):
"""
Set up subdomain state
Returns a SubdomainIndex object that has been successfully connected to Atlas
"""
if not is_subdomains_enabled(blockstack_opts):
return None
subdomain_state = SubdomainIndex(blockstack_opts['subdomaindb_path'], blockstack_opts=blockstack_opts)
atlas_node_add_callback(atlas_state, 'store_zonefile', subdomain_state.enqueue_zonefile)
return subdomain_state | [
"def",
"subdomains_init",
"(",
"blockstack_opts",
",",
"working_dir",
",",
"atlas_state",
")",
":",
"if",
"not",
"is_subdomains_enabled",
"(",
"blockstack_opts",
")",
":",
"return",
"None",
"subdomain_state",
"=",
"SubdomainIndex",
"(",
"blockstack_opts",
"[",
"'sub... | Set up subdomain state
Returns a SubdomainIndex object that has been successfully connected to Atlas | [
"Set",
"up",
"subdomain",
"state",
"Returns",
"a",
"SubdomainIndex",
"object",
"that",
"has",
"been",
"successfully",
"connected",
"to",
"Atlas"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L2220-L2231 | train | 225,520 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | Subdomain.verify_signature | def verify_signature(self, addr):
"""
Given an address, verify whether or not it was signed by it
"""
return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig) | python | def verify_signature(self, addr):
"""
Given an address, verify whether or not it was signed by it
"""
return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig) | [
"def",
"verify_signature",
"(",
"self",
",",
"addr",
")",
":",
"return",
"verify",
"(",
"virtualchain",
".",
"address_reencode",
"(",
"addr",
")",
",",
"self",
".",
"get_plaintext_to_sign",
"(",
")",
",",
"self",
".",
"sig",
")"
] | Given an address, verify whether or not it was signed by it | [
"Given",
"an",
"address",
"verify",
"whether",
"or",
"not",
"it",
"was",
"signed",
"by",
"it"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L202-L206 | train | 225,521 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | Subdomain.serialize_to_txt | def serialize_to_txt(self):
"""
Serialize this subdomain record to a TXT record. The trailing newline will be omitted
"""
txtrec = {
'name': self.fqn if self.independent else self.subdomain,
'txt': self.pack_subdomain()[1:]
}
return blockstack_zones.record_processors.process_txt([txtrec], '{txt}').strip() | python | def serialize_to_txt(self):
"""
Serialize this subdomain record to a TXT record. The trailing newline will be omitted
"""
txtrec = {
'name': self.fqn if self.independent else self.subdomain,
'txt': self.pack_subdomain()[1:]
}
return blockstack_zones.record_processors.process_txt([txtrec], '{txt}').strip() | [
"def",
"serialize_to_txt",
"(",
"self",
")",
":",
"txtrec",
"=",
"{",
"'name'",
":",
"self",
".",
"fqn",
"if",
"self",
".",
"independent",
"else",
"self",
".",
"subdomain",
",",
"'txt'",
":",
"self",
".",
"pack_subdomain",
"(",
")",
"[",
"1",
":",
"]... | Serialize this subdomain record to a TXT record. The trailing newline will be omitted | [
"Serialize",
"this",
"subdomain",
"record",
"to",
"a",
"TXT",
"record",
".",
"The",
"trailing",
"newline",
"will",
"be",
"omitted"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L224-L232 | train | 225,522 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | Subdomain.parse_subdomain_missing_zonefiles_record | def parse_subdomain_missing_zonefiles_record(cls, rec):
"""
Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records
"""
txt_entry = rec['txt']
if isinstance(txt_entry, list):
raise ParseError("TXT entry too long for a missing zone file list")
try:
return [int(i) for i in txt_entry.split(',')] if txt_entry is not None and len(txt_entry) > 0 else []
except ValueError:
raise ParseError('Invalid integers') | python | def parse_subdomain_missing_zonefiles_record(cls, rec):
"""
Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records
"""
txt_entry = rec['txt']
if isinstance(txt_entry, list):
raise ParseError("TXT entry too long for a missing zone file list")
try:
return [int(i) for i in txt_entry.split(',')] if txt_entry is not None and len(txt_entry) > 0 else []
except ValueError:
raise ParseError('Invalid integers') | [
"def",
"parse_subdomain_missing_zonefiles_record",
"(",
"cls",
",",
"rec",
")",
":",
"txt_entry",
"=",
"rec",
"[",
"'txt'",
"]",
"if",
"isinstance",
"(",
"txt_entry",
",",
"list",
")",
":",
"raise",
"ParseError",
"(",
"\"TXT entry too long for a missing zone file li... | Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records | [
"Parse",
"a",
"missing",
"-",
"zonefiles",
"vector",
"given",
"by",
"the",
"domain",
".",
"Returns",
"the",
"list",
"of",
"zone",
"file",
"indexes",
"on",
"success",
"Raises",
"ParseError",
"on",
"unparseable",
"records"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L260-L273 | train | 225,523 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | Subdomain.get_public_key | def get_public_key(self):
"""
Parse the scriptSig and extract the public key.
Raises ValueError if this is a multisig-controlled subdomain.
"""
res = self.get_public_key_info()
if 'error' in res:
raise ValueError(res['error'])
if res['type'] != 'singlesig':
raise ValueError(res['error'])
return res['public_keys'][0] | python | def get_public_key(self):
"""
Parse the scriptSig and extract the public key.
Raises ValueError if this is a multisig-controlled subdomain.
"""
res = self.get_public_key_info()
if 'error' in res:
raise ValueError(res['error'])
if res['type'] != 'singlesig':
raise ValueError(res['error'])
return res['public_keys'][0] | [
"def",
"get_public_key",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"get_public_key_info",
"(",
")",
"if",
"'error'",
"in",
"res",
":",
"raise",
"ValueError",
"(",
"res",
"[",
"'error'",
"]",
")",
"if",
"res",
"[",
"'type'",
"]",
"!=",
"'singlesig... | Parse the scriptSig and extract the public key.
Raises ValueError if this is a multisig-controlled subdomain. | [
"Parse",
"the",
"scriptSig",
"and",
"extract",
"the",
"public",
"key",
".",
"Raises",
"ValueError",
"if",
"this",
"is",
"a",
"multisig",
"-",
"controlled",
"subdomain",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L345-L357 | train | 225,524 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.close | def close(self):
"""
Close the index
"""
with self.subdomain_db_lock:
self.subdomain_db.close()
self.subdomain_db = None
self.subdomain_db_path = None | python | def close(self):
"""
Close the index
"""
with self.subdomain_db_lock:
self.subdomain_db.close()
self.subdomain_db = None
self.subdomain_db_path = None | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"subdomain_db_lock",
":",
"self",
".",
"subdomain_db",
".",
"close",
"(",
")",
"self",
".",
"subdomain_db",
"=",
"None",
"self",
".",
"subdomain_db_path",
"=",
"None"
] | Close the index | [
"Close",
"the",
"index"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L441-L448 | train | 225,525 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.make_new_subdomain_history | def make_new_subdomain_history(self, cursor, subdomain_rec):
"""
Recalculate the history for this subdomain from genesis up until this record.
Returns the list of subdomain records we need to save.
"""
# what's the subdomain's history up until this subdomain record?
hist = self.subdomain_db.get_subdomain_history(subdomain_rec.get_fqn(), include_unaccepted=True, end_sequence=subdomain_rec.n+1, end_zonefile_index=subdomain_rec.parent_zonefile_index+1, cur=cursor)
assert len(hist) > 0, 'BUG: not yet stored: {}'.format(subdomain_rec)
for i in range(0, len(hist)):
hist[i].accepted = False
hist.sort(lambda h1, h2: -1 if h1.n < h2.n or (h1.n == h2.n and h1.parent_zonefile_index < h2.parent_zonefile_index) \
else 0 if h1.n == h2.n and h1.parent_zonefile_index == h2.parent_zonefile_index \
else 1)
if not self.check_initial_subdomain(hist[0]):
log.debug("Reject initial {}".format(hist[0]))
return hist
else:
log.debug("Accept initial {}".format(hist[0]))
pass
hist[0].accepted = True
last_accepted = 0
for i in xrange(1, len(hist)):
if self.check_subdomain_transition(hist[last_accepted], hist[i]):
log.debug("Accept historic update {}".format(hist[i]))
hist[i].accepted = True
last_accepted = i
else:
log.debug("Reject historic update {}".format(hist[i]))
hist[i].accepted = False
return hist | python | def make_new_subdomain_history(self, cursor, subdomain_rec):
"""
Recalculate the history for this subdomain from genesis up until this record.
Returns the list of subdomain records we need to save.
"""
# what's the subdomain's history up until this subdomain record?
hist = self.subdomain_db.get_subdomain_history(subdomain_rec.get_fqn(), include_unaccepted=True, end_sequence=subdomain_rec.n+1, end_zonefile_index=subdomain_rec.parent_zonefile_index+1, cur=cursor)
assert len(hist) > 0, 'BUG: not yet stored: {}'.format(subdomain_rec)
for i in range(0, len(hist)):
hist[i].accepted = False
hist.sort(lambda h1, h2: -1 if h1.n < h2.n or (h1.n == h2.n and h1.parent_zonefile_index < h2.parent_zonefile_index) \
else 0 if h1.n == h2.n and h1.parent_zonefile_index == h2.parent_zonefile_index \
else 1)
if not self.check_initial_subdomain(hist[0]):
log.debug("Reject initial {}".format(hist[0]))
return hist
else:
log.debug("Accept initial {}".format(hist[0]))
pass
hist[0].accepted = True
last_accepted = 0
for i in xrange(1, len(hist)):
if self.check_subdomain_transition(hist[last_accepted], hist[i]):
log.debug("Accept historic update {}".format(hist[i]))
hist[i].accepted = True
last_accepted = i
else:
log.debug("Reject historic update {}".format(hist[i]))
hist[i].accepted = False
return hist | [
"def",
"make_new_subdomain_history",
"(",
"self",
",",
"cursor",
",",
"subdomain_rec",
")",
":",
"# what's the subdomain's history up until this subdomain record?",
"hist",
"=",
"self",
".",
"subdomain_db",
".",
"get_subdomain_history",
"(",
"subdomain_rec",
".",
"get_fqn",... | Recalculate the history for this subdomain from genesis up until this record.
Returns the list of subdomain records we need to save. | [
"Recalculate",
"the",
"history",
"for",
"this",
"subdomain",
"from",
"genesis",
"up",
"until",
"this",
"record",
".",
"Returns",
"the",
"list",
"of",
"subdomain",
"records",
"we",
"need",
"to",
"save",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L570-L605 | train | 225,526 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.make_new_subdomain_future | def make_new_subdomain_future(self, cursor, subdomain_rec):
"""
Recalculate the future for this subdomain from the current record
until the latest known record.
Returns the list of subdomain records we need to save.
"""
assert subdomain_rec.accepted, 'BUG: given subdomain record must already be accepted'
# what's the subdomain's future after this record?
fut = self.subdomain_db.get_subdomain_history(subdomain_rec.get_fqn(), include_unaccepted=True, start_sequence=subdomain_rec.n, start_zonefile_index=subdomain_rec.parent_zonefile_index, cur=cursor)
for i in range(0, len(fut)):
if fut[i].n == subdomain_rec.n and fut[i].parent_zonefile_index == subdomain_rec.parent_zonefile_index:
fut.pop(i)
break
if len(fut) == 0:
log.debug("At tip: {}".format(subdomain_rec))
return []
for i in range(0, len(fut)):
fut[i].accepted = False
fut = [subdomain_rec] + fut
fut.sort(lambda h1, h2: -1 if h1.n < h2.n or (h1.n == h2.n and h1.parent_zonefile_index < h2.parent_zonefile_index) \
else 0 if h1.n == h2.n and h1.parent_zonefile_index == h2.parent_zonefile_index \
else 1)
assert fut[0].accepted, 'BUG: initial subdomain record is not accepted: {}'.format(fut[0])
last_accepted = 0
for i in range(1, len(fut)):
if self.check_subdomain_transition(fut[last_accepted], fut[i]):
log.debug("Accept future update {}".format(fut[i]))
fut[i].accepted = True
last_accepted = i
else:
log.debug("Reject future update {}".format(fut[i]))
fut[i].accepted = False
return fut | python | def make_new_subdomain_future(self, cursor, subdomain_rec):
"""
Recalculate the future for this subdomain from the current record
until the latest known record.
Returns the list of subdomain records we need to save.
"""
assert subdomain_rec.accepted, 'BUG: given subdomain record must already be accepted'
# what's the subdomain's future after this record?
fut = self.subdomain_db.get_subdomain_history(subdomain_rec.get_fqn(), include_unaccepted=True, start_sequence=subdomain_rec.n, start_zonefile_index=subdomain_rec.parent_zonefile_index, cur=cursor)
for i in range(0, len(fut)):
if fut[i].n == subdomain_rec.n and fut[i].parent_zonefile_index == subdomain_rec.parent_zonefile_index:
fut.pop(i)
break
if len(fut) == 0:
log.debug("At tip: {}".format(subdomain_rec))
return []
for i in range(0, len(fut)):
fut[i].accepted = False
fut = [subdomain_rec] + fut
fut.sort(lambda h1, h2: -1 if h1.n < h2.n or (h1.n == h2.n and h1.parent_zonefile_index < h2.parent_zonefile_index) \
else 0 if h1.n == h2.n and h1.parent_zonefile_index == h2.parent_zonefile_index \
else 1)
assert fut[0].accepted, 'BUG: initial subdomain record is not accepted: {}'.format(fut[0])
last_accepted = 0
for i in range(1, len(fut)):
if self.check_subdomain_transition(fut[last_accepted], fut[i]):
log.debug("Accept future update {}".format(fut[i]))
fut[i].accepted = True
last_accepted = i
else:
log.debug("Reject future update {}".format(fut[i]))
fut[i].accepted = False
return fut | [
"def",
"make_new_subdomain_future",
"(",
"self",
",",
"cursor",
",",
"subdomain_rec",
")",
":",
"assert",
"subdomain_rec",
".",
"accepted",
",",
"'BUG: given subdomain record must already be accepted'",
"# what's the subdomain's future after this record?",
"fut",
"=",
"self",
... | Recalculate the future for this subdomain from the current record
until the latest known record.
Returns the list of subdomain records we need to save. | [
"Recalculate",
"the",
"future",
"for",
"this",
"subdomain",
"from",
"the",
"current",
"record",
"until",
"the",
"latest",
"known",
"record",
".",
"Returns",
"the",
"list",
"of",
"subdomain",
"records",
"we",
"need",
"to",
"save",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L608-L647 | train | 225,527 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.subdomain_try_insert | def subdomain_try_insert(self, cursor, subdomain_rec, history_neighbors):
"""
Try to insert a subdomain record into its history neighbors.
This is an optimization that handles the "usual" case.
We can do this without having to rewrite this subdomain's past and future
if (1) we can find a previously-accepted subdomain record, and (2) the transition
from this subdomain record to a future subdomain record preserves its
acceptance as True. In this case, the "far" past and "far" future are already
consistent.
Return True if we succeed in doing so.
Return False if not.
"""
blockchain_order = history_neighbors['prev'] + history_neighbors['cur'] + history_neighbors['fut']
last_accepted = -1
for i in range(0, len(blockchain_order)):
if blockchain_order[i].accepted:
last_accepted = i
break
if blockchain_order[i].n > subdomain_rec.n or (blockchain_order[i].n == subdomain_rec.n and blockchain_order[i].parent_zonefile_index > subdomain_rec.parent_zonefile_index):
# can't cheaply insert this subdomain record,
# since none of its immediate ancestors are accepted.
log.debug("No immediate ancestors are accepted on {}".format(subdomain_rec))
return False
if last_accepted < 0:
log.debug("No immediate ancestors or successors are accepted on {}".format(subdomain_rec))
return False
# one ancestor was accepted.
# work from there.
chain_tip_status = blockchain_order[-1].accepted
dirty = [] # to be written
for i in range(last_accepted+1, len(blockchain_order)):
cur_accepted = blockchain_order[i].accepted
new_accepted = self.check_subdomain_transition(blockchain_order[last_accepted], blockchain_order[i])
if new_accepted != cur_accepted:
blockchain_order[i].accepted = new_accepted
log.debug("Changed from {} to {}: {}".format(cur_accepted, new_accepted, blockchain_order[i]))
dirty.append(blockchain_order[i])
if new_accepted:
last_accepted = i
if chain_tip_status != blockchain_order[-1].accepted and len(history_neighbors['fut']) > 0:
# deeper reorg
log.debug("Immediate history chain tip altered from {} to {}: {}".format(chain_tip_status, blockchain_order[-1].accepted, blockchain_order[-1]))
return False
# localized change. Just commit the dirty entries
for subrec in dirty:
log.debug("Update to accepted={}: {}".format(subrec.accepted, subrec))
self.subdomain_db.update_subdomain_entry(subrec, cur=cursor)
return True | python | def subdomain_try_insert(self, cursor, subdomain_rec, history_neighbors):
"""
Try to insert a subdomain record into its history neighbors.
This is an optimization that handles the "usual" case.
We can do this without having to rewrite this subdomain's past and future
if (1) we can find a previously-accepted subdomain record, and (2) the transition
from this subdomain record to a future subdomain record preserves its
acceptance as True. In this case, the "far" past and "far" future are already
consistent.
Return True if we succeed in doing so.
Return False if not.
"""
blockchain_order = history_neighbors['prev'] + history_neighbors['cur'] + history_neighbors['fut']
last_accepted = -1
for i in range(0, len(blockchain_order)):
if blockchain_order[i].accepted:
last_accepted = i
break
if blockchain_order[i].n > subdomain_rec.n or (blockchain_order[i].n == subdomain_rec.n and blockchain_order[i].parent_zonefile_index > subdomain_rec.parent_zonefile_index):
# can't cheaply insert this subdomain record,
# since none of its immediate ancestors are accepted.
log.debug("No immediate ancestors are accepted on {}".format(subdomain_rec))
return False
if last_accepted < 0:
log.debug("No immediate ancestors or successors are accepted on {}".format(subdomain_rec))
return False
# one ancestor was accepted.
# work from there.
chain_tip_status = blockchain_order[-1].accepted
dirty = [] # to be written
for i in range(last_accepted+1, len(blockchain_order)):
cur_accepted = blockchain_order[i].accepted
new_accepted = self.check_subdomain_transition(blockchain_order[last_accepted], blockchain_order[i])
if new_accepted != cur_accepted:
blockchain_order[i].accepted = new_accepted
log.debug("Changed from {} to {}: {}".format(cur_accepted, new_accepted, blockchain_order[i]))
dirty.append(blockchain_order[i])
if new_accepted:
last_accepted = i
if chain_tip_status != blockchain_order[-1].accepted and len(history_neighbors['fut']) > 0:
# deeper reorg
log.debug("Immediate history chain tip altered from {} to {}: {}".format(chain_tip_status, blockchain_order[-1].accepted, blockchain_order[-1]))
return False
# localized change. Just commit the dirty entries
for subrec in dirty:
log.debug("Update to accepted={}: {}".format(subrec.accepted, subrec))
self.subdomain_db.update_subdomain_entry(subrec, cur=cursor)
return True | [
"def",
"subdomain_try_insert",
"(",
"self",
",",
"cursor",
",",
"subdomain_rec",
",",
"history_neighbors",
")",
":",
"blockchain_order",
"=",
"history_neighbors",
"[",
"'prev'",
"]",
"+",
"history_neighbors",
"[",
"'cur'",
"]",
"+",
"history_neighbors",
"[",
"'fut... | Try to insert a subdomain record into its history neighbors.
This is an optimization that handles the "usual" case.
We can do this without having to rewrite this subdomain's past and future
if (1) we can find a previously-accepted subdomain record, and (2) the transition
from this subdomain record to a future subdomain record preserves its
acceptance as True. In this case, the "far" past and "far" future are already
consistent.
Return True if we succeed in doing so.
Return False if not. | [
"Try",
"to",
"insert",
"a",
"subdomain",
"record",
"into",
"its",
"history",
"neighbors",
".",
"This",
"is",
"an",
"optimization",
"that",
"handles",
"the",
"usual",
"case",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L684-L743 | train | 225,528 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.enqueue_zonefile | def enqueue_zonefile(self, zonefile_hash, block_height):
"""
Called when we discover a zone file. Queues up a request to reprocess this name's zone files' subdomains.
zonefile_hash is the hash of the zonefile.
block_height is the minimium block height at which this zone file occurs.
This gets called by:
* AtlasZonefileCrawler (as it's "store_zonefile" callback).
* rpc_put_zonefiles()
"""
with self.serialized_enqueue_zonefile:
log.debug("Append {} from {}".format(zonefile_hash, block_height))
queuedb_append(self.subdomain_queue_path, "zonefiles", zonefile_hash, json.dumps({'zonefile_hash': zonefile_hash, 'block_height': block_height})) | python | def enqueue_zonefile(self, zonefile_hash, block_height):
"""
Called when we discover a zone file. Queues up a request to reprocess this name's zone files' subdomains.
zonefile_hash is the hash of the zonefile.
block_height is the minimium block height at which this zone file occurs.
This gets called by:
* AtlasZonefileCrawler (as it's "store_zonefile" callback).
* rpc_put_zonefiles()
"""
with self.serialized_enqueue_zonefile:
log.debug("Append {} from {}".format(zonefile_hash, block_height))
queuedb_append(self.subdomain_queue_path, "zonefiles", zonefile_hash, json.dumps({'zonefile_hash': zonefile_hash, 'block_height': block_height})) | [
"def",
"enqueue_zonefile",
"(",
"self",
",",
"zonefile_hash",
",",
"block_height",
")",
":",
"with",
"self",
".",
"serialized_enqueue_zonefile",
":",
"log",
".",
"debug",
"(",
"\"Append {} from {}\"",
".",
"format",
"(",
"zonefile_hash",
",",
"block_height",
")",
... | Called when we discover a zone file. Queues up a request to reprocess this name's zone files' subdomains.
zonefile_hash is the hash of the zonefile.
block_height is the minimium block height at which this zone file occurs.
This gets called by:
* AtlasZonefileCrawler (as it's "store_zonefile" callback).
* rpc_put_zonefiles() | [
"Called",
"when",
"we",
"discover",
"a",
"zone",
"file",
".",
"Queues",
"up",
"a",
"request",
"to",
"reprocess",
"this",
"name",
"s",
"zone",
"files",
"subdomains",
".",
"zonefile_hash",
"is",
"the",
"hash",
"of",
"the",
"zonefile",
".",
"block_height",
"i... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L823-L835 | train | 225,529 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.index_blockchain | def index_blockchain(self, block_start, block_end):
"""
Go through the sequence of zone files discovered in a block range, and reindex the names' subdomains.
"""
log.debug("Processing subdomain updates for zonefiles in blocks {}-{}".format(block_start, block_end))
res = self.find_zonefile_subdomains(block_start, block_end)
zonefile_subdomain_info = res['zonefile_info']
self.process_subdomains(zonefile_subdomain_info) | python | def index_blockchain(self, block_start, block_end):
"""
Go through the sequence of zone files discovered in a block range, and reindex the names' subdomains.
"""
log.debug("Processing subdomain updates for zonefiles in blocks {}-{}".format(block_start, block_end))
res = self.find_zonefile_subdomains(block_start, block_end)
zonefile_subdomain_info = res['zonefile_info']
self.process_subdomains(zonefile_subdomain_info) | [
"def",
"index_blockchain",
"(",
"self",
",",
"block_start",
",",
"block_end",
")",
":",
"log",
".",
"debug",
"(",
"\"Processing subdomain updates for zonefiles in blocks {}-{}\"",
".",
"format",
"(",
"block_start",
",",
"block_end",
")",
")",
"res",
"=",
"self",
"... | Go through the sequence of zone files discovered in a block range, and reindex the names' subdomains. | [
"Go",
"through",
"the",
"sequence",
"of",
"zone",
"files",
"discovered",
"in",
"a",
"block",
"range",
"and",
"reindex",
"the",
"names",
"subdomains",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L838-L847 | train | 225,530 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainIndex.index_discovered_zonefiles | def index_discovered_zonefiles(self, lastblock):
"""
Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height.
Find all subsequent zone files for this name, and process all subdomain operations contained within them.
"""
all_queued_zfinfos = [] # contents of the queue
subdomain_zonefile_infos = {} # map subdomain fqn to list of zonefile info bundles, for process_subdomains
name_blocks = {} # map domain name to the block at which we should reprocess its subsequent zone files
offset = 0
while True:
queued_zfinfos = queuedb_findall(self.subdomain_queue_path, "zonefiles", limit=100, offset=offset)
if len(queued_zfinfos) == 0:
# done!
break
offset += 100
all_queued_zfinfos += queued_zfinfos
if len(all_queued_zfinfos) >= 1000:
# only do so many zone files per block, so we don't stall the node
break
log.debug("Discovered {} zonefiles".format(len(all_queued_zfinfos)))
for queued_zfinfo in all_queued_zfinfos:
zfinfo = json.loads(queued_zfinfo['data'])
zonefile_hash = zfinfo['zonefile_hash']
block_height = zfinfo['block_height']
# find out the names that sent this zone file at this block
zfinfos = atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=block_height, path=self.atlasdb_path)
if zfinfos is None:
log.warn("Absent zonefile {}".format(zonefile_hash))
continue
# find out for each name block height at which its zone file was discovered.
# this is where we'll begin looking for more subdomain updates.
for zfi in zfinfos:
if zfi['name'] not in name_blocks:
name_blocks[zfi['name']] = block_height
else:
name_blocks[zfi['name']] = min(block_height, name_blocks[zfi['name']])
for name in name_blocks:
if name_blocks[name] >= lastblock:
continue
log.debug("Finding subdomain updates for {} at block {}".format(name, name_blocks[name]))
# get the subdomains affected at this block by finding the zonefiles created here.
res = self.find_zonefile_subdomains(name_blocks[name], lastblock, name=name)
zonefile_subdomain_info = res['zonefile_info']
subdomain_index = res['subdomains']
# for each subdomain, find the list of zonefiles that contain records for it
for fqn in subdomain_index:
if fqn not in subdomain_zonefile_infos:
subdomain_zonefile_infos[fqn] = []
for i in subdomain_index[fqn]:
subdomain_zonefile_infos[fqn].append(zonefile_subdomain_info[i])
processed = []
for fqn in subdomain_zonefile_infos:
subseq = filter(lambda szi: szi['zonefile_hash'] not in processed, subdomain_zonefile_infos[fqn])
if len(subseq) == 0:
continue
log.debug("Processing {} zone file entries found for {} and others".format(len(subseq), fqn))
subseq.sort(cmp=lambda z1, z2: -1 if z1['block_height'] < z2['block_height'] else 0 if z1['block_height'] == z2['block_height'] else 1)
self.process_subdomains(subseq)
processed += [szi['zonefile_hash'] for szi in subseq]
# clear queue
queuedb_removeall(self.subdomain_queue_path, all_queued_zfinfos)
return True | python | def index_discovered_zonefiles(self, lastblock):
"""
Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height.
Find all subsequent zone files for this name, and process all subdomain operations contained within them.
"""
all_queued_zfinfos = [] # contents of the queue
subdomain_zonefile_infos = {} # map subdomain fqn to list of zonefile info bundles, for process_subdomains
name_blocks = {} # map domain name to the block at which we should reprocess its subsequent zone files
offset = 0
while True:
queued_zfinfos = queuedb_findall(self.subdomain_queue_path, "zonefiles", limit=100, offset=offset)
if len(queued_zfinfos) == 0:
# done!
break
offset += 100
all_queued_zfinfos += queued_zfinfos
if len(all_queued_zfinfos) >= 1000:
# only do so many zone files per block, so we don't stall the node
break
log.debug("Discovered {} zonefiles".format(len(all_queued_zfinfos)))
for queued_zfinfo in all_queued_zfinfos:
zfinfo = json.loads(queued_zfinfo['data'])
zonefile_hash = zfinfo['zonefile_hash']
block_height = zfinfo['block_height']
# find out the names that sent this zone file at this block
zfinfos = atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=block_height, path=self.atlasdb_path)
if zfinfos is None:
log.warn("Absent zonefile {}".format(zonefile_hash))
continue
# find out for each name block height at which its zone file was discovered.
# this is where we'll begin looking for more subdomain updates.
for zfi in zfinfos:
if zfi['name'] not in name_blocks:
name_blocks[zfi['name']] = block_height
else:
name_blocks[zfi['name']] = min(block_height, name_blocks[zfi['name']])
for name in name_blocks:
if name_blocks[name] >= lastblock:
continue
log.debug("Finding subdomain updates for {} at block {}".format(name, name_blocks[name]))
# get the subdomains affected at this block by finding the zonefiles created here.
res = self.find_zonefile_subdomains(name_blocks[name], lastblock, name=name)
zonefile_subdomain_info = res['zonefile_info']
subdomain_index = res['subdomains']
# for each subdomain, find the list of zonefiles that contain records for it
for fqn in subdomain_index:
if fqn not in subdomain_zonefile_infos:
subdomain_zonefile_infos[fqn] = []
for i in subdomain_index[fqn]:
subdomain_zonefile_infos[fqn].append(zonefile_subdomain_info[i])
processed = []
for fqn in subdomain_zonefile_infos:
subseq = filter(lambda szi: szi['zonefile_hash'] not in processed, subdomain_zonefile_infos[fqn])
if len(subseq) == 0:
continue
log.debug("Processing {} zone file entries found for {} and others".format(len(subseq), fqn))
subseq.sort(cmp=lambda z1, z2: -1 if z1['block_height'] < z2['block_height'] else 0 if z1['block_height'] == z2['block_height'] else 1)
self.process_subdomains(subseq)
processed += [szi['zonefile_hash'] for szi in subseq]
# clear queue
queuedb_removeall(self.subdomain_queue_path, all_queued_zfinfos)
return True | [
"def",
"index_discovered_zonefiles",
"(",
"self",
",",
"lastblock",
")",
":",
"all_queued_zfinfos",
"=",
"[",
"]",
"# contents of the queue",
"subdomain_zonefile_infos",
"=",
"{",
"}",
"# map subdomain fqn to list of zonefile info bundles, for process_subdomains",
"name_blocks",
... | Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height.
Find all subsequent zone files for this name, and process all subdomain operations contained within them. | [
"Go",
"through",
"the",
"list",
"of",
"zone",
"files",
"we",
"discovered",
"via",
"Atlas",
"grouped",
"by",
"name",
"and",
"ordered",
"by",
"block",
"height",
".",
"Find",
"all",
"subsequent",
"zone",
"files",
"for",
"this",
"name",
"and",
"process",
"all"... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L850-L929 | train | 225,531 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.subdomain_row_factory | def subdomain_row_factory(cls, cursor, row):
"""
Dict row factory for subdomains
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | python | def subdomain_row_factory(cls, cursor, row):
"""
Dict row factory for subdomains
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | [
"def",
"subdomain_row_factory",
"(",
"cls",
",",
"cursor",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"cursor",
".",
"description",
")",
":",
"d",
"[",
"col",
"[",
"0",
"]",
"]",
"=",
"row",
"[",
... | Dict row factory for subdomains | [
"Dict",
"row",
"factory",
"for",
"subdomains"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1000-L1008 | train | 225,532 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB._extract_subdomain | def _extract_subdomain(self, rowdata):
"""
Extract a single subdomain from a DB cursor
Raise SubdomainNotFound if there are no valid rows
"""
name = str(rowdata['fully_qualified_subdomain'])
domain = str(rowdata['domain'])
n = str(rowdata['sequence'])
encoded_pubkey = str(rowdata['owner'])
zonefile_hash = str(rowdata['zonefile_hash'])
sig = rowdata['signature']
block_height = int(rowdata['block_height'])
parent_zonefile_hash = str(rowdata['parent_zonefile_hash'])
parent_zonefile_index = int(rowdata['parent_zonefile_index'])
zonefile_offset = int(rowdata['zonefile_offset'])
txid = str(rowdata['txid'])
missing = [int(i) for i in rowdata['missing'].split(',')] if rowdata['missing'] is not None and len(rowdata['missing']) > 0 else []
accepted = int(rowdata['accepted'])
resolver = str(rowdata['resolver']) if rowdata['resolver'] is not None else None
if accepted == 0:
accepted = False
else:
accepted = True
if sig == '' or sig is None:
sig = None
else:
sig = str(sig)
name = str(name)
is_subdomain, _, _ = is_address_subdomain(name)
if not is_subdomain:
raise Exception("Subdomain DB lookup returned bad subdomain result {}".format(name))
zonefile_str = get_atlas_zonefile_data(zonefile_hash, self.zonefiles_dir)
if zonefile_str is None:
log.error("No zone file for {}".format(name))
raise SubdomainNotFound('{}: missing zone file {}'.format(name, zonefile_hash))
return Subdomain(str(name), str(domain), str(encoded_pubkey), int(n), str(zonefile_str), sig, block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing=missing, accepted=accepted, resolver=resolver) | python | def _extract_subdomain(self, rowdata):
"""
Extract a single subdomain from a DB cursor
Raise SubdomainNotFound if there are no valid rows
"""
name = str(rowdata['fully_qualified_subdomain'])
domain = str(rowdata['domain'])
n = str(rowdata['sequence'])
encoded_pubkey = str(rowdata['owner'])
zonefile_hash = str(rowdata['zonefile_hash'])
sig = rowdata['signature']
block_height = int(rowdata['block_height'])
parent_zonefile_hash = str(rowdata['parent_zonefile_hash'])
parent_zonefile_index = int(rowdata['parent_zonefile_index'])
zonefile_offset = int(rowdata['zonefile_offset'])
txid = str(rowdata['txid'])
missing = [int(i) for i in rowdata['missing'].split(',')] if rowdata['missing'] is not None and len(rowdata['missing']) > 0 else []
accepted = int(rowdata['accepted'])
resolver = str(rowdata['resolver']) if rowdata['resolver'] is not None else None
if accepted == 0:
accepted = False
else:
accepted = True
if sig == '' or sig is None:
sig = None
else:
sig = str(sig)
name = str(name)
is_subdomain, _, _ = is_address_subdomain(name)
if not is_subdomain:
raise Exception("Subdomain DB lookup returned bad subdomain result {}".format(name))
zonefile_str = get_atlas_zonefile_data(zonefile_hash, self.zonefiles_dir)
if zonefile_str is None:
log.error("No zone file for {}".format(name))
raise SubdomainNotFound('{}: missing zone file {}'.format(name, zonefile_hash))
return Subdomain(str(name), str(domain), str(encoded_pubkey), int(n), str(zonefile_str), sig, block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing=missing, accepted=accepted, resolver=resolver) | [
"def",
"_extract_subdomain",
"(",
"self",
",",
"rowdata",
")",
":",
"name",
"=",
"str",
"(",
"rowdata",
"[",
"'fully_qualified_subdomain'",
"]",
")",
"domain",
"=",
"str",
"(",
"rowdata",
"[",
"'domain'",
"]",
")",
"n",
"=",
"str",
"(",
"rowdata",
"[",
... | Extract a single subdomain from a DB cursor
Raise SubdomainNotFound if there are no valid rows | [
"Extract",
"a",
"single",
"subdomain",
"from",
"a",
"DB",
"cursor",
"Raise",
"SubdomainNotFound",
"if",
"there",
"are",
"no",
"valid",
"rows"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1025-L1065 | train | 225,533 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_subdomains_count | def get_subdomains_count(self, accepted=True, cur=None):
"""
Fetch subdomain names
"""
if accepted:
accepted_filter = 'WHERE accepted=1'
else:
accepted_filter = ''
get_cmd = "SELECT COUNT(DISTINCT fully_qualified_subdomain) as count FROM {} {};".format(
self.subdomain_table, accepted_filter)
cursor = cur
if cursor is None:
cursor = self.conn.cursor()
db_query_execute(cursor, get_cmd, ())
try:
rowdata = cursor.fetchone()
return rowdata['count']
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return 0 | python | def get_subdomains_count(self, accepted=True, cur=None):
"""
Fetch subdomain names
"""
if accepted:
accepted_filter = 'WHERE accepted=1'
else:
accepted_filter = ''
get_cmd = "SELECT COUNT(DISTINCT fully_qualified_subdomain) as count FROM {} {};".format(
self.subdomain_table, accepted_filter)
cursor = cur
if cursor is None:
cursor = self.conn.cursor()
db_query_execute(cursor, get_cmd, ())
try:
rowdata = cursor.fetchone()
return rowdata['count']
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return 0 | [
"def",
"get_subdomains_count",
"(",
"self",
",",
"accepted",
"=",
"True",
",",
"cur",
"=",
"None",
")",
":",
"if",
"accepted",
":",
"accepted_filter",
"=",
"'WHERE accepted=1'",
"else",
":",
"accepted_filter",
"=",
"''",
"get_cmd",
"=",
"\"SELECT COUNT(DISTINCT ... | Fetch subdomain names | [
"Fetch",
"subdomain",
"names"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1068-L1092 | train | 225,534 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_all_subdomains | def get_all_subdomains(self, offset=None, count=None, min_sequence=None, cur=None):
"""
Get and all subdomain names, optionally over a range
"""
get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}'.format(self.subdomain_table)
args = ()
if min_sequence is not None:
get_cmd += ' WHERE sequence >= ?'
args += (min_sequence,)
if count is not None:
get_cmd += ' LIMIT ?'
args += (count,)
if offset is not None:
get_cmd += ' OFFSET ?'
args += (offset,)
get_cmd += ';'
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, get_cmd, args)
subdomains = []
for row in rows:
subdomains.append(row['fully_qualified_subdomain'])
return subdomains | python | def get_all_subdomains(self, offset=None, count=None, min_sequence=None, cur=None):
"""
Get and all subdomain names, optionally over a range
"""
get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}'.format(self.subdomain_table)
args = ()
if min_sequence is not None:
get_cmd += ' WHERE sequence >= ?'
args += (min_sequence,)
if count is not None:
get_cmd += ' LIMIT ?'
args += (count,)
if offset is not None:
get_cmd += ' OFFSET ?'
args += (offset,)
get_cmd += ';'
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, get_cmd, args)
subdomains = []
for row in rows:
subdomains.append(row['fully_qualified_subdomain'])
return subdomains | [
"def",
"get_all_subdomains",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"min_sequence",
"=",
"None",
",",
"cur",
"=",
"None",
")",
":",
"get_cmd",
"=",
"'SELECT DISTINCT fully_qualified_subdomain FROM {}'",
".",
"format",
"(",
"se... | Get and all subdomain names, optionally over a range | [
"Get",
"and",
"all",
"subdomain",
"names",
"optionally",
"over",
"a",
"range"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1095-L1127 | train | 225,535 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_subdomain_ops_at_txid | def get_subdomain_ops_at_txid(self, txid, cur=None):
"""
Given a txid, get all subdomain operations at that txid.
Include unaccepted operations.
Order by zone file index
"""
get_cmd = 'SELECT * FROM {} WHERE txid = ? ORDER BY zonefile_offset'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (txid,))
try:
return [x for x in cursor.fetchall()]
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return [] | python | def get_subdomain_ops_at_txid(self, txid, cur=None):
"""
Given a txid, get all subdomain operations at that txid.
Include unaccepted operations.
Order by zone file index
"""
get_cmd = 'SELECT * FROM {} WHERE txid = ? ORDER BY zonefile_offset'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (txid,))
try:
return [x for x in cursor.fetchall()]
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return [] | [
"def",
"get_subdomain_ops_at_txid",
"(",
"self",
",",
"txid",
",",
"cur",
"=",
"None",
")",
":",
"get_cmd",
"=",
"'SELECT * FROM {} WHERE txid = ? ORDER BY zonefile_offset'",
".",
"format",
"(",
"self",
".",
"subdomain_table",
")",
"cursor",
"=",
"None",
"if",
"cu... | Given a txid, get all subdomain operations at that txid.
Include unaccepted operations.
Order by zone file index | [
"Given",
"a",
"txid",
"get",
"all",
"subdomain",
"operations",
"at",
"that",
"txid",
".",
"Include",
"unaccepted",
"operations",
".",
"Order",
"by",
"zone",
"file",
"index"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1202-L1224 | train | 225,536 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_subdomains_owned_by_address | def get_subdomains_owned_by_address(self, owner, cur=None):
"""
Get the list of subdomain names that are owned by a given address.
"""
get_cmd = "SELECT fully_qualified_subdomain, MAX(sequence) FROM {} WHERE owner = ? AND accepted=1 GROUP BY fully_qualified_subdomain".format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (owner,))
try:
return [ x['fully_qualified_subdomain'] for x in cursor.fetchall() ]
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return [] | python | def get_subdomains_owned_by_address(self, owner, cur=None):
"""
Get the list of subdomain names that are owned by a given address.
"""
get_cmd = "SELECT fully_qualified_subdomain, MAX(sequence) FROM {} WHERE owner = ? AND accepted=1 GROUP BY fully_qualified_subdomain".format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (owner,))
try:
return [ x['fully_qualified_subdomain'] for x in cursor.fetchall() ]
except Exception as e:
if BLOCKSTACK_DEBUG:
log.exception(e)
return [] | [
"def",
"get_subdomains_owned_by_address",
"(",
"self",
",",
"owner",
",",
"cur",
"=",
"None",
")",
":",
"get_cmd",
"=",
"\"SELECT fully_qualified_subdomain, MAX(sequence) FROM {} WHERE owner = ? AND accepted=1 GROUP BY fully_qualified_subdomain\"",
".",
"format",
"(",
"self",
"... | Get the list of subdomain names that are owned by a given address. | [
"Get",
"the",
"list",
"of",
"subdomain",
"names",
"that",
"are",
"owned",
"by",
"a",
"given",
"address",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1227-L1247 | train | 225,537 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_domain_resolver | def get_domain_resolver(self, domain_name, cur=None):
"""
Get the last-knwon resolver entry for a domain name
Returns None if not found.
"""
get_cmd = "SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;".format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (domain_name,))
rowdata = cursor.fetchone()
if not rowdata:
return None
return rowdata['resolver'] | python | def get_domain_resolver(self, domain_name, cur=None):
"""
Get the last-knwon resolver entry for a domain name
Returns None if not found.
"""
get_cmd = "SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;".format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, get_cmd, (domain_name,))
rowdata = cursor.fetchone()
if not rowdata:
return None
return rowdata['resolver'] | [
"def",
"get_domain_resolver",
"(",
"self",
",",
"domain_name",
",",
"cur",
"=",
"None",
")",
":",
"get_cmd",
"=",
"\"SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;\"",
".",
"format",
"(",
"self"... | Get the last-knwon resolver entry for a domain name
Returns None if not found. | [
"Get",
"the",
"last",
"-",
"knwon",
"resolver",
"entry",
"for",
"a",
"domain",
"name",
"Returns",
"None",
"if",
"not",
"found",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1250-L1269 | train | 225,538 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_subdomain_DID_info | def get_subdomain_DID_info(self, fqn, cur=None):
"""
Get the DID information for a subdomain.
Raise SubdomainNotFound if there is no such subdomain
Return {'name_type': ..., 'address': ..., 'index': ...}
"""
subrec = self.get_subdomain_entry_at_sequence(fqn, 0, cur=cur)
cmd = 'SELECT zonefile_offset FROM {} WHERE fully_qualified_subdomain = ? AND owner = ? AND sequence=0 AND parent_zonefile_index <= ? AND accepted=1 ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1;'.format(self.subdomain_table)
args = (fqn, subrec.address, subrec.parent_zonefile_index)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, cmd, args)
zonefile_offset = None
for r in rows:
zonefile_offset = r['zonefile_offset']
break
if zonefile_offset is None:
raise SubdomainNotFound('No rows for {}'.format(fqn))
cmd = 'SELECT COUNT(*) FROM {} WHERE owner = ? AND sequence=0 AND (parent_zonefile_index < ? OR parent_zonefile_index = ? AND zonefile_offset < ?) AND accepted=1 ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1;'.format(self.subdomain_table)
args = (subrec.address, subrec.parent_zonefile_index, subrec.parent_zonefile_index, zonefile_offset)
rows = db_query_execute(cursor, cmd, args)
count = None
for r in rows:
count = r['COUNT(*)']
break
if count is None:
raise SubdomainNotFound('No rows for {}'.format(fqn))
return {'name_type': 'subdomain', 'address': subrec.address, 'index': count} | python | def get_subdomain_DID_info(self, fqn, cur=None):
"""
Get the DID information for a subdomain.
Raise SubdomainNotFound if there is no such subdomain
Return {'name_type': ..., 'address': ..., 'index': ...}
"""
subrec = self.get_subdomain_entry_at_sequence(fqn, 0, cur=cur)
cmd = 'SELECT zonefile_offset FROM {} WHERE fully_qualified_subdomain = ? AND owner = ? AND sequence=0 AND parent_zonefile_index <= ? AND accepted=1 ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1;'.format(self.subdomain_table)
args = (fqn, subrec.address, subrec.parent_zonefile_index)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, cmd, args)
zonefile_offset = None
for r in rows:
zonefile_offset = r['zonefile_offset']
break
if zonefile_offset is None:
raise SubdomainNotFound('No rows for {}'.format(fqn))
cmd = 'SELECT COUNT(*) FROM {} WHERE owner = ? AND sequence=0 AND (parent_zonefile_index < ? OR parent_zonefile_index = ? AND zonefile_offset < ?) AND accepted=1 ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1;'.format(self.subdomain_table)
args = (subrec.address, subrec.parent_zonefile_index, subrec.parent_zonefile_index, zonefile_offset)
rows = db_query_execute(cursor, cmd, args)
count = None
for r in rows:
count = r['COUNT(*)']
break
if count is None:
raise SubdomainNotFound('No rows for {}'.format(fqn))
return {'name_type': 'subdomain', 'address': subrec.address, 'index': count} | [
"def",
"get_subdomain_DID_info",
"(",
"self",
",",
"fqn",
",",
"cur",
"=",
"None",
")",
":",
"subrec",
"=",
"self",
".",
"get_subdomain_entry_at_sequence",
"(",
"fqn",
",",
"0",
",",
"cur",
"=",
"cur",
")",
"cmd",
"=",
"'SELECT zonefile_offset FROM {} WHERE fu... | Get the DID information for a subdomain.
Raise SubdomainNotFound if there is no such subdomain
Return {'name_type': ..., 'address': ..., 'index': ...} | [
"Get",
"the",
"DID",
"information",
"for",
"a",
"subdomain",
".",
"Raise",
"SubdomainNotFound",
"if",
"there",
"is",
"no",
"such",
"subdomain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1272-L1311 | train | 225,539 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_DID_subdomain | def get_DID_subdomain(self, did, cur=None):
"""
Get a subdomain, given its DID
Raise ValueError if the DID is invalid
Raise SubdomainNotFound if the DID does not correspond to a subdomain
"""
did = str(did)
try:
did_info = parse_DID(did)
assert did_info['name_type'] == 'subdomain', 'Not a subdomain DID'
except:
raise ValueError("Invalid DID: {}".format(did))
original_address = did_info['address']
name_index = did_info['index']
# find the initial subdomain (the nth subdomain created by this address)
cmd = 'SELECT fully_qualified_subdomain FROM {} WHERE owner = ? AND sequence = ? ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1 OFFSET ?;'.format(self.subdomain_table)
args = (original_address, 0, name_index)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
subdomain_name = None
rows = db_query_execute(cursor, cmd, args)
for r in rows:
subdomain_name = r['fully_qualified_subdomain']
break
if not subdomain_name:
raise SubdomainNotFound('Does not correspond to a subdomain: {}'.format(did))
# get the current form
subrec = self.get_subdomain_entry(subdomain_name, cur=cur)
subrec.did_info = did_info
return subrec | python | def get_DID_subdomain(self, did, cur=None):
"""
Get a subdomain, given its DID
Raise ValueError if the DID is invalid
Raise SubdomainNotFound if the DID does not correspond to a subdomain
"""
did = str(did)
try:
did_info = parse_DID(did)
assert did_info['name_type'] == 'subdomain', 'Not a subdomain DID'
except:
raise ValueError("Invalid DID: {}".format(did))
original_address = did_info['address']
name_index = did_info['index']
# find the initial subdomain (the nth subdomain created by this address)
cmd = 'SELECT fully_qualified_subdomain FROM {} WHERE owner = ? AND sequence = ? ORDER BY parent_zonefile_index, zonefile_offset LIMIT 1 OFFSET ?;'.format(self.subdomain_table)
args = (original_address, 0, name_index)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
subdomain_name = None
rows = db_query_execute(cursor, cmd, args)
for r in rows:
subdomain_name = r['fully_qualified_subdomain']
break
if not subdomain_name:
raise SubdomainNotFound('Does not correspond to a subdomain: {}'.format(did))
# get the current form
subrec = self.get_subdomain_entry(subdomain_name, cur=cur)
subrec.did_info = did_info
return subrec | [
"def",
"get_DID_subdomain",
"(",
"self",
",",
"did",
",",
"cur",
"=",
"None",
")",
":",
"did",
"=",
"str",
"(",
"did",
")",
"try",
":",
"did_info",
"=",
"parse_DID",
"(",
"did",
")",
"assert",
"did_info",
"[",
"'name_type'",
"]",
"==",
"'subdomain'",
... | Get a subdomain, given its DID
Raise ValueError if the DID is invalid
Raise SubdomainNotFound if the DID does not correspond to a subdomain | [
"Get",
"a",
"subdomain",
"given",
"its",
"DID",
"Raise",
"ValueError",
"if",
"the",
"DID",
"is",
"invalid",
"Raise",
"SubdomainNotFound",
"if",
"the",
"DID",
"does",
"not",
"correspond",
"to",
"a",
"subdomain"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1314-L1354 | train | 225,540 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.is_subdomain_zonefile_hash | def is_subdomain_zonefile_hash(self, fqn, zonefile_hash, cur=None):
"""
Does this zone file hash belong to this subdomain?
"""
sql = 'SELECT COUNT(zonefile_hash) FROM {} WHERE fully_qualified_subdomain = ? and zonefile_hash = ?;'.format(self.subdomain_table)
args = (fqn,zonefile_hash)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, sql, args)
count = None
for row in rows:
count = row['COUNT(zonefile_hash)']
break
return (count > 0) | python | def is_subdomain_zonefile_hash(self, fqn, zonefile_hash, cur=None):
"""
Does this zone file hash belong to this subdomain?
"""
sql = 'SELECT COUNT(zonefile_hash) FROM {} WHERE fully_qualified_subdomain = ? and zonefile_hash = ?;'.format(self.subdomain_table)
args = (fqn,zonefile_hash)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, sql, args)
count = None
for row in rows:
count = row['COUNT(zonefile_hash)']
break
return (count > 0) | [
"def",
"is_subdomain_zonefile_hash",
"(",
"self",
",",
"fqn",
",",
"zonefile_hash",
",",
"cur",
"=",
"None",
")",
":",
"sql",
"=",
"'SELECT COUNT(zonefile_hash) FROM {} WHERE fully_qualified_subdomain = ? and zonefile_hash = ?;'",
".",
"format",
"(",
"self",
".",
"subdoma... | Does this zone file hash belong to this subdomain? | [
"Does",
"this",
"zone",
"file",
"hash",
"belong",
"to",
"this",
"subdomain?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1357-L1377 | train | 225,541 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.update_subdomain_entry | def update_subdomain_entry(self, subdomain_obj, cur=None):
"""
Update the subdomain history table for this subdomain entry.
Creates it if it doesn't exist.
Return True on success
Raise exception on error
"""
# sanity checks
assert isinstance(subdomain_obj, Subdomain)
# NOTE: there is no need to call fsync() on the zone file fd here---we already have the data from the on-chain name's zone file fsync'ed,
# so this information is already durable (albeit somewhere else) and can ostensibly be restored later.
# We get such high subdomain traffic that we cannot call fsync() here each time; otherwise we could stall the node.
zonefile_hash = get_zonefile_data_hash(subdomain_obj.zonefile_str)
rc = store_atlas_zonefile_data(subdomain_obj.zonefile_str, self.zonefiles_dir, fsync=False)
if not rc:
raise Exception("Failed to store zone file {} from {}".format(zonefile_hash, subdomain_obj.get_fqn()))
write_cmd = 'INSERT OR REPLACE INTO {} VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'.format(self.subdomain_table)
args = (subdomain_obj.get_fqn(), subdomain_obj.domain, subdomain_obj.n, subdomain_obj.address, zonefile_hash,
subdomain_obj.sig, subdomain_obj.block_height, subdomain_obj.parent_zonefile_hash,
subdomain_obj.parent_zonefile_index, subdomain_obj.zonefile_offset, subdomain_obj.txid,
','.join(str(i) for i in subdomain_obj.domain_zonefiles_missing),
1 if subdomain_obj.accepted else 0,
subdomain_obj.resolver)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, write_cmd, args)
num_rows_written = cursor.rowcount
if cur is None:
# not part of a transaction
self.conn.commit()
if num_rows_written != 1:
raise ValueError("No row written: fqn={} seq={}".format(subdomain_obj.get_fqn(), subdomain_obj.n))
return True | python | def update_subdomain_entry(self, subdomain_obj, cur=None):
"""
Update the subdomain history table for this subdomain entry.
Creates it if it doesn't exist.
Return True on success
Raise exception on error
"""
# sanity checks
assert isinstance(subdomain_obj, Subdomain)
# NOTE: there is no need to call fsync() on the zone file fd here---we already have the data from the on-chain name's zone file fsync'ed,
# so this information is already durable (albeit somewhere else) and can ostensibly be restored later.
# We get such high subdomain traffic that we cannot call fsync() here each time; otherwise we could stall the node.
zonefile_hash = get_zonefile_data_hash(subdomain_obj.zonefile_str)
rc = store_atlas_zonefile_data(subdomain_obj.zonefile_str, self.zonefiles_dir, fsync=False)
if not rc:
raise Exception("Failed to store zone file {} from {}".format(zonefile_hash, subdomain_obj.get_fqn()))
write_cmd = 'INSERT OR REPLACE INTO {} VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'.format(self.subdomain_table)
args = (subdomain_obj.get_fqn(), subdomain_obj.domain, subdomain_obj.n, subdomain_obj.address, zonefile_hash,
subdomain_obj.sig, subdomain_obj.block_height, subdomain_obj.parent_zonefile_hash,
subdomain_obj.parent_zonefile_index, subdomain_obj.zonefile_offset, subdomain_obj.txid,
','.join(str(i) for i in subdomain_obj.domain_zonefiles_missing),
1 if subdomain_obj.accepted else 0,
subdomain_obj.resolver)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, write_cmd, args)
num_rows_written = cursor.rowcount
if cur is None:
# not part of a transaction
self.conn.commit()
if num_rows_written != 1:
raise ValueError("No row written: fqn={} seq={}".format(subdomain_obj.get_fqn(), subdomain_obj.n))
return True | [
"def",
"update_subdomain_entry",
"(",
"self",
",",
"subdomain_obj",
",",
"cur",
"=",
"None",
")",
":",
"# sanity checks",
"assert",
"isinstance",
"(",
"subdomain_obj",
",",
"Subdomain",
")",
"# NOTE: there is no need to call fsync() on the zone file fd here---we already have ... | Update the subdomain history table for this subdomain entry.
Creates it if it doesn't exist.
Return True on success
Raise exception on error | [
"Update",
"the",
"subdomain",
"history",
"table",
"for",
"this",
"subdomain",
"entry",
".",
"Creates",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1435-L1478 | train | 225,542 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_last_block | def get_last_block(self, cur=None):
"""
Get the highest block last processed
"""
sql = 'SELECT MAX(block_height) FROM {};'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, sql, ())
height = 0
try:
rowdata = rows.fetchone()
height = rowdata['MAX(block_height)']
except:
height = 0
return height | python | def get_last_block(self, cur=None):
"""
Get the highest block last processed
"""
sql = 'SELECT MAX(block_height) FROM {};'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
rows = db_query_execute(cursor, sql, ())
height = 0
try:
rowdata = rows.fetchone()
height = rowdata['MAX(block_height)']
except:
height = 0
return height | [
"def",
"get_last_block",
"(",
"self",
",",
"cur",
"=",
"None",
")",
":",
"sql",
"=",
"'SELECT MAX(block_height) FROM {};'",
".",
"format",
"(",
"self",
".",
"subdomain_table",
")",
"cursor",
"=",
"None",
"if",
"cur",
"is",
"None",
":",
"cursor",
"=",
"self... | Get the highest block last processed | [
"Get",
"the",
"highest",
"block",
"last",
"processed"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1513-L1532 | train | 225,543 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB.get_last_sequence | def get_last_sequence(self, cur=None):
"""
Get the highest sequence number in this db
"""
sql = 'SELECT sequence FROM {} ORDER BY sequence DESC LIMIT 1;'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, sql, ())
last_seq = None
try:
last_seq = cursor.fetchone()[0]
except:
last_seq = 0
return int(last_seq) | python | def get_last_sequence(self, cur=None):
"""
Get the highest sequence number in this db
"""
sql = 'SELECT sequence FROM {} ORDER BY sequence DESC LIMIT 1;'.format(self.subdomain_table)
cursor = None
if cur is None:
cursor = self.conn.cursor()
else:
cursor = cur
db_query_execute(cursor, sql, ())
last_seq = None
try:
last_seq = cursor.fetchone()[0]
except:
last_seq = 0
return int(last_seq) | [
"def",
"get_last_sequence",
"(",
"self",
",",
"cur",
"=",
"None",
")",
":",
"sql",
"=",
"'SELECT sequence FROM {} ORDER BY sequence DESC LIMIT 1;'",
".",
"format",
"(",
"self",
".",
"subdomain_table",
")",
"cursor",
"=",
"None",
"if",
"cur",
"is",
"None",
":",
... | Get the highest sequence number in this db | [
"Get",
"the",
"highest",
"sequence",
"number",
"in",
"this",
"db"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1535-L1553 | train | 225,544 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | SubdomainDB._drop_tables | def _drop_tables(self):
"""
Clear the subdomain db's tables
"""
drop_cmd = "DROP TABLE IF EXISTS {};"
for table in [self.subdomain_table, self.blocked_table]:
cursor = self.conn.cursor()
db_query_execute(cursor, drop_cmd.format(table), ()) | python | def _drop_tables(self):
"""
Clear the subdomain db's tables
"""
drop_cmd = "DROP TABLE IF EXISTS {};"
for table in [self.subdomain_table, self.blocked_table]:
cursor = self.conn.cursor()
db_query_execute(cursor, drop_cmd.format(table), ()) | [
"def",
"_drop_tables",
"(",
"self",
")",
":",
"drop_cmd",
"=",
"\"DROP TABLE IF EXISTS {};\"",
"for",
"table",
"in",
"[",
"self",
".",
"subdomain_table",
",",
"self",
".",
"blocked_table",
"]",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
"... | Clear the subdomain db's tables | [
"Clear",
"the",
"subdomain",
"db",
"s",
"tables"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1556-L1563 | train | 225,545 |
blockstack/blockstack-core | blockstack/lib/hashing.py | hash_name | def hash_name(name, script_pubkey, register_addr=None):
"""
Generate the hash over a name and hex-string script pubkey
"""
bin_name = b40_to_bin(name)
name_and_pubkey = bin_name + unhexlify(script_pubkey)
if register_addr is not None:
name_and_pubkey += str(register_addr)
return hex_hash160(name_and_pubkey) | python | def hash_name(name, script_pubkey, register_addr=None):
"""
Generate the hash over a name and hex-string script pubkey
"""
bin_name = b40_to_bin(name)
name_and_pubkey = bin_name + unhexlify(script_pubkey)
if register_addr is not None:
name_and_pubkey += str(register_addr)
return hex_hash160(name_and_pubkey) | [
"def",
"hash_name",
"(",
"name",
",",
"script_pubkey",
",",
"register_addr",
"=",
"None",
")",
":",
"bin_name",
"=",
"b40_to_bin",
"(",
"name",
")",
"name_and_pubkey",
"=",
"bin_name",
"+",
"unhexlify",
"(",
"script_pubkey",
")",
"if",
"register_addr",
"is",
... | Generate the hash over a name and hex-string script pubkey | [
"Generate",
"the",
"hash",
"over",
"a",
"name",
"and",
"hex",
"-",
"string",
"script",
"pubkey"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/hashing.py#L32-L42 | train | 225,546 |
blockstack/blockstack-core | api/search/basic_index.py | fetch_profile_data_from_file | def fetch_profile_data_from_file():
""" takes profile data from file and saves in the profile_data DB
"""
with open(SEARCH_PROFILE_DATA_FILE, 'r') as fin:
profiles = json.load(fin)
counter = 0
log.debug("-" * 5)
log.debug("Fetching profile data from file")
for entry in profiles:
new_entry = {}
new_entry['key'] = entry['fqu']
new_entry['value'] = entry['profile']
try:
clean_profile_entries(entry['profile'])
profile_data.save(new_entry)
except Exception as e:
log.exception(e)
log.error("Exception on entry {}".format(new_entry))
counter += 1
if counter % 1000 == 0:
log.debug("Processed entries: %s" % counter)
profile_data.ensure_index('key')
return | python | def fetch_profile_data_from_file():
""" takes profile data from file and saves in the profile_data DB
"""
with open(SEARCH_PROFILE_DATA_FILE, 'r') as fin:
profiles = json.load(fin)
counter = 0
log.debug("-" * 5)
log.debug("Fetching profile data from file")
for entry in profiles:
new_entry = {}
new_entry['key'] = entry['fqu']
new_entry['value'] = entry['profile']
try:
clean_profile_entries(entry['profile'])
profile_data.save(new_entry)
except Exception as e:
log.exception(e)
log.error("Exception on entry {}".format(new_entry))
counter += 1
if counter % 1000 == 0:
log.debug("Processed entries: %s" % counter)
profile_data.ensure_index('key')
return | [
"def",
"fetch_profile_data_from_file",
"(",
")",
":",
"with",
"open",
"(",
"SEARCH_PROFILE_DATA_FILE",
",",
"'r'",
")",
"as",
"fin",
":",
"profiles",
"=",
"json",
".",
"load",
"(",
"fin",
")",
"counter",
"=",
"0",
"log",
".",
"debug",
"(",
"\"-\"",
"*",
... | takes profile data from file and saves in the profile_data DB | [
"takes",
"profile",
"data",
"from",
"file",
"and",
"saves",
"in",
"the",
"profile_data",
"DB"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/basic_index.py#L65-L95 | train | 225,547 |
blockstack/blockstack-core | api/search/basic_index.py | create_search_index | def create_search_index():
""" takes people names from blockchain and writes deduped names in a 'cache'
"""
# create people name cache
counter = 0
people_names = []
twitter_handles = []
usernames = []
log.debug("-" * 5)
log.debug("Creating search index")
for user in namespace.find():
# the profile/info to be inserted
search_profile = {}
counter += 1
if(counter % 1000 == 0):
log.debug("Processed entries: %s" % counter)
if validUsername(user['username']):
pass
else:
continue
profile = get_json(user['profile'])
hasBazaarId=False
# search for openbazaar id in the profile
if 'account' in profile:
for accounts in profile['account']:
if accounts['service'] == 'openbazaar':
hasBazaarId = True
search_profile['openbazaar']=accounts['identifier']
if (hasBazaarId == False):
search_profile['openbazaar'] = None
if 'name' in profile:
try:
name = profile['name']
except:
continue
try:
name = name['formatted'].lower()
except:
name = name.lower()
people_names.append(name)
search_profile['name'] = name
else:
search_profile['name'] = None
if 'twitter' in profile:
twitter_handle = profile['twitter']
try:
twitter_handle = twitter_handle['username'].lower()
except:
try:
twitter_handle = profile['twitter'].lower()
except:
continue
twitter_handles.append(twitter_handle)
search_profile['twitter_handle'] = twitter_handle
else:
search_profile['twitter_handle'] = None
search_profile['fullyQualifiedName'] = user['fqu']
search_profile['username'] = user['username']
usernames.append(user['fqu'])
search_profile['profile'] = profile
search_profiles.save(search_profile)
# dedup names
people_names = list(set(people_names))
people_names = {'name': people_names}
twitter_handles = list(set(twitter_handles))
twitter_handles = {'twitter_handle': twitter_handles}
usernames = list(set(usernames))
usernames = {'username': usernames}
# save final dedup results to mongodb (using it as a cache)
people_cache.save(people_names)
twitter_cache.save(twitter_handles)
username_cache.save(usernames)
optimize_db()
log.debug('Created name/twitter/username search index') | python | def create_search_index():
""" takes people names from blockchain and writes deduped names in a 'cache'
"""
# create people name cache
counter = 0
people_names = []
twitter_handles = []
usernames = []
log.debug("-" * 5)
log.debug("Creating search index")
for user in namespace.find():
# the profile/info to be inserted
search_profile = {}
counter += 1
if(counter % 1000 == 0):
log.debug("Processed entries: %s" % counter)
if validUsername(user['username']):
pass
else:
continue
profile = get_json(user['profile'])
hasBazaarId=False
# search for openbazaar id in the profile
if 'account' in profile:
for accounts in profile['account']:
if accounts['service'] == 'openbazaar':
hasBazaarId = True
search_profile['openbazaar']=accounts['identifier']
if (hasBazaarId == False):
search_profile['openbazaar'] = None
if 'name' in profile:
try:
name = profile['name']
except:
continue
try:
name = name['formatted'].lower()
except:
name = name.lower()
people_names.append(name)
search_profile['name'] = name
else:
search_profile['name'] = None
if 'twitter' in profile:
twitter_handle = profile['twitter']
try:
twitter_handle = twitter_handle['username'].lower()
except:
try:
twitter_handle = profile['twitter'].lower()
except:
continue
twitter_handles.append(twitter_handle)
search_profile['twitter_handle'] = twitter_handle
else:
search_profile['twitter_handle'] = None
search_profile['fullyQualifiedName'] = user['fqu']
search_profile['username'] = user['username']
usernames.append(user['fqu'])
search_profile['profile'] = profile
search_profiles.save(search_profile)
# dedup names
people_names = list(set(people_names))
people_names = {'name': people_names}
twitter_handles = list(set(twitter_handles))
twitter_handles = {'twitter_handle': twitter_handles}
usernames = list(set(usernames))
usernames = {'username': usernames}
# save final dedup results to mongodb (using it as a cache)
people_cache.save(people_names)
twitter_cache.save(twitter_handles)
username_cache.save(usernames)
optimize_db()
log.debug('Created name/twitter/username search index') | [
"def",
"create_search_index",
"(",
")",
":",
"# create people name cache",
"counter",
"=",
"0",
"people_names",
"=",
"[",
"]",
"twitter_handles",
"=",
"[",
"]",
"usernames",
"=",
"[",
"]",
"log",
".",
"debug",
"(",
"\"-\"",
"*",
"5",
")",
"log",
".",
"de... | takes people names from blockchain and writes deduped names in a 'cache' | [
"takes",
"people",
"names",
"from",
"blockchain",
"and",
"writes",
"deduped",
"names",
"in",
"a",
"cache"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/basic_index.py#L177-L277 | train | 225,548 |
blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_extract | def op_extract(op_name, data, senders, inputs, outputs, block_id, vtxindex, txid):
"""
Extract an operation from transaction data.
Return the extracted fields as a dict.
"""
global EXTRACT_METHODS
if op_name not in EXTRACT_METHODS.keys():
raise Exception("No such operation '%s'" % op_name)
method = EXTRACT_METHODS[op_name]
op_data = method( data, senders, inputs, outputs, block_id, vtxindex, txid )
return op_data | python | def op_extract(op_name, data, senders, inputs, outputs, block_id, vtxindex, txid):
"""
Extract an operation from transaction data.
Return the extracted fields as a dict.
"""
global EXTRACT_METHODS
if op_name not in EXTRACT_METHODS.keys():
raise Exception("No such operation '%s'" % op_name)
method = EXTRACT_METHODS[op_name]
op_data = method( data, senders, inputs, outputs, block_id, vtxindex, txid )
return op_data | [
"def",
"op_extract",
"(",
"op_name",
",",
"data",
",",
"senders",
",",
"inputs",
",",
"outputs",
",",
"block_id",
",",
"vtxindex",
",",
"txid",
")",
":",
"global",
"EXTRACT_METHODS",
"if",
"op_name",
"not",
"in",
"EXTRACT_METHODS",
".",
"keys",
"(",
")",
... | Extract an operation from transaction data.
Return the extracted fields as a dict. | [
"Extract",
"an",
"operation",
"from",
"transaction",
"data",
".",
"Return",
"the",
"extracted",
"fields",
"as",
"a",
"dict",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L183-L195 | train | 225,549 |
blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_canonicalize | def op_canonicalize(op_name, parsed_op):
"""
Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility
"""
global CANONICALIZE_METHODS
if op_name not in CANONICALIZE_METHODS:
# no canonicalization needed
return parsed_op
else:
return CANONICALIZE_METHODS[op_name](parsed_op) | python | def op_canonicalize(op_name, parsed_op):
"""
Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility
"""
global CANONICALIZE_METHODS
if op_name not in CANONICALIZE_METHODS:
# no canonicalization needed
return parsed_op
else:
return CANONICALIZE_METHODS[op_name](parsed_op) | [
"def",
"op_canonicalize",
"(",
"op_name",
",",
"parsed_op",
")",
":",
"global",
"CANONICALIZE_METHODS",
"if",
"op_name",
"not",
"in",
"CANONICALIZE_METHODS",
":",
"# no canonicalization needed",
"return",
"parsed_op",
"else",
":",
"return",
"CANONICALIZE_METHODS",
"[",
... | Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility | [
"Get",
"the",
"canonical",
"representation",
"of",
"a",
"parsed",
"operation",
"s",
"data",
".",
"Meant",
"for",
"backwards",
"-",
"compatibility"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L198-L209 | train | 225,550 |
blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_decanonicalize | def op_decanonicalize(op_name, canonical_op):
"""
Get the current representation of a parsed operation's data, given the canonical representation
Meant for backwards-compatibility
"""
global DECANONICALIZE_METHODS
if op_name not in DECANONICALIZE_METHODS:
# no decanonicalization needed
return canonical_op
else:
return DECANONICALIZE_METHODS[op_name](canonical_op) | python | def op_decanonicalize(op_name, canonical_op):
"""
Get the current representation of a parsed operation's data, given the canonical representation
Meant for backwards-compatibility
"""
global DECANONICALIZE_METHODS
if op_name not in DECANONICALIZE_METHODS:
# no decanonicalization needed
return canonical_op
else:
return DECANONICALIZE_METHODS[op_name](canonical_op) | [
"def",
"op_decanonicalize",
"(",
"op_name",
",",
"canonical_op",
")",
":",
"global",
"DECANONICALIZE_METHODS",
"if",
"op_name",
"not",
"in",
"DECANONICALIZE_METHODS",
":",
"# no decanonicalization needed",
"return",
"canonical_op",
"else",
":",
"return",
"DECANONICALIZE_M... | Get the current representation of a parsed operation's data, given the canonical representation
Meant for backwards-compatibility | [
"Get",
"the",
"current",
"representation",
"of",
"a",
"parsed",
"operation",
"s",
"data",
"given",
"the",
"canonical",
"representation",
"Meant",
"for",
"backwards",
"-",
"compatibility"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L212-L223 | train | 225,551 |
blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_check | def op_check( state_engine, nameop, block_id, checked_ops ):
"""
Given the state engine, the current block, the list of pending
operations processed so far, and the current operation, determine
whether or not it should be accepted.
The operation is allowed to be "type-cast" to a new operation, but only once.
If this happens, the operation will be checked again.
Subsequent casts are considered bugs, and will cause a program abort.
TODO: remove type-cast
"""
global CHECK_METHODS, MUTATE_FIELDS
nameop_clone = copy.deepcopy( nameop )
opcode = None
if 'opcode' not in nameop_clone.keys():
op = nameop_clone.get('op', None)
try:
assert op is not None, "BUG: no op defined"
opcode = op_get_opcode_name( op )
assert opcode is not None, "BUG: op '%s' undefined" % op
except Exception, e:
log.exception(e)
log.error("FATAL: BUG: no 'op' defined")
sys.exit(1)
else:
opcode = nameop_clone['opcode']
check_method = CHECK_METHODS.get( opcode, None )
try:
assert check_method is not None, "BUG: no check-method for '%s'" % opcode
except Exception, e:
log.exception(e)
log.error("FATAL: BUG: no check-method for '%s'" % opcode )
sys.exit(1)
rc = check_method( state_engine, nameop_clone, block_id, checked_ops )
if not rc:
# rejected
return False
# accepted! clean up and canonicalize
nameop.clear()
nameop.update(nameop_clone)
# nameop = op_canonicalize(nameop['opcode'], nameop)
op_canonicalize(nameop['opcode'], nameop)
# make sure we don't send unstored fields to the db that are otherwise canonical
unstored_canonical_fields = UNSTORED_CANONICAL_FIELDS.get(nameop['opcode'])
assert unstored_canonical_fields is not None, "BUG: no UNSTORED_CANONICAL_FIELDS entry for {}".format(nameop['opcode'])
for f in unstored_canonical_fields:
if f in nameop:
del nameop[f]
return rc | python | def op_check( state_engine, nameop, block_id, checked_ops ):
"""
Given the state engine, the current block, the list of pending
operations processed so far, and the current operation, determine
whether or not it should be accepted.
The operation is allowed to be "type-cast" to a new operation, but only once.
If this happens, the operation will be checked again.
Subsequent casts are considered bugs, and will cause a program abort.
TODO: remove type-cast
"""
global CHECK_METHODS, MUTATE_FIELDS
nameop_clone = copy.deepcopy( nameop )
opcode = None
if 'opcode' not in nameop_clone.keys():
op = nameop_clone.get('op', None)
try:
assert op is not None, "BUG: no op defined"
opcode = op_get_opcode_name( op )
assert opcode is not None, "BUG: op '%s' undefined" % op
except Exception, e:
log.exception(e)
log.error("FATAL: BUG: no 'op' defined")
sys.exit(1)
else:
opcode = nameop_clone['opcode']
check_method = CHECK_METHODS.get( opcode, None )
try:
assert check_method is not None, "BUG: no check-method for '%s'" % opcode
except Exception, e:
log.exception(e)
log.error("FATAL: BUG: no check-method for '%s'" % opcode )
sys.exit(1)
rc = check_method( state_engine, nameop_clone, block_id, checked_ops )
if not rc:
# rejected
return False
# accepted! clean up and canonicalize
nameop.clear()
nameop.update(nameop_clone)
# nameop = op_canonicalize(nameop['opcode'], nameop)
op_canonicalize(nameop['opcode'], nameop)
# make sure we don't send unstored fields to the db that are otherwise canonical
unstored_canonical_fields = UNSTORED_CANONICAL_FIELDS.get(nameop['opcode'])
assert unstored_canonical_fields is not None, "BUG: no UNSTORED_CANONICAL_FIELDS entry for {}".format(nameop['opcode'])
for f in unstored_canonical_fields:
if f in nameop:
del nameop[f]
return rc | [
"def",
"op_check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"global",
"CHECK_METHODS",
",",
"MUTATE_FIELDS",
"nameop_clone",
"=",
"copy",
".",
"deepcopy",
"(",
"nameop",
")",
"opcode",
"=",
"None",
"if",
"'opcode'",
... | Given the state engine, the current block, the list of pending
operations processed so far, and the current operation, determine
whether or not it should be accepted.
The operation is allowed to be "type-cast" to a new operation, but only once.
If this happens, the operation will be checked again.
Subsequent casts are considered bugs, and will cause a program abort.
TODO: remove type-cast | [
"Given",
"the",
"state",
"engine",
"the",
"current",
"block",
"the",
"list",
"of",
"pending",
"operations",
"processed",
"so",
"far",
"and",
"the",
"current",
"operation",
"determine",
"whether",
"or",
"not",
"it",
"should",
"be",
"accepted",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L284-L343 | train | 225,552 |
blockstack/blockstack-core | blockstack/lib/operations/__init__.py | op_get_mutate_fields | def op_get_mutate_fields( op_name ):
"""
Get the names of the fields that will change
when this operation gets applied to a record.
"""
global MUTATE_FIELDS
if op_name not in MUTATE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name)
fields = MUTATE_FIELDS[op_name][:]
return fields | python | def op_get_mutate_fields( op_name ):
"""
Get the names of the fields that will change
when this operation gets applied to a record.
"""
global MUTATE_FIELDS
if op_name not in MUTATE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name)
fields = MUTATE_FIELDS[op_name][:]
return fields | [
"def",
"op_get_mutate_fields",
"(",
"op_name",
")",
":",
"global",
"MUTATE_FIELDS",
"if",
"op_name",
"not",
"in",
"MUTATE_FIELDS",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"No such operation '%s'\"",
"%",
"op_name",
")",
"fields",
"=",
"MUTATE_FI... | Get the names of the fields that will change
when this operation gets applied to a record. | [
"Get",
"the",
"names",
"of",
"the",
"fields",
"that",
"will",
"change",
"when",
"this",
"operation",
"gets",
"applied",
"to",
"a",
"record",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L346-L357 | train | 225,553 |
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",
"=",
"... | 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 | train | 225,554 |
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 lega... | 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 | train | 225,555 |
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 gene... | 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 | train | 225,556 |
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",
... | 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 | train | 225,557 |
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",
"... | 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 | train | 225,558 |
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",
"jsoni... | 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 | train | 225,559 |
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'",
"... | 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 | train | 225,560 |
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_i... | 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 | train | 225,561 |
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",
"[",
"... | 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 | train | 225,562 |
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",
"=",... | 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 | train | 225,563 |
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'",
",",
"(",
... | 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 | train | 225,564 |
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",
"(",
")",
"val... | 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 | train | 225,565 |
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",... | 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 | train | 225,566 |
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",
"}",
",",
"... | 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",
... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L674-L689 | train | 225,567 |
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 | train | 225,568 |
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",
... | 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 | train | 225,569 |
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",
"... | 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 | train | 225,570 |
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",
"(... | 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 | train | 225,571 |
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",
"("... | 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 | train | 225,572 |
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",
")",
... | 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 | train | 225,573 |
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... | 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 | train | 225,574 |
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",
":",... | 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 | train | 225,575 |
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",
"a... | 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 | train | 225,576 |
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",
... | 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 | train | 225,577 |
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",
"(",
")",
",",
"\"B... | 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 | train | 225,578 |
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",
")",
... | 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 | train | 225,579 |
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",
"=",
"n... | 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 | train | 225,580 |
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",
"(... | 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 | train | 225,581 |
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",
",",
")",
"... | 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 | train | 225,582 |
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",
"(",
"... | 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 | train | 225,583 |
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 th... | 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 | train | 225,584 |
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 e... | 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",
".",
"... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2174-L2194 | train | 225,585 |
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",
... | 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",
"o... | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2197-L2211 | train | 225,586 |
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_... | 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 | train | 225,587 |
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",
... | 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 | train | 225,588 |
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",
"unexpir... | 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 | train | 225,589 |
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_exp... | 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 | train | 225,590 |
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 ... | 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 | train | 225,591 |
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",
... | 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 | train | 225,592 |
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",
")"... | 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 | train | 225,593 |
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",
",",
"c... | 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 | train | 225,594 |
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",
"... | 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 | train | 225,595 |
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",... | 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 | train | 225,596 |
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 na... | 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 | train | 225,597 |
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",
... | 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 | train | 225,598 |
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",
",",
"sele... | 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 | train | 225,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.