INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Static method for determining the last-known resolver for a domain name. Returns the resolver URL on success Returns None on error
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("Su...
Static method for getting count of all subdomains Return number of subdomains on success
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 ...
Get a subdomain's DID info. Return None if not found
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: ...
Static method for resolving a DID to a subdomain Return the subdomain record on success Return None on error
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): ...
Static method for getting all historic zone file hashes for a subdomain
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['su...
Static method for getting all historic operations on a subdomain
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: ...
Static method for getting the list of 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['subdo...
Static method for getting the list of subdomain operations accepted at a given txid. Includes unaccepted subdomain operations
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 ...
Static method for getting the list of subdomains for a given 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...
Static method for getting the last sequence number in the database
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...
Make a signed subdomain TXT record, to be appended to a (domain's) zone file. Return the TXT record string
def make_subdomain_txt(name_or_fqn, domain, address, n, zonefile_str, privkey_bundle): """ Make a signed subdomain TXT record, to be appended to a (domain's) zone file. Return the TXT record string """ subrec = Subdomain(str(name_or_fqn), str(domain), str(address), int(n), str(zonefile_str), None, N...
Sign a subdomain plaintext with a private key bundle Returns the base64-encoded scriptsig
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): ret...
Sign a subdomain record's plaintext with a private key. Return a bitcoin-compatible scriptSig, base64-encoded, that encodes the [signature, public-key] data
def sign_singlesig(privkey_hex, plaintext): """ Sign a subdomain record's plaintext with a private key. Return a bitcoin-compatible scriptSig, base64-encoded, that encodes the [signature, public-key] data """ hash_hex = hashlib.sha256(plaintext).hexdigest() b64sig = virtualchain.ecdsalib.sign_di...
Sign a subdomain record's plaintext with a multisig key bundle. This returns a bitcoin-compatible multisig scriptSig, base64-encoded, that encodes the [OP_0, m, [signatures], [public_keys], n, OP_CHECKMULTISIG] script
def sign_multisig(privkey_bundle, plaintext): """ Sign a subdomain record's plaintext with a multisig key bundle. This returns a bitcoin-compatible multisig scriptSig, base64-encoded, that encodes the [OP_0, m, [signatures], [public_keys], n, OP_CHECKMULTISIG] script """ hash_hex = hashlib.sha256(pl...
Set up subdomain state Returns a SubdomainIndex object that has been successfully connected to Atlas
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['subdo...
Pack all of the data for this subdomain into a list of strings. The list of strings will be given in the order in which they should be signed. That is: NAME, ADDR, N, NUM_ZF_PARTS ZF_PARTS, IN_ORDER_PIECES, (? SIG)
def pack_subdomain(self): """ Pack all of the data for this subdomain into a list of strings. The list of strings will be given in the order in which they should be signed. That is: NAME, ADDR, N, NUM_ZF_PARTS ZF_PARTS, IN_ORDER_PIECES, (? SIG) """ output = [] # ...
Given an address, verify whether or not it was signed by it
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)
Get back the plaintext that will be signed. It is derived from the serialized zone file strings, but encoded as a single string (omitting the signature field, if already given)
def get_plaintext_to_sign(self): """ Get back the plaintext that will be signed. It is derived from the serialized zone file strings, but encoded as a single string (omitting the signature field, if already given) """ as_strings = self.pack_subdomain() if ...
Serialize this subdomain record to a TXT record. The trailing newline will be omitted
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_zon...
Serialize to JSON, which can be returned e.g. via RPC
def to_json(self): """ Serialize to JSON, which can be returned e.g. via RPC """ ret = { 'address': self.address, 'domain': self.domain, 'block_number': self.block_height, 'sequence': self.n, 'txid': self.txid, 'valu...
Parse a missing-zonefiles vector given by the domain. Returns the list of zone file indexes on success Raises ParseError on unparseable records
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): ...
Parse a subdomain record, and verify its signature. @domain_name: the stem name @rec: the parsed zone file, with 'txt' records Returns a Subdomain object on success Raises an exception on parse error
def parse_subdomain_record(domain_name, rec, block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing, resolver=None): """ Parse a subdomain record, and verify its signature. @domain_name: the stem name @rec: the parsed zone file, with 't...
Parse the scriptSig and extract the public key. Raises ValueError if this is a multisig-controlled subdomain.
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'] != 'singl...
Analyze the public key information we have in our scriptSig. Returns {'status': true, 'type': 'singlesig' | 'multisig', 'public_keys': [...], 'num_sigs': ...} on success Returns {'error': ...} on error
def get_public_key_info(self): """ Analyze the public key information we have in our scriptSig. Returns {'status': true, 'type': 'singlesig' | 'multisig', 'public_keys': [...], 'num_sigs': ...} on success Returns {'error': ...} on error """ script_parts = virtualchain.btc...
Close the index
def close(self): """ Close the index """ with self.subdomain_db_lock: self.subdomain_db.close() self.subdomain_db = None self.subdomain_db_path = None
Given an existing subdomain record and a (newly-discovered) new subdomain record, determine if we can use the new subdomain record (i.e. is its signature valid? is it in the right sequence?) Return True if so Return False if not
def check_subdomain_transition(cls, existing_subrec, new_subrec): """ Given an existing subdomain record and a (newly-discovered) new subdomain record, determine if we can use the new subdomain record (i.e. is its signature valid? is it in the right sequence?) Return True if so R...
Verify that a first-ever subdomain record is well-formed. * n must be 0 * the subdomain must not be independent of its domain
def check_initial_subdomain(cls, subdomain_rec): """ Verify that a first-ever subdomain record is well-formed. * n must be 0 * the subdomain must not be independent of its domain """ if subdomain_rec.n != 0: return False if subdomain_rec.indepe...
Find the sequence of subdomain operations over a block range (block_end is excluded). Does not check for validity or signature matches; only that they are well-formed. Optionally only finds zone file updates for a specific name Returns { 'zonefile_info': [{'name':.., 'zonefile_hash...
def find_zonefile_subdomains(self, block_start, block_end, name=None): """ Find the sequence of subdomain operations over a block range (block_end is excluded). Does not check for validity or signature matches; only that they are well-formed. Optionally only finds zone file updates for ...
Recalculate the history for this subdomain from genesis up until this record. Returns the list of subdomain records we need to save.
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 ...
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.
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...
Given a subdomain record, get its neighbors. I.e. get all of the subdomain records with the previous sequence number, and get all of the subdomain records with the next sequence number Returns {'prev': [...blockchain order...], 'cur': [...blockchain order...], 'fut': [...blockchain order...]}
def get_subdomain_history_neighbors(self, cursor, subdomain_rec): """ Given a subdomain record, get its neighbors. I.e. get all of the subdomain records with the previous sequence number, and get all of the subdomain records with the next sequence number Returns {'prev': [...bloc...
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 subd...
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 c...
Takes the output of find_zonefile_subdomains, and processes the sequence of subdomain operations. Does state-transitions in a big step: * loads the current subdomain state for each subdomain affected in @zonefile_subdomain_info * computes and executes all valid subdomain creations and subdomain ...
def process_subdomains(self, zonefile_subdomain_info): """ Takes the output of find_zonefile_subdomains, and processes the sequence of subdomain operations. Does state-transitions in a big step: * loads the current subdomain state for each subdomain affected in @zonefile_subdomain_info ...
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_zon...
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. ...
Go through the sequence of zone files discovered in a block range, and reindex the names' subdomains.
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 = ...
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.
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_zf...
Entry point for indexing: * scan the blockchain from start_block to end_block and make sure we're up-to-date * process any newly-arrived zone files and re-index the affected subdomains
def index(self, block_start, block_end): """ Entry point for indexing: * scan the blockchain from start_block to end_block and make sure we're up-to-date * process any newly-arrived zone files and re-index the affected subdomains """ log.debug("BEGIN Processing zonefiles ...
Generate a subdomains db from scratch, using the names db and the atlas db and zone file collection. Best to do this in a one-off command (i.e. *not* in the blockstackd process)
def reindex(cls, lastblock, firstblock=None, opts=None): """ Generate a subdomains db from scratch, using the names db and the atlas db and zone file collection. Best to do this in a one-off command (i.e. *not* in the blockstackd process) """ if opts is None: opts = g...
Dict row factory for subdomains
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
Extract a single subdomain from a DB cursor Raise SubdomainNotFound if there are no valid rows
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']) enco...
Fetch subdomain names
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 {} {};".f...
Get and all subdomain names, optionally over a range
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 No...
Given a fully-qualified subdomain, get its (latest) subdomain record. Raises SubdomainNotFound if there is no such subdomain
def get_subdomain_entry(self, fqn, accepted=True, cur=None): """ Given a fully-qualified subdomain, get its (latest) subdomain record. Raises SubdomainNotFound if there is no such subdomain """ get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DES...
Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence. Raises SubdomainNotFound if there is no such subdomain
def get_subdomain_entry_at_sequence(self, fqn, sequence, include_unaccepted=False, cur=None): """ Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence. Raises SubdomainNotFound if there is no such subdomain """ get_cmd = "SEL...
Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence. Raises SubdomainNotFound if there is no such subdomain
def get_subdomain_entry_at_zonefile_index(self, fqn, zonefile_index, cur=None): """ Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence. Raises SubdomainNotFound if there is no such subdomain """ get_cmd = "SELECT * FROM {} ...
Given a txid, get all subdomain operations at that txid. Include unaccepted operations. Order by zone file index
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) ...
Get the list of subdomain names that are owned by a given 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.subdoma...
Get the last-knwon resolver entry for a domain name Returns None if not found.
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 LIMI...
Get the DID information for a subdomain. Raise SubdomainNotFound if there is no such subdomain Return {'name_type': ..., 'address': ..., 'index': ...}
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) ...
Get a subdomain, given its DID Raise ValueError if the DID is invalid Raise SubdomainNotFound if the DID does not correspond to a 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) a...
Does this zone file hash belong to this subdomain?
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_...
Get the subdomain's history over a block range. By default, only include accepted history items (but set include_unaccepted=True to get them all) No zone files will be loaded. Returns the list of subdomains in order by sequnce number, and then by parent zonefile index
def get_subdomain_history(self, fqn, start_sequence=None, end_sequence=None, start_zonefile_index=None, end_zonefile_index=None, include_unaccepted=False, offset=None, count=None, cur=None): """ Get the subdomain's history over a block range. By default, only include accepted history items (but ...
Update the subdomain history table for this subdomain entry. Creates it if it doesn't exist. Return True on success Raise exception on error
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...
Determine whether or not a subdomain record's domain is missing zone files (besides the ones we expect) that could invalidate its history.
def subdomain_check_pending(self, subrec, atlasdb_path, cur=None): """ Determine whether or not a subdomain record's domain is missing zone files (besides the ones we expect) that could invalidate its history. """ _, _, domain = is_address_subdomain(subrec.get_fqn()) sql ...
Get the highest block last processed
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 ro...
Get the highest sequence number in this db
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: ...
Clear the subdomain db's 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), ())
Set up the subdomain db's tables
def _create_tables(self): """ Set up the subdomain db's tables """ cursor = self.conn.cursor() create_cmd = """CREATE TABLE IF NOT EXISTS {} ( fully_qualified_subdomain TEXT NOT NULL, domain TEXT NOT NULL, sequence INTEGER NOT NULL, owner TEXT NOT...
Generate the hash over a name and hex-string script pubkey
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_has...
takes profile data from file and saves in the profile_data DB
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: ...
takes people names from blockchain and writes deduped names in a 'cache'
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...
Extract an operation from transaction data. Return the extracted fields as a dict.
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_na...
Get the canonical representation of a parsed operation's data. Meant for backwards-compatibility
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: r...
Get the current representation of a parsed operation's data, given the canonical representation Meant for backwards-compatibility
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 ...
This method preserves backwards-compatibility quirks on canonicalized op data, for snapshotting purposes. It gets called after the nameop is committed and its history is saved, but before it gets snapshotted to form the new consensus hash. Backwards-compatibility quirks: * if the operation was cr...
def op_canonicalize_quirks(op_name, new_record, current_record): """ This method preserves backwards-compatibility quirks on canonicalized op data, for snapshotting purposes. It gets called after the nameop is committed and its history is saved, but before it gets snapshotted to form the new consensus...
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. ...
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 ...
Get the names of the fields that will change when this operation gets applied to a record.
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][:...
Get the set of consensus-generating fields for an operation.
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 fiel...
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.
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 Retu...
Parse a payload to get back the name and update hash. NOTE: bin_payload excludes the leading three bytes.
def parse(bin_payload): """ Parse a payload to get back the name and update hash. NOTE: bin_payload excludes the leading three bytes. """ if len(bin_payload) != LENGTHS['name_consensus_hash'] + LENGTHS['value_hash']: log.error("Invalid update length %s" % len(bin_payload)) retur...
Verify that a token transfer operation is permitted. * the token feature must exist * the sender must be unlocked---i.e. able to send at this point * the sender must have enough balance of the given token to send the amount requested * the token value must be positive * the consensus hash must be va...
def check( state_engine, token_op, block_id, checked_ops ): """ Verify that a token transfer operation is permitted. * the token feature must exist * the sender must be unlocked---i.e. able to send at this point * the sender must have enough balance of the given token to send the amount requested ...
Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. structure: inputs | outputs ------------------------------------------------------------------------------ sender scriptsig + scriptPubkey | OP...
def tx_extract(payload, senders, inputs, outputs, block_id, vtxindex, txid): """ Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. structure: inputs | outputs ------------------------------------...
Parse a token transfer NOTE: bin_payload *excludes* the leading 3 bytes (magic + op) returned by build. Record format: 0 2 3 19 38 46 80 |-----|--|--------------|----------|-----------|-------------------------| magic op consensus_hash ...
def parse(bin_payload, block_height): """ Parse a token transfer NOTE: bin_payload *excludes* the leading 3 bytes (magic + op) returned by build. Record format: 0 2 3 19 38 46 80 |-----|--|--------------|----------|-----------|------...
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
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 ...
Get proofs for a profile and: a) check cached entries b) check which version of profile we're using
def fetch_proofs(profile, username, address, profile_ver=2, zonefile = None): """ Get proofs for a profile and: a) check cached entries b) check which version of profile we're using """ if 'account' not in profile: return [] # fix up missing proofUrls for account in profile[...
Is a given profile JSON object 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:...
Process profile data and 1) Insert verifications 2) Check if profile data is valid JSON
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_fil...
Given a fully-qualified username (username.namespace) get the data associated with that fqu. Return cached entries, if possible.
def get_profile(fqa): """ Given a fully-qualified username (username.namespace) get the data associated with that fqu. Return cached entries, if possible. """ profile_expired_grace = False fqa = fqa.lower() try: try: res = blockstack.lib.client.resolve_profile(...
Fetch data from username in .id namespace
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...
This is meant for NAME_IMPORT operations, which have five outputs: the OP_RETURN, the sender (i.e. the namespace owner), the name's recipient, the name's update hash, and the burn output. This method extracts the name update hash from the list of outputs. By construction, the update hash ...
def get_import_update_hash_from_outputs( outputs ): """ This is meant for NAME_IMPORT operations, which have five outputs: the OP_RETURN, the sender (i.e. the namespace owner), the name's recipient, the name's update hash, and the burn output. This method extracts the name update hash from ...
Does nameop1 come before bock_id and vtxindex?
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)
Given a NAME_IMPORT nameop, see if we can import it. * the name must be well-formed * the namespace must be revealed, but not ready * the name cannot have been imported yet * the sender must be the same as the namespace's sender Set the __preorder__ and __prior_history__ fields, since this is a...
def check( state_engine, nameop, block_id, checked_ops ): """ Given a NAME_IMPORT nameop, see if we can import it. * the name must be well-formed * the namespace must be revealed, but not ready * the name cannot have been imported yet * the sender must be the same as the namespace's sender ...
Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. Required (+ parse) sender: the script_pubkey (as a hex string) of the principal that sent the name import transaction address: the address from the sender script recipient: the ...
def tx_extract( payload, senders, inputs, outputs, block_id, vtxindex, txid ): """ Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. Required (+ parse) sender: the script_pubkey (as a hex string) of the principal that sent the na...
# NOTE: first three bytes were stripped
def parse(bin_payload, recipient, update_hash ): """ # NOTE: first three bytes were stripped """ fqn = bin_payload if not is_name_valid( fqn ): log.warning("Name '%s' is invalid" % fqn) return None return { 'opcode': 'NAME_IMPORT', 'name': fqn, 're...
Verify the validity of a namespace reveal. Return True if valid Raise an Exception if not valid.
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 ...
Check a NAMESPACE_REVEAL operation to the name database. It is only valid if it is the first such operation for this namespace, and if it was sent by the same sender who sent the NAMESPACE_PREORDER. Return True if accepted Return False if not
def check( state_engine, nameop, block_id, checked_ops ): """ Check a NAMESPACE_REVEAL operation to the name database. It is only valid if it is the first such operation for this namespace, and if it was sent by the same sender who sent the NAMESPACE_PREORDER. Return True if accepted Return...
NOTE: the first three bytes will be missing
def parse( bin_payload, sender_script, recipient_address ): """ NOTE: the first three bytes will be missing """ if len(bin_payload) < MIN_OP_LENGTHS['namespace_reveal']: raise AssertionError("Payload is too short to be a namespace reveal") off = 0 life = None coeff = None base = N...
Fetch all names in a namespace that should be indexed. Data is saved in data/ directory
def fetch_namespace(): """ Fetch all names in a namespace that should be indexed. Data is saved in data/ directory """ resp = blockstack.lib.client.get_all_names(hostport=blockstack_indexer_url) subdomain_names = blockstack.lib.subdomains.get_all_subdomains() all_names = list(resp) ...
Fetch profile data using Blockstack Core and save the data. Data is saved in: data/profile_data.json Format of the data is <fqu, profile> * fqu: fully-qualified name * profile: json profile data
def fetch_profiles(max_to_fetch = None, just_test_set = False): """ Fetch profile data using Blockstack Core and save the data. Data is saved in: data/profile_data.json Format of the data is <fqu, profile> * fqu: fully-qualified name * profile: json profile data """ ...
Revoke a name--make it available for registration. * it must be well-formed * its namespace must be ready. * the name must be registered * it must be sent by the name owner NAME_REVOKE isn't allowed during an import, so the name's namespace must be ready. Return True if accepted Return Fal...
def check( state_engine, nameop, block_id, checked_ops ): """ Revoke a name--make it available for registration. * it must be well-formed * its namespace must be ready. * the name must be registered * it must be sent by the name owner NAME_REVOKE isn't allowed during an import, so the name'...
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 ...
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 registra...
Given the set of outputs, find the fee sent to our burn address. This is always the third output. Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...} Return None if not found
def get_preorder_burn_info( outputs ): """ Given the set of outputs, find the fee sent to our burn address. This is always the third output. Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...} Return None if not found """ if len(outputs) != 3: ...
Parse a name preorder. NOTE: bin_payload *excludes* the leading 3 bytes (magic + op) returned by build. Record format: 0 2 3 23 39 |-----|--|----------------------------------------------|--------------| magic op hash(name.ns_id,sc...
def parse(bin_payload, block_height): """ Parse a name preorder. NOTE: bin_payload *excludes* the leading 3 bytes (magic + op) returned by build. Record format: 0 2 3 23 39 |-----|--|---------------------------------------------...
>>> c32encode('a46ff88886c2ef9762d970b4d2c63678835bd39d') 'MHQZH246RBQSERPSE2TD5HHPF21NQMWX' >>> c32encode('') '' >>> c32encode('0000000000000000000000000000000000000000', 20) '00000000000000000000' >>> c32encode('0000000000000000000000000000000000000001', 20) '00000000000000000001' >>> ...
def c32encode(input_hex, min_length=None): """ >>> c32encode('a46ff88886c2ef9762d970b4d2c63678835bd39d') 'MHQZH246RBQSERPSE2TD5HHPF21NQMWX' >>> c32encode('') '' >>> c32encode('0000000000000000000000000000000000000000', 20) '00000000000000000000' >>> c32encode('000000000000000000000000000...
>>> c32decode('MHQZH246RBQSERPSE2TD5HHPF21NQMWX') 'a46ff88886c2ef9762d970b4d2c63678835bd39d' >>> c32decode('') '' >>> c32decode('00000000000000000000', 20) '0000000000000000000000000000000000000000' >>> c32decode('00000000000000000001', 20) '0000000000000000000000000000000000000001' >>> ...
def c32decode(c32input, min_length=0): """ >>> c32decode('MHQZH246RBQSERPSE2TD5HHPF21NQMWX') 'a46ff88886c2ef9762d970b4d2c63678835bd39d' >>> c32decode('') '' >>> c32decode('00000000000000000000', 20) '0000000000000000000000000000000000000000' >>> c32decode('00000000000000000001', 20) ...
>>> c32checkEncode(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> c32checkEncode(0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') '02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE' >>> c32checkEncode(31, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'Z2J6ZY48GV1EZ...
def c32checkEncode(version, data): """ >>> c32checkEncode(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> c32checkEncode(0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') '02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE' >>> c32checkEncode(31, 'a46ff88886c2ef...
>>> c32checkDecode('P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7') (22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') >>> c32checkDecode('02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE') (0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') >>> c32checkDecode('Z2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR') (31, 'a46ff888...
def c32checkDecode(c32data): """ >>> c32checkDecode('P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7') (22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') >>> c32checkDecode('02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE') (0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') >>> c32checkDecode('Z2J6ZY48GV1EZ5V2V5RB...
>>> c32address(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> c32address(0, '0000000000000000000000000000000000000000') 'S0000000000000000000002AA028H' >>> c32address(31, '0000000000000000000000000000000000000001') 'SZ00000000000000000005HZ3DVN' >...
def c32address(version, hash160hex): """ >>> c32address(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> c32address(0, '0000000000000000000000000000000000000000') 'S0000000000000000000002AA028H' >>> c32address(31, '0000000000000000000000000000000000...
>>> b58ToC32('1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> b58ToC32('3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y') 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G' >>> b58ToC32('mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8') 'ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ' >>> b58ToC3...
def b58ToC32(b58check, version=-1): """ >>> b58ToC32('1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> b58ToC32('3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y') 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G' >>> b58ToC32('mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8') 'ST2J6ZY48G...
>>> c32ToB58('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7') '1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d' >>> c32ToB58('SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G') '3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y' >>> c32ToB58('ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ') 'mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8' >>> c32ToB5...
def c32ToB58(c32string, version=-1): """ >>> c32ToB58('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7') '1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d' >>> c32ToB58('SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G') '3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y' >>> c32ToB58('ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ') 'mv...