INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Make a "fake" txid for a genesis block entry.
Returns a 32-byte hash (double-sha256), hex-encoded | def namedb_genesis_txid(address, metadata):
"""
Make a "fake" txid for a genesis block entry.
Returns a 32-byte hash (double-sha256), hex-encoded
"""
preimage = '{} genesis {}'.format(address, metadata)
return virtualchain.lib.hashing.bin_double_sha256(preimage).encode('hex') |
Make a "fake" txid for a vesting transaction.
Returns a 32-byte hash (double-sha256), hex-encoded | def namedb_vesting_txid(address, token_type, token_amount, block_height):
"""
Make a "fake" txid for a vesting transaction.
Returns a 32-byte hash (double-sha256), hex-encoded
"""
preimage = '{} vesting {} {} at {}'.format(address, token_type, token_amount, block_height)
return virtualchain.lib.... |
Make a "fake" txid for the genesis block history
Returns a 32-byte hash (single sha256), hex-encoded
(single sha256 so it can be easily verified against our genesis block tooling) | def namedb_genesis_block_history_hash(genesis_block_history):
"""
Make a "fake" txid for the genesis block history
Returns a 32-byte hash (single sha256), hex-encoded
(single sha256 so it can be easily verified against our genesis block tooling)
"""
# no-whitespace sorted serialization
preim... |
Create the initial account balances.
All accounts will be locked, and will have been created at the genesis date
for Blockstack (i.e. FIRST_BLOCK_MAINNET)
The genesis block has multiple "stages" that encode the transfer of tokens from
Blockstack Token LLC to the various investors, GPs, etc. For the in... | def namedb_create_token_genesis(con, initial_account_balances, genesis_block_history):
"""
Create the initial account balances.
All accounts will be locked, and will have been created at the genesis date
for Blockstack (i.e. FIRST_BLOCK_MAINNET)
The genesis block has multiple "stages" that encode t... |
Get the db version | def namedb_get_version(con):
"""
Get the db version
"""
sql = 'SELECT version FROM db_version;'
args = ()
try:
rowdata = namedb_query_execute(con, sql, args, abort=False)
row = rowdata.fetchone()
return row['version']
except:
# no version defined
retu... |
Get the db version | def namedb_read_version(path):
"""
Get the db version
"""
con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
con.row_factory = namedb_row_factory
sql = 'SELECT version FROM db_version;'
args = ()
try:
rowdata = namedb_query_execute(con, sql, args, abort=False)
... |
Create a sqlite3 db at the given path.
Create all the tables and indexes we need. | 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_S... |
Open a connection to our database | 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(versio... |
Row factor to enforce some additional types:
* force 'revoked' to be a bool | def namedb_row_factory( cursor, row ):
"""
Row factor to enforce some additional types:
* force 'revoked' to be a bool
"""
d = {}
for idx, col in enumerate( cursor.description ):
if col[0] in ['revoked', 'locked', 'receive_whitelisted']:
if row[idx] == 0:
d[co... |
Find the set of fields missing from record, and set of extra fields from record, based on the db schema.
Return (missing, extra) | def namedb_find_missing_and_extra(cur, record, table_name):
"""
Find the set of fields missing from record, and set of extra fields from record, based on the db schema.
Return (missing, extra)
"""
rec_missing = []
rec_extra = []
# sanity check: all fields must be defined
name_fields... |
Ensure that the fields of a given record match
the columns of the given table.
* if record_match_columns, then the keys in record must match all columns.
* if columns_match_record, then the columns must match the keys in the record.
Return True if so.
Raise an exception if not. | def namedb_assert_fields_match( cur, record, table_name, record_matches_columns=True, columns_match_record=True ):
"""
Ensure that the fields of a given record match
the columns of the given table.
* if record_match_columns, then the keys in record must match all columns.
* if columns_match_record, ... |
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. | 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 )
col... |
Prepare to update a record, but make sure that the fields in input_record
correspond to acual columns.
Also, enforce any fields that must be equal to the fields
in the given record (must_equal), and require that certian fields in record
have certain values first (only_if)
Return an UPDATE ... SET .... | def namedb_update_prepare( cur, primary_key_or_keys, input_record, table_name, must_equal=[], only_if={} ):
"""
Prepare to update a record, but make sure that the fields in input_record
correspond to acual columns.
Also, enforce any fields that must be equal to the fields
in the given record (must_e... |
Generate the set of fields that must stay the same across an update. | 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.appen... |
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 | 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
... |
Execute a query. If it fails, abort. Retry with timeouts on lock
DO NOT CALL THIS DIRECTLY. | 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) |
Add a name or namespace preorder record, if it doesn't exist already.
DO NOT CALL THIS DIRECTLY. | 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:
pre... |
Remove a preorder hash.
DO NOT CALL THIS DIRECTLY. | 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 d... |
Make sure that a name record has some fields
that must always be present:
* name
* namespace_id
* name_hash128
Makes the record suitable for insertion/update.
NOTE: MODIFIES name_rec | def namedb_name_fields_check( name_rec ):
"""
Make sure that a name record has some fields
that must always be present:
* name
* namespace_id
* name_hash128
Makes the record suitable for insertion/update.
NOTE: MODIFIES name_rec
"""
if not name_rec.has_key('name'):
rais... |
Add the given name record to the database,
if it doesn't exist already. | 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... |
Update an existing name in the database.
If non-empty, only update the given fields.
DO NOT CALL THIS METHOD DIRECTLY. | 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 )
... |
Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec | def namedb_namespace_fields_check( namespace_rec ):
"""
Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec
"""
assert namespace_rec.has_key('namespace_id'), "BUG: na... |
Add a namespace to the database,
if it doesn't exist already.
It must be a *revealed* namespace, not a ready namespace
(to mark a namespace as ready, you should use the namedb_apply_operation()
method). | def namedb_namespace_insert( cur, input_namespace_rec ):
"""
Add a namespace to the database,
if it doesn't exist already.
It must be a *revealed* namespace, not a ready namespace
(to mark a namespace as ready, you should use the namedb_apply_operation()
method).
"""
namespace_rec = cop... |
Sanity checks over operation and state graph data:
* opcode and op_data must be consistent
* record must have an opcode
* the given opcode must be reachable from it. | def namedb_op_sanity_check( opcode, op_data, record ):
"""
Sanity checks over operation and state graph data:
* opcode and op_data must be consistent
* record must have an opcode
* the given opcode must be reachable from it.
"""
assert 'address' in record, "BUG: current record has no 'addre... |
Sanity checks: make sure that:
* the opcode and op_data are consistent with one another.
* the history_id, cur_record, and record_table are consistent with one another.
Return True if so.
Raise an exception if not.
DO NOT CALL THIS METHOD DIRECTLY. | def namedb_state_transition_sanity_check( opcode, op_data, history_id, cur_record, record_table ):
"""
Sanity checks: make sure that:
* the opcode and op_data are consistent with one another.
* the history_id, cur_record, and record_table are consistent with one another.
Return True if so.
Rais... |
Make sure all mutate fields for this operation are present.
Return True if so
Raise exception if not | 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_... |
Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current
record (history_id, cur_record), apply the operation to the record and save the delta to the record's
history. Also, insert or update the new record into the db.
The cur_record must exist already.
Return t... | def namedb_state_transition( cur, opcode, op_data, block_id, vtxindex, txid, history_id, cur_record, record_table, constraints_ignored=[] ):
"""
Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current
record (history_id, cur_record), apply the operation to the record ... |
Sanity checks on a preorder and a state-creation operation:
* the opcode must match the op_data
* the history_id and operation must match the preorder
* everything must match the record table.
Return True on success
Raise an exception on error.
DO NOT CALL THIS METHOD DIRECTLY. | def namedb_state_create_sanity_check( opcode, op_data, history_id, preorder_record, record_table ):
"""
Sanity checks on a preorder and a state-creation operation:
* the opcode must match the op_data
* the history_id and operation must match the preorder
* everything must match the record table.
... |
Given an operation and a new record (opcode, new_record), a point in time (block_id, vtxindex, txid), and a preorder
record for a known record (history_id, preorder_record), create the initial name or namespace using
the preorder and operation's data. Record the preorder as history.
This operation will al... | def namedb_state_create( cur, opcode, new_record, block_id, vtxindex, txid, history_id, preorder_record, record_table, constraints_ignored=[] ):
"""
Given an operation and a new record (opcode, new_record), a point in time (block_id, vtxindex, txid), and a preorder
record for a known record (history_id, pre... |
Find the last name import for this name | 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... |
Sanity checks on a name-import:
* the opcode must match the op_data
* everything must match the record table.
* if prior_import is None, then the name shouldn't exist
* if prior_import is not None, then it must exist
Return True on success
Raise an exception on error.
DO NOT CALL THIS METH... | def namedb_name_import_sanity_check( cur, opcode, op_data, history_id, block_id, vtxindex, prior_import, record_table):
"""
Sanity checks on a name-import:
* the opcode must match the op_data
* everything must match the record table.
* if prior_import is None, then the name shouldn't exist
* if ... |
Given an operation and a new record (opcode, new_record), and point in time (block_id, vtxindex, txid)
create the initial name as an import. Does not work on namespaces.
Returns the data to snapshot on success (with all compatibility quirks preserved)
Raise an exception on failure.
DO NOT CALL THIS M... | def namedb_state_create_as_import( db, opcode, new_record, block_id, vtxindex, txid, history_id, record_table, constraints_ignored=[] ):
"""
Given an operation and a new record (opcode, new_record), and point in time (block_id, vtxindex, txid)
create the initial name as an import. Does not work on namespac... |
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 Tr... | 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, bu... |
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 | 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 goe... |
Vest tokens at this block to all recipients.
Goes through the vesting table and debits each account that should vest on this block. | 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_quer... |
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. | 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... |
Insert data into the state engine's history.
It must be for a never-before-seen (txid,block_id,vtxindex) set.
@history_id is either the name or namespace ID
Return True on success
Raise an Exception on error | def namedb_history_save( cur, opcode, history_id, creator_address, value_hash, block_id, vtxindex, txid, accepted_rec, history_snapshot=False ):
"""
Insert data into the state engine's history.
It must be for a never-before-seen (txid,block_id,vtxindex) set.
@history_id is either the name or namespace I... |
Get the history for a name or namespace from the history table.
Use offset/count if given. | def namedb_get_history_rows( cur, history_id, offset=None, count=None, reverse=False ):
"""
Get the history for a name or namespace from the history table.
Use offset/count if given.
"""
ret = []
if not reverse:
select_query = "SELECT * FROM history WHERE history_id = ? ORDER BY block_id... |
Get the history for a name or namespace from the history table.
Use offset/count if given. | def namedb_get_num_history_rows( cur, history_id ):
"""
Get the history for a name or namespace from the history table.
Use offset/count if given.
"""
ret = []
select_query = "SELECT COUNT(*) FROM history WHERE history_id = ? ORDER BY block_id ASC, vtxindex ASC;"
args = (history_id,)
co... |
Get all of the history for a name or namespace.
Returns a dict keyed by block heights, paired to lists of changes (see namedb_history_extract) | def namedb_get_history( cur, history_id, offset=None, count=None, reverse=False ):
"""
Get all of the history for a name or namespace.
Returns a dict keyed by block heights, paired to lists of changes (see namedb_history_extract)
"""
# get history in increasing order by block_id and then vtxindex
... |
Given the rows of history for a name, collapse
them into a history dictionary.
Return a dict of:
{
block_id: [
{ ... historical copy ...
txid:
vtxindex:
op:
opcode:
}, ...
],
...
} | def namedb_history_extract( history_rows ):
"""
Given the rows of history for a name, collapse
them into a history dictionary.
Return a dict of:
{
block_id: [
{ ... historical copy ...
txid:
vtxindex:
op:
opcode:
},... |
Given a name's history, flatten it into a list of deltas.
They will be in *increasing* order. | def namedb_flatten_history( hist ):
"""
Given a name's history, flatten it into a list of deltas.
They will be in *increasing* order.
"""
ret = []
block_ids = sorted(hist.keys())
for block_id in block_ids:
vtxinfos = hist[block_id]
for vtxinfo in vtxinfos:
info = ... |
Get an account's tokens
Returns the list of tokens on success
Returns None if not found | 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 r... |
Get an account, given the address.
Returns the account row on success
Returns None if not found | 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)
... |
Get the account state for a token type at the given (block_id,vtxindex), plus the account state for
the same token type at the prior operation.
The current account must have been debited or credited at (block_id,vtxindex)
Returns {'current': ..., 'prior': ...} on success
Returns None on error | def namedb_get_account_delta(cur, address, token_type, block_id, vtxindex):
"""
Get the account state for a token type at the given (block_id,vtxindex), plus the account state for
the same token type at the prior operation.
The current account must have been debited or credited at (block_id,vtxindex)
... |
Figure out what the expenditure difference is between two accounts.
They must be for the same token type and address.
Calculates current - prior | 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 Value... |
Get the history of an account's tokens | 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,)... |
TESTING ONLY
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 r... |
Get a namespace (revealed or ready) and optionally its history.
Only return an expired namespace if asked.
If current_block is None, any namespace is returned (expired or not)
If current_block is not None and only_revealed is False, then a namespace can be returned before it was revealed.
-- if include_... | def namedb_get_namespace( cur, namespace_id, current_block, include_expired=False, include_history=True, only_revealed=True):
"""
Get a namespace (revealed or ready) and optionally its history.
Only return an expired namespace if asked.
If current_block is None, any namespace is returned (expired or not... |
Get a namespace by its preorder hash (regardless of whether or not it was expired.) | def namedb_get_namespace_by_preorder_hash( cur, preorder_hash, include_history=True ):
"""
Get a namespace by its preorder hash (regardless of whether or not it was expired.)
"""
select_query = "SELECT * FROM namespaces WHERE preorder_hash = ?;"
namespace_rows = namedb_query_execute( cur, select_qu... |
Get a name by its preorder hash (regardless of whether or not it was expired or revoked.) | def namedb_get_name_by_preorder_hash( cur, preorder_hash, include_history=True ):
"""
Get a name by its preorder hash (regardless of whether or not it was expired or revoked.)
"""
select_query = "SELECT * FROM name_records WHERE preorder_hash = ?;"
name_rows = namedb_query_execute( cur, select_quer... |
Generate part of a WHERE clause that selects from name records joined with namespaces
(or projections of them) that are not expired.
Also limit to names that are registered at this block, if only_registered=True.
If only_registered is False, then as long as current_block is before the expire block, then th... | def namedb_select_where_unexpired_names(current_block, only_registered=True):
"""
Generate part of a WHERE clause that selects from name records joined with namespaces
(or projections of them) that are not expired.
Also limit to names that are registered at this block, if only_registered=True.
If o... |
Get a name and all of its history. Note: will return a revoked name
Return the name + history on success
Return None if the name doesn't exist, or is expired (NOTE: will return a revoked name) | def namedb_get_name(cur, name, current_block, include_expired=False, include_history=True, only_registered=True):
"""
Get a name and all of its history. Note: will return a revoked name
Return the name + history on success
Return None if the name doesn't exist, or is expired (NOTE: will return a revoke... |
Given a name and a DB cursor, find out its DID info at the given block.
Returns {'name_type': ..., 'address': ..., 'index': ...} on success
Return None if there is no such name | def namedb_get_name_DID_info(cur, name, block_height):
"""
Given a name and a DB cursor, find out its DID info at the given block.
Returns {'name_type': ..., 'address': ..., 'index': ...} on success
Return None if there is no such name
"""
# get the latest creator addresses for this name, as wel... |
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed at this block, then this method returns all states the record passed through.... | def namedb_get_record_states_at(cur, history_id, block_number):
"""
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed a... |
Get the state(s) that a given account was in at a given block height
Normally this is one state if nothing happened in this block.
Otherwise, this is one or more states.
Returns an array of states | def namedb_get_account_at(cur, address, block_number):
"""
Get the state(s) that a given account was in at a given block height
Normally this is one state if nothing happened in this block.
Otherwise, this is one or more states.
Returns an array of states
"""
query = 'SELECT * FROM accounts... |
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. | 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... |
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 | 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 r... |
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. | 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 do... |
Get a preorder record by hash.
If include_expired is set, then so must expiry_time
Return None if not found. | 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:
... |
Get the list of non-expired, non-revoked names owned by an address.
Only works if there is a *singular* address for the name. | def namedb_get_names_owned_by_address( cur, address, current_block ):
"""
Get the list of non-expired, non-revoked names owned by an address.
Only works if there is a *singular* address for the name.
"""
unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block )
... |
Get the number of names owned by an address throughout history | 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 = ?;"
... |
Get the list of all names ever owned by this address (except the current one), ordered by creation date.
Return a list of {'name': ..., 'block_id': ..., 'vtxindex': ...}} | def namedb_get_historic_names_by_address( cur, address, offset=None, count=None ):
"""
Get the list of all names ever owned by this address (except the current one), ordered by creation date.
Return a list of {'name': ..., 'block_id': ..., 'vtxindex': ...}}
"""
query = "SELECT name_records.name,his... |
Make an offset/count predicate
even if offset=None or count=None.
Return (query, args) | def namedb_offset_count_predicate( offset=None, count=None ):
"""
Make an offset/count predicate
even if offset=None or count=None.
Return (query, args)
"""
offset_count_query = ""
offset_count_args = ()
if count is not None:
offset_count_query += "LIMIT ? "
offset_coun... |
Execute a SELECT COUNT(*) ... query
and return the number of rows. | def namedb_select_count_rows( cur, query, args, count_column='COUNT(*)' ):
"""
Execute a SELECT COUNT(*) ... query
and return the number of rows.
"""
count_rows = namedb_query_execute( cur, query, args )
count = 0
for r in count_rows:
count = r[count_column]
break
return... |
Get the states that each name, namespace, and account record
passed through in the given block. Note that this only concerns
operations written on-chain, for use in SNV and database verification
(i.e. does not include implicit account debits and account vesting).
Return the list of prior record states... | def namedb_get_all_blockstack_ops_at(db, block_id, offset=None, count=None):
"""
Get the states that each name, namespace, and account record
passed through in the given block. Note that this only concerns
operations written on-chain, for use in SNV and database verification
(i.e. does not include ... |
Get the number of name/namespace/token operations that occurred at a particular block. | def namedb_get_num_blockstack_ops_at( db, block_id ):
"""
Get the number of name/namespace/token operations that occurred at a particular block.
"""
cur = db.cursor()
# preorders at this block
preorder_count_rows_query = "SELECT COUNT(*) FROM preorders WHERE block_number = ?;"
preorder_coun... |
Get the number of names that exist at the current block | 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 = nam... |
Get a list of all names in the database, optionally
paginated with offset and count. Exclude expired names. Include revoked 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 inclu... |
Get the number of names in a given 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_r... |
Get a list of all names in a namespace, optionally
paginated with offset and count. Exclude expired names | 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 )
... |
Get a list of all READY 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:
... |
Get a list of all preordered namespace hashes that haven't expired yet.
Used for testing | 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... |
Get all non-expired revealed namespaces. | 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_qu... |
Get the list of all non-expired preordered and revealed 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, curr... |
Given a sender pubkey script, find all the non-expired non-revoked names owned by it.
Return None if the sender owns no names. | 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 = "S... |
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found. | def namedb_get_name_preorder( db, preorder_hash, current_block ):
"""
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
"""
select_query = "SEL... |
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. | 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 ... |
Get a namespace reveal, and optionally its history, given its namespace ID.
Only return a namespace record if:
* it is not ready
* it is not expired | def namedb_get_namespace_reveal( cur, namespace_id, current_block, include_history=True ):
"""
Get a namespace reveal, and optionally its history, given its namespace ID.
Only return a namespace record if:
* it is not ready
* it is not expired
"""
select_query = "SELECT * FROM namespaces WH... |
Get a ready namespace, and optionally its history.
Only return a namespace if it is 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, ... |
Given the hexlified 128-bit hash of a name, get the name. | def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ):
"""
Given the hexlified 128-bit hash of a name, get the name.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_re... |
Get the names with the given value hash. Only includes current, non-revoked names.
Return None if there are no names. | def namedb_get_names_with_value_hash( cur, value_hash, block_number ):
"""
Get the names with the given value hash. Only includes current, non-revoked names.
Return None if there are no names.
"""
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_quer... |
Get the list of txs that sent this value hash, ordered by block and vtxindex | def namedb_get_value_hash_txids(cur, value_hash):
"""
Get the list of txs that sent this value hash, ordered by block and vtxindex
"""
query = 'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;'
args = (value_hash,)
rows = namedb_query_execute(cur, query, args)
txids... |
How many virtual transactions were processed for this block? | def namedb_get_num_block_vtxs( cur, block_number ):
"""
How many virtual transactions were processed for this block?
"""
select_query = "SELECT vtxindex FROM history WHERE history_id = ?;"
args = (block_number,)
rows = namedb_query_execute( cur, select_query, args )
count = 0
for r in ... |
Determine if a zone file hash was sent by a name.
Return True if so, false if not | def namedb_is_name_zonefile_hash(cur, name, zonefile_hash):
"""
Determine if a zone file hash was sent by a name.
Return True if so, false if not
"""
select_query = 'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?'
select_args = (name,zonefile_hash)
rows = name... |
If the announcement is valid, then immediately record it. | def process_announcement( sender_namerec, op, working_dir ):
"""
If the announcement is valid, then immediately record it.
"""
node_config = get_blockstack_opts()
# valid announcement
announce_hash = op['message_hash']
announcer_id = op['announcer_id']
# verify that it came from thi... |
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 preorder transaction
address: the address from the sender script
Optional:
... | 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 n... |
Interpret a block's nulldata back into a SHA256. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload. | def parse(bin_payload):
"""
Interpret a block's nulldata back into a SHA256. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
"""
message_hash = hexlify(bin_payload)
if not is_hex( message_hash ):
log.warning("Not a message hash")
return No... |
Log an announcement from the blockstack developers,
but first verify that it is correct.
Return True if the announcement came from the announce IDs whitelist
Return False otherwise | def check( state_engine, nameop, block_id, checked_ops ):
"""
Log an announcement from the blockstack developers,
but first verify that it is correct.
Return True if the announcement came from the announce IDs whitelist
Return False otherwise
"""
sender = nameop['sender']
sending_blockc... |
Connect to the bitcoind node | def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_pass... |
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, txdata) on success
Return (None, None, None) on error | def txid_to_block_data(txid, bitcoind_proxy, proxy=None):
"""
Given a txid, get its block's data.
Use SPV to verify the information we receive from the (untrusted)
bitcoind host.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Return the (block hash, block data, t... |
Convert a serial number into its transaction in the blockchain.
Use an untrusted bitcoind connection to get the list of transactions,
and use trusted SPV headers to ensure that the transaction obtained is on the main chain.
@bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session)
Re... | def serial_number_to_tx(serial_number, bitcoind_proxy, proxy=None):
"""
Convert a serial number into its transaction in the blockchain.
Use an untrusted bitcoind connection to get the list of transactions,
and use trusted SPV headers to ensure that the transaction obtained is on the main chain.
@bit... |
Given a transaction, locate its OP_RETURN and parse
out its opcode and payload.
Return (opcode, payload) on success
Return (None, None) if there is no OP_RETURN, or if it's not a blockchain ID operation. | def parse_tx_op_return(tx):
"""
Given a transaction, locate its OP_RETURN and parse
out its opcode and payload.
Return (opcode, payload) on success
Return (None, None) if there is no OP_RETURN, or if it's not a blockchain ID operation.
"""
# find OP_RETURN output
op_return = None
ou... |
Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error. | def get_consensus_hash_from_tx(tx):
"""
Given an SPV-verified transaction, extract its consensus hash.
Only works of the tx encodes a NAME_PREORDER, NAMESPACE_PREORDER,
or NAME_TRANSFER.
Return hex-encoded consensus hash on success.
Return None on error.
"""
opcode, payload = parse_tx_... |
Simple name verification (snv) lookup:
Use a known-good "current" consensus hash and block ID to
look up a set of name operations from the past, given the previous
point in time's untrusted block ID and consensus hash. | def snv_get_blockstack_ops_at(current_block_id, current_consensus_hash, block_id, consensus_hash, proxy=None):
"""
Simple name verification (snv) lookup:
Use a known-good "current" consensus hash and block ID to
look up a set of name operations from the past, given the previous
point in time's untru... |
Use SNV to verify that a name existed at a particular block ID in the past,
given a later known-good block ID and consensus hash (as well as the previous
untrusted consensus hash)
Return the name's historic nameop(s) on success.
If there are multiple matches, multiple nameops will be returned.
The ... | def snv_name_verify(name, current_block_id, current_consensus_hash, block_id,
consensus_hash, trusted_txid=None, trusted_txindex=None, proxy=None):
"""
Use SNV to verify that a name existed at a particular block ID in the past,
given a later known-good block ID and consensus hash (as wel... |
High-level call to simple name verification:
Given a trusted serial number, txid, or consensus_hash, use it as a trust root to verify that
a previously-registered but untrusted name (@verify_name) exists and was processed
at a given block (@verify_block_id)
Basically, use the trust root to derive a "cu... | def snv_lookup(verify_name, verify_block_id,
trusted_serial_number_or_txid_or_consensus_hash, hostport=None, proxy=None, trusted_txid=None):
"""
High-level call to simple name verification:
Given a trusted serial number, txid, or consensus_hash, use it as a trust root to verify that
a pr... |
Is the given response object
an exception traceback?
Return True if so
Return False if not | def json_is_exception(resp):
"""
Is the given response object
an exception traceback?
Return True if so
Return False if not
"""
if not json_is_error(resp):
return False
if 'traceback' not in resp.keys() or 'error' not in resp.keys():
return False
return True |
Validate an RPC response.
The response must either take the
form of the given schema, or it must
take the form of {'error': ...}
Returns the resp on success
Returns {'error': ...} on validation error | def json_validate(schema, resp):
"""
Validate an RPC response.
The response must either take the
form of the given schema, or it must
take the form of {'error': ...}
Returns the resp on success
Returns {'error': ...} on validation error
"""
# is this an error?
try:
json_... |
Generate a stack trace as a JSON-formatted error message.
Optionally use error_msg as the error field.
Return {'error': ..., 'traceback'...} | def json_traceback(error_msg=None):
"""
Generate a stack trace as a JSON-formatted error message.
Optionally use error_msg as the error field.
Return {'error': ..., 'traceback'...}
"""
exception_data = traceback.format_exc().splitlines()
if error_msg is None:
error_msg = '\n'.join(e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.