idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
224,500 | def get_epoch_namespace_prices ( block_height , units ) : assert units in [ 'BTC' , TOKEN_TYPE_STACKS ] , 'Invalid unit {}' . format ( units ) epoch_config = get_epoch_config ( block_height ) if units == 'BTC' : return epoch_config [ 'namespace_prices' ] else : return epoch_config [ 'namespace_prices_stacks' ] | get the list of namespace prices by block height | 100 | 9 |
224,501 | def op_get_opcode_name ( op_string ) : global OPCODE_NAMES # special case... if op_string == '{}:' . format ( NAME_REGISTRATION ) : return 'NAME_RENEWAL' op = op_string [ 0 ] if op not in OPCODE_NAMES : raise Exception ( 'No such operation "{}"' . format ( op ) ) return OPCODE_NAMES [ op ] | Get the name of an opcode given the op byte sequence of the operation . | 100 | 16 |
224,502 | def get_announce_filename ( working_dir ) : announce_filepath = os . path . join ( working_dir , get_default_virtualchain_impl ( ) . get_virtual_chain_name ( ) ) + '.announce' return announce_filepath | Get the path to the file that stores all of the announcements . | 59 | 13 |
224,503 | def is_indexing ( working_dir ) : indexing_path = get_indexing_lockfile ( working_dir ) if os . path . exists ( indexing_path ) : return True else : return False | Is the blockstack daemon synchronizing with the blockchain? | 47 | 11 |
224,504 | def set_indexing ( working_dir , flag ) : indexing_path = get_indexing_lockfile ( working_dir ) if flag : try : fd = open ( indexing_path , "w+" ) fd . close ( ) return True except : return False else : try : os . unlink ( indexing_path ) return True except : return False | Set a flag in the filesystem as to whether or not we re indexing . | 82 | 16 |
224,505 | def set_recovery_range ( working_dir , start_block , end_block ) : recovery_range_path = os . path . join ( working_dir , '.recovery' ) with open ( recovery_range_path , 'w' ) as f : f . write ( '{}\n{}\n' . format ( start_block , end_block ) ) f . flush ( ) os . fsync ( f . fileno ( ) ) | Set the recovery block range if we re restoring and reporcessing transactions from a backup . | 101 | 19 |
224,506 | def clear_recovery_range ( working_dir ) : recovery_range_path = os . path . join ( working_dir , '.recovery' ) if os . path . exists ( recovery_range_path ) : os . unlink ( recovery_range_path ) | Clear out our recovery hint | 61 | 5 |
224,507 | def is_atlas_enabled ( blockstack_opts ) : if not blockstack_opts [ 'atlas' ] : log . debug ( "Atlas is disabled" ) return False if 'zonefiles' not in blockstack_opts : log . debug ( "Atlas is disabled: no 'zonefiles' path set" ) return False if 'atlasdb_path' not in blockstack_opts : log . debug ( "Atlas is disabled: no 'atlasdb_path' path set" ) return False return True | Can we do atlas operations? | 118 | 7 |
224,508 | def is_subdomains_enabled ( blockstack_opts ) : if not is_atlas_enabled ( blockstack_opts ) : log . debug ( "Subdomains are disabled" ) return False if 'subdomaindb_path' not in blockstack_opts : log . debug ( "Subdomains are disabled: no 'subdomaindb_path' path set" ) return False return True | Can we do subdomain operations? | 89 | 7 |
224,509 | def store_announcement ( working_dir , announcement_hash , announcement_text , force = False ) : if not force : # don't store unless we haven't seen it before if announcement_hash in ANNOUNCEMENTS : return announce_filename = get_announce_filename ( working_dir ) announce_filename_tmp = announce_filename + ".tmp" announce_text = "" announce_cleanup_list = [ ] # did we try (and fail) to store a previous announcement? If so, merge them all if os . path . exists ( announce_filename_tmp ) : log . debug ( "Merge announcement list %s" % announce_filename_tmp ) with open ( announce_filename , "r" ) as f : announce_text += f . read ( ) i = 1 failed_path = announce_filename_tmp + ( ".%s" % i ) while os . path . exists ( failed_path ) : log . debug ( "Merge announcement list %s" % failed_path ) with open ( failed_path , "r" ) as f : announce_text += f . read ( ) announce_cleanup_list . append ( failed_path ) i += 1 failed_path = announce_filename_tmp + ( ".%s" % i ) announce_filename_tmp = failed_path if os . path . exists ( announce_filename ) : with open ( announce_filename , "r" ) as f : announce_text += f . read ( ) announce_text += ( "\n%s\n" % announcement_hash ) # filter if not force : announcement_list = announce_text . split ( "\n" ) unseen_announcements = filter ( lambda a : a not in ANNOUNCEMENTS , announcement_list ) announce_text = "\n" . join ( unseen_announcements ) . strip ( ) + "\n" log . debug ( "Store announcement hash to %s" % announce_filename ) with open ( announce_filename_tmp , "w" ) as f : f . write ( announce_text ) f . flush ( ) # NOTE: rename doesn't remove the old file on Windows if sys . platform == 'win32' and os . path . exists ( announce_filename_tmp ) : try : os . unlink ( announce_filename_tmp ) except : pass try : os . rename ( announce_filename_tmp , announce_filename ) except : log . error ( "Failed to save announcement %s to %s" % ( announcement_hash , announce_filename ) ) raise # clean up for tmp_path in announce_cleanup_list : try : os . unlink ( tmp_path ) except : pass # put the announcement text announcement_text_dir = os . path . join ( working_dir , "announcements" ) if not os . path . exists ( announcement_text_dir ) : try : os . makedirs ( announcement_text_dir ) except : log . error ( "Failed to make directory %s" % announcement_text_dir ) raise announcement_text_path = os . path . join ( announcement_text_dir , "%s.txt" % announcement_hash ) try : with open ( announcement_text_path , "w" ) as f : f . write ( announcement_text ) except : log . error ( "Failed to save announcement text to %s" % announcement_text_path ) raise log . debug ( "Stored announcement to %s" % ( announcement_text_path ) ) | Store a new announcement locally atomically . | 756 | 8 |
224,510 | def default_blockstack_api_opts ( working_dir , config_file = None ) : from . util import url_to_host_port , url_protocol if config_file is None : config_file = virtualchain . get_config_filename ( get_default_virtualchain_impl ( ) , working_dir ) parser = SafeConfigParser ( ) parser . read ( config_file ) blockstack_api_opts = { } indexer_url = None api_port = DEFAULT_API_PORT api_host = DEFAULT_API_HOST run_api = True if parser . has_section ( 'blockstack-api' ) : if parser . has_option ( 'blockstack-api' , 'enabled' ) : run_api = parser . get ( 'blockstack-api' , 'enabled' ) . lower ( ) in [ 'true' , '1' , 'on' ] if parser . has_option ( 'blockstack-api' , 'api_port' ) : api_port = int ( parser . get ( 'blockstack-api' , 'api_port' ) ) if parser . has_option ( 'blockstack-api' , 'api_host' ) : api_host = parser . get ( 'blockstack-api' , 'api_host' ) if parser . has_option ( 'blockstack-api' , 'indexer_url' ) : indexer_host , indexer_port = url_to_host_port ( parser . get ( 'blockstack-api' , 'indexer_url' ) ) indexer_protocol = url_protocol ( parser . get ( 'blockstack-api' , 'indexer_url' ) ) if indexer_protocol is None : indexer_protocol = 'http' indexer_url = parser . get ( 'blockstack-api' , 'indexer_url' ) if indexer_url is None : # try defaults indexer_url = 'http://localhost:{}' . format ( RPC_SERVER_PORT ) blockstack_api_opts = { 'indexer_url' : indexer_url , 'api_host' : api_host , 'api_port' : api_port , 'enabled' : run_api } # strip Nones for ( k , v ) in blockstack_api_opts . items ( ) : if v is None : del blockstack_api_opts [ k ] return blockstack_api_opts | Get our default blockstack RESTful API opts from a config file or from sane defaults . | 547 | 19 |
224,511 | def interactive_prompt ( message , parameters , default_opts ) : # pretty-print the message lines = message . split ( '\n' ) max_line_len = max ( [ len ( l ) for l in lines ] ) print ( '-' * max_line_len ) print ( message ) print ( '-' * max_line_len ) ret = { } for param in parameters : formatted_param = param prompt_str = '{}: ' . format ( formatted_param ) if param in default_opts : prompt_str = '{} (default: "{}"): ' . format ( formatted_param , default_opts [ param ] ) try : value = raw_input ( prompt_str ) except KeyboardInterrupt : log . debug ( 'Exiting on keyboard interrupt' ) sys . exit ( 0 ) if len ( value ) > 0 : ret [ param ] = value elif param in default_opts : ret [ param ] = default_opts [ param ] else : ret [ param ] = None return ret | Prompt the user for a series of parameters Return a dict mapping the parameter name to the user - given value . | 224 | 23 |
224,512 | def find_missing ( message , all_params , given_opts , default_opts , header = None , prompt_missing = True ) : # are we missing anything? missing_params = list ( set ( all_params ) - set ( given_opts ) ) num_prompted = 0 if not missing_params : return given_opts , missing_params , num_prompted if not prompt_missing : # count the number missing, and go with defaults missing_values = set ( default_opts ) - set ( given_opts ) num_prompted = len ( missing_values ) given_opts . update ( default_opts ) else : if header is not None : print ( '-' * len ( header ) ) print ( header ) missing_values = interactive_prompt ( message , missing_params , default_opts ) num_prompted = len ( missing_values ) given_opts . update ( missing_values ) return given_opts , missing_params , num_prompted | Find and interactively prompt the user for missing parameters given the list of all valid parameters and a dict of known options . | 226 | 24 |
224,513 | def opt_strip ( prefix , opts ) : ret = { } for opt_name , opt_value in opts . items ( ) : # remove prefix if opt_name . startswith ( prefix ) : opt_name = opt_name [ len ( prefix ) : ] ret [ opt_name ] = opt_value return ret | Given a dict of opts that start with prefix remove the prefix from each of them . | 72 | 18 |
224,514 | def opt_restore ( prefix , opts ) : return { prefix + name : value for name , value in opts . items ( ) } | Given a dict of opts add the given prefix to each key | 31 | 13 |
224,515 | def default_bitcoind_opts ( config_file = None , prefix = False ) : default_bitcoin_opts = virtualchain . get_bitcoind_config ( config_file = config_file ) # drop dict values that are None default_bitcoin_opts = { k : v for k , v in default_bitcoin_opts . items ( ) if v is not None } # strip 'bitcoind_' if not prefix : default_bitcoin_opts = opt_strip ( 'bitcoind_' , default_bitcoin_opts ) return default_bitcoin_opts | Get our default bitcoind options such as from a config file or from sane defaults | 130 | 17 |
224,516 | def default_working_dir ( ) : import nameset . virtualchain_hooks as virtualchain_hooks return os . path . expanduser ( '~/.{}' . format ( virtualchain_hooks . get_virtual_chain_name ( ) ) ) | Get the default configuration directory for blockstackd | 58 | 9 |
224,517 | def write_config_file ( opts , config_file ) : parser = SafeConfigParser ( ) if os . path . exists ( config_file ) : parser . read ( config_file ) for sec_name in opts : sec_opts = opts [ sec_name ] if parser . has_section ( sec_name ) : parser . remove_section ( sec_name ) parser . add_section ( sec_name ) for opt_name , opt_value in sec_opts . items ( ) : if opt_value is None : opt_value = '' parser . set ( sec_name , opt_name , '{}' . format ( opt_value ) ) with open ( config_file , 'w' ) as fout : os . fchmod ( fout . fileno ( ) , 0600 ) parser . write ( fout ) return True | Write our config file with the given options dict . Each key is a section name and each value is the list of options . | 189 | 25 |
224,518 | def load_configuration ( working_dir ) : import nameset . virtualchain_hooks as virtualchain_hooks # acquire configuration, and store it globally opts = configure ( working_dir ) blockstack_opts = opts . get ( 'blockstack' , None ) blockstack_api_opts = opts . get ( 'blockstack-api' , None ) bitcoin_opts = opts [ 'bitcoind' ] # config file version check config_server_version = blockstack_opts . get ( 'server_version' , None ) if ( config_server_version is None or versions_need_upgrade ( config_server_version , VERSION ) ) : print >> sys . stderr , "Obsolete or unrecognizable config file ({}): '{}' != '{}'" . format ( virtualchain . get_config_filename ( virtualchain_hooks , working_dir ) , config_server_version , VERSION ) print >> sys . stderr , 'Please see the release notes for version {} for instructions to upgrade (in the release-notes/ folder).' . format ( VERSION ) return None # store options set_bitcoin_opts ( bitcoin_opts ) set_blockstack_opts ( blockstack_opts ) set_blockstack_api_opts ( blockstack_api_opts ) return { 'bitcoind' : bitcoin_opts , 'blockstack' : blockstack_opts , 'blockstack-api' : blockstack_api_opts } | Load the system configuration and set global variables Return the configuration of the node on success . Return None on failure | 337 | 21 |
224,519 | def check ( state_engine , nameop , block_id , checked_ops ) : namespace_id = nameop [ 'namespace_id' ] sender = nameop [ 'sender' ] # must have been revealed if not state_engine . is_namespace_revealed ( namespace_id ) : log . warning ( "Namespace '%s' is not revealed" % namespace_id ) return False # must have been sent by the same person who revealed it revealed_namespace = state_engine . get_namespace_reveal ( namespace_id ) if revealed_namespace [ 'recipient' ] != sender : log . warning ( "Namespace '%s' is not owned by '%s' (but by %s)" % ( namespace_id , sender , revealed_namespace [ 'recipient' ] ) ) return False # can't be ready yet if state_engine . is_namespace_ready ( namespace_id ) : # namespace already exists log . warning ( "Namespace '%s' is already registered" % namespace_id ) return False # preserve from revealed nameop [ 'sender_pubkey' ] = revealed_namespace [ 'sender_pubkey' ] nameop [ 'address' ] = revealed_namespace [ 'address' ] # can commit imported nameops return True | Verify the validity of a NAMESPACE_READY operation . It is only valid if it has been imported by the same sender as the corresponding NAMESPACE_REVEAL and the namespace is still in the process of being imported . | 286 | 51 |
224,520 | def int_to_charset ( val , charset ) : if val < 0 : raise ValueError ( '"val" must be a non-negative integer.' ) if val == 0 : return charset [ 0 ] output = "" while val > 0 : val , digit = divmod ( val , len ( charset ) ) output += charset [ digit ] # reverse the characters in the output and return return output [ : : - 1 ] | Turn a non - negative integer into a string . | 95 | 10 |
224,521 | def charset_to_int ( s , charset ) : output = 0 for char in s : output = output * len ( charset ) + charset . index ( char ) return output | Turn a string into a non - negative integer . | 41 | 10 |
224,522 | def change_charset ( s , original_charset , target_charset ) : if not isinstance ( s , str ) : raise ValueError ( '"s" must be a string.' ) intermediate_integer = charset_to_int ( s , original_charset ) output_string = int_to_charset ( intermediate_integer , target_charset ) return output_string | Convert a string from one charset to another . | 91 | 11 |
224,523 | def autofill ( * autofill_fields ) : def wrap ( reader ) : def wrapped_reader ( * args , * * kw ) : rec = reader ( * args , * * kw ) if rec is not None : for field in autofill_fields : if field == "opcode" and 'opcode' not in rec . keys ( ) : assert 'op' in rec . keys ( ) , "BUG: record is missing 'op'" rec [ 'opcode' ] = op_get_opcode_name ( rec [ 'op' ] ) else : raise Exception ( "Unknown autofill field '%s'" % field ) return rec return wrapped_reader return wrap | Decorator to automatically fill in extra useful fields that aren t stored in the db . | 150 | 18 |
224,524 | def get_readonly_instance ( cls , working_dir , expected_snapshots = { } ) : import virtualchain_hooks db_path = virtualchain . get_db_filename ( virtualchain_hooks , working_dir ) db = BlockstackDB ( db_path , DISPOSITION_RO , working_dir , get_genesis_block ( ) , expected_snapshots = { } ) rc = db . db_setup ( ) if not rc : log . error ( "Failed to set up virtualchain state engine" ) return None return db | Get a read - only handle to the blockstack - specific name db . Multiple read - only handles may exist . | 123 | 23 |
224,525 | def make_opfields ( cls ) : # construct fields opfields = { } for opname in SERIALIZE_FIELDS . keys ( ) : opcode = NAME_OPCODES [ opname ] opfields [ opcode ] = SERIALIZE_FIELDS [ opname ] return opfields | Calculate the virtulachain - required opfields dict . | 68 | 14 |
224,526 | def get_state_paths ( cls , impl , working_dir ) : return super ( BlockstackDB , cls ) . get_state_paths ( impl , working_dir ) + [ os . path . join ( working_dir , 'atlas.db' ) , os . path . join ( working_dir , 'subdomains.db' ) , os . path . join ( working_dir , 'subdomains.db.queue' ) ] | Get the paths to the relevant db files to back up | 102 | 11 |
224,527 | def close ( self ) : if self . db is not None : self . db . commit ( ) self . db . close ( ) self . db = None return | Close the db and release memory | 34 | 6 |
224,528 | def get_import_keychain_path ( cls , keychain_dir , namespace_id ) : cached_keychain = os . path . join ( keychain_dir , "{}.keychain" . format ( namespace_id ) ) return cached_keychain | Get the path to the import keychain | 57 | 8 |
224,529 | def build_import_keychain ( cls , keychain_dir , namespace_id , pubkey_hex ) : pubkey_addr = virtualchain . BitcoinPublicKey ( str ( pubkey_hex ) ) . address ( ) # do we have a cached one on disk? cached_keychain = cls . get_import_keychain_path ( keychain_dir , namespace_id ) if os . path . exists ( cached_keychain ) : child_addrs = [ ] try : lines = [ ] with open ( cached_keychain , "r" ) as f : lines = f . readlines ( ) child_attrs = [ l . strip ( ) for l in lines ] log . debug ( "Loaded cached import keychain for '%s' (%s)" % ( pubkey_hex , pubkey_addr ) ) return child_attrs except Exception , e : log . exception ( e ) pass pubkey_hex = str ( pubkey_hex ) public_keychain = keychain . PublicKeychain . from_public_key ( pubkey_hex ) child_addrs = [ ] for i in xrange ( 0 , NAME_IMPORT_KEYRING_SIZE ) : public_child = public_keychain . child ( i ) public_child_address = public_child . address ( ) # if we're on testnet, then re-encode as a testnet address if virtualchain . version_byte == 111 : old_child_address = public_child_address public_child_address = virtualchain . hex_hash160_to_address ( virtualchain . address_to_hex_hash160 ( public_child_address ) ) log . debug ( "Re-encode '%s' to '%s'" % ( old_child_address , public_child_address ) ) child_addrs . append ( public_child_address ) if i % 20 == 0 and i != 0 : log . debug ( "%s children..." % i ) # include this address child_addrs . append ( pubkey_addr ) log . debug ( "Done building import keychain for '%s' (%s)" % ( pubkey_hex , pubkey_addr ) ) # cache try : with open ( cached_keychain , "w+" ) as f : for addr in child_addrs : f . write ( "%s\n" % addr ) f . flush ( ) log . debug ( "Cached keychain to '%s'" % cached_keychain ) except Exception , e : log . exception ( e ) log . error ( "Unable to cache keychain for '%s' (%s)" % ( pubkey_hex , pubkey_addr ) ) return child_addrs | Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key | 592 | 21 |
224,530 | def load_import_keychain ( cls , working_dir , namespace_id ) : # do we have a cached one on disk? cached_keychain = os . path . join ( working_dir , "%s.keychain" % namespace_id ) if os . path . exists ( cached_keychain ) : log . debug ( "Load import keychain '%s'" % cached_keychain ) child_addrs = [ ] try : lines = [ ] with open ( cached_keychain , "r" ) as f : lines = f . readlines ( ) child_attrs = [ l . strip ( ) for l in lines ] log . debug ( "Loaded cached import keychain for '%s'" % namespace_id ) return child_attrs except Exception , e : log . exception ( e ) log . error ( "FATAL: uncaught exception loading the import keychain" ) os . abort ( ) else : log . debug ( "No import keychain at '%s'" % cached_keychain ) return None | Get an import keychain from disk . Return None if it doesn t exist . | 225 | 16 |
224,531 | def commit_finished ( self , block_id ) : self . db . commit ( ) # NOTE: tokens vest for the *next* block in order to make the immediately usable assert block_id + 1 in self . vesting , 'BUG: failed to vest at {}' . format ( block_id ) self . clear_collisions ( block_id ) self . clear_vesting ( block_id + 1 ) | Called when the block is finished . Commits all data . | 89 | 13 |
224,532 | def log_commit ( self , block_id , vtxindex , op , opcode , op_data ) : debug_op = self . sanitize_op ( op_data ) if 'history' in debug_op : del debug_op [ 'history' ] log . debug ( "COMMIT %s (%s) at (%s, %s) data: %s" , opcode , op , block_id , vtxindex , ", " . join ( [ "%s='%s'" % ( k , debug_op [ k ] ) for k in sorted ( debug_op . keys ( ) ) ] ) ) return | Log a committed operation | 137 | 4 |
224,533 | def log_reject ( self , block_id , vtxindex , op , op_data ) : debug_op = self . sanitize_op ( op_data ) if 'history' in debug_op : del debug_op [ 'history' ] log . debug ( "REJECT %s at (%s, %s) data: %s" , op_get_opcode_name ( op ) , block_id , vtxindex , ", " . join ( [ "%s='%s'" % ( k , debug_op [ k ] ) for k in sorted ( debug_op . keys ( ) ) ] ) ) return | Log a rejected operation | 139 | 4 |
224,534 | def sanitize_op ( self , op_data ) : op_data = super ( BlockstackDB , self ) . sanitize_op ( op_data ) # remove invariant tags (i.e. added by our invariant state_* decorators) to_remove = get_state_invariant_tags ( ) for tag in to_remove : if tag in op_data . keys ( ) : del op_data [ tag ] # NOTE: this is called the opcode family, because # different operation names can have the same operation code # (such as NAME_RENEWAL and NAME_REGISTRATION). They must # have the same mutation fields. opcode_family = op_get_opcode_name ( op_data [ 'op' ] ) # for each column in the appropriate state table, # if the column is not identified in the operation's # MUTATE_FIELDS list, then set it to None here. mutate_fields = op_get_mutate_fields ( opcode_family ) for mf in mutate_fields : if not op_data . has_key ( mf ) : log . debug ( "Adding NULL mutate field '%s.%s'" % ( opcode_family , mf ) ) op_data [ mf ] = None # TODO: less ad-hoc for extra_field in [ 'opcode' ] : if extra_field in op_data : del op_data [ extra_field ] return op_data | Remove unnecessary fields for an operation i . e . prior to committing it . This includes any invariant tags we ve added with our invariant decorators ( such as | 330 | 33 |
224,535 | def put_collisions ( self , block_id , collisions ) : self . collisions [ block_id ] = copy . deepcopy ( collisions ) | Put collision state for a particular block . Any operations checked at this block_id that collide with the given collision state will be rejected . | 31 | 27 |
224,536 | def get_namespace ( self , namespace_id , include_history = True ) : cur = self . db . cursor ( ) return namedb_get_namespace_ready ( cur , namespace_id , include_history = include_history ) | Given a namespace ID get the ready namespace op for it . | 53 | 12 |
224,537 | def get_DID_name ( self , did ) : did = str ( did ) did_info = None try : did_info = parse_DID ( did ) assert did_info [ 'name_type' ] == 'name' except Exception as e : if BLOCKSTACK_DEBUG : log . exception ( e ) raise ValueError ( "Invalid DID: {}" . format ( did ) ) cur = self . db . cursor ( ) historic_name_info = namedb_get_historic_names_by_address ( cur , did_info [ 'address' ] , offset = did_info [ 'index' ] , count = 1 ) if historic_name_info is None : # no such name return None name = historic_name_info [ 0 ] [ 'name' ] block_height = historic_name_info [ 0 ] [ 'block_id' ] vtxindex = historic_name_info [ 0 ] [ 'vtxindex' ] log . debug ( "DID {} refers to {}-{}-{}" . format ( did , name , block_height , vtxindex ) ) name_rec = self . get_name ( name , include_history = True , include_expired = True ) if name_rec is None : # dead return None name_rec_latest = None found = False for height in sorted ( name_rec [ 'history' ] . keys ( ) ) : if found : break if height < block_height : continue for state in name_rec [ 'history' ] [ height ] : if height == block_height and state [ 'vtxindex' ] < vtxindex : # too soon continue if state [ 'op' ] == NAME_PREORDER : # looped to the next iteration of this name found = True break if state [ 'revoked' ] : # revoked log . debug ( "DID {} refers to {}-{}-{}, which is revoked at {}-{}" . format ( did , name , block_height , vtxindex , height , state [ 'vtxindex' ] ) ) return None name_rec_latest = state return name_rec_latest | Given a DID get the name Return None if not found or if the name was revoked Raise if the DID is invalid | 464 | 23 |
224,538 | def get_account_tokens ( self , address ) : cur = self . db . cursor ( ) return namedb_get_account_tokens ( cur , address ) | Get the list of tokens that this address owns | 39 | 9 |
224,539 | def get_account ( self , address , token_type ) : cur = self . db . cursor ( ) return namedb_get_account ( cur , address , token_type ) | Get the state of an account for a given token type | 39 | 11 |
224,540 | def get_account_balance ( self , account ) : balance = namedb_get_account_balance ( account ) assert isinstance ( balance , ( int , long ) ) , 'BUG: account balance of {} is {} (type {})' . format ( account [ 'address' ] , balance , type ( balance ) ) return balance | What s the balance of an account? Aborts if its negative | 70 | 13 |
224,541 | def get_account_history ( self , address , offset = None , count = None ) : cur = self . db . cursor ( ) return namedb_get_account_history ( cur , address , offset = offset , count = count ) | Get the history of account transactions over a block range Returns a dict keyed by blocks which map to lists of account state transitions | 51 | 25 |
224,542 | def get_name_at ( self , name , block_number , include_expired = False ) : cur = self . db . cursor ( ) return namedb_get_name_at ( cur , name , block_number , include_expired = include_expired ) | Generate and return the sequence of of states a name record was in at a particular block number . | 60 | 20 |
224,543 | def get_namespace_at ( self , namespace_id , block_number ) : cur = self . db . cursor ( ) return namedb_get_namespace_at ( cur , namespace_id , block_number , include_expired = True ) | Generate and return the sequence of states a namespace record was in at a particular block number . | 56 | 19 |
224,544 | def get_account_at ( self , address , block_number ) : cur = self . db . cursor ( ) return namedb_get_account_at ( cur , address , block_number ) | Get the sequence of states an account was in at a given block . Returns a list of states | 43 | 19 |
224,545 | def get_name_history ( self , name , offset = None , count = None , reverse = False ) : cur = self . db . cursor ( ) name_hist = namedb_get_history ( cur , name , offset = offset , count = count , reverse = reverse ) return name_hist | Get the historic states for a name grouped by block height . | 64 | 12 |
224,546 | def is_name_zonefile_hash ( self , name , zonefile_hash ) : cur = self . db . cursor ( ) return namedb_is_name_zonefile_hash ( cur , name , zonefile_hash ) | Was a zone file sent by a name? | 51 | 9 |
224,547 | def get_all_blockstack_ops_at ( self , block_number , offset = None , count = None , include_history = None , restore_history = None ) : if include_history is not None : log . warn ( "DEPRECATED use of include_history" ) if restore_history is not None : log . warn ( "DEPRECATED use of restore_history" ) log . debug ( "Get all accepted operations at %s in %s" % ( block_number , self . db_filename ) ) recs = namedb_get_all_blockstack_ops_at ( self . db , block_number , offset = offset , count = count ) # include opcode for rec in recs : assert 'op' in rec rec [ 'opcode' ] = op_get_opcode_name ( rec [ 'op' ] ) return recs | Get all name namespace and account records affected at a particular block in the state they were at the given block number . Paginate if offset count are given . | 190 | 31 |
224,548 | def get_name_from_name_hash128 ( self , name ) : cur = self . db . cursor ( ) name = namedb_get_name_from_name_hash128 ( cur , name , self . lastblock ) return name | Get the name from a name hash | 53 | 7 |
224,549 | def get_num_historic_names_by_address ( self , address ) : cur = self . db . cursor ( ) count = namedb_get_num_historic_names_by_address ( cur , address ) return count | Get the number of names historically owned by an address | 50 | 10 |
224,550 | def get_names_owned_by_sender ( self , sender_pubkey , lastblock = None ) : cur = self . db . cursor ( ) if lastblock is None : lastblock = self . lastblock names = namedb_get_names_by_sender ( cur , sender_pubkey , lastblock ) return names | Get the set of names owned by a particular script - pubkey . | 73 | 14 |
224,551 | def get_num_names ( self , include_expired = False ) : cur = self . db . cursor ( ) return namedb_get_num_names ( cur , self . lastblock , include_expired = include_expired ) | Get the number of names that exist . | 53 | 8 |
224,552 | def get_all_names ( self , offset = None , count = None , include_expired = False ) : if offset is not None and offset < 0 : offset = None if count is not None and count < 0 : count = None cur = self . db . cursor ( ) names = namedb_get_all_names ( cur , self . lastblock , offset = offset , count = count , include_expired = include_expired ) return names | Get the set of all registered names with optional pagination Returns the list of names . | 98 | 17 |
224,553 | def get_num_names_in_namespace ( self , namespace_id ) : cur = self . db . cursor ( ) return namedb_get_num_names_in_namespace ( cur , namespace_id , self . lastblock ) | Get the number of names in a namespace | 54 | 8 |
224,554 | def get_names_in_namespace ( self , namespace_id , offset = None , count = None ) : if offset is not None and offset < 0 : offset = None if count is not None and count < 0 : count = None cur = self . db . cursor ( ) names = namedb_get_names_in_namespace ( cur , namespace_id , self . lastblock , offset = offset , count = count ) return names | Get the set of all registered names in a particular namespace . Returns the list of names . | 95 | 18 |
224,555 | def get_all_namespace_ids ( self ) : cur = self . db . cursor ( ) namespace_ids = namedb_get_all_namespace_ids ( cur ) return namespace_ids | Get the set of all existing READY namespace IDs . | 44 | 11 |
224,556 | def get_all_revealed_namespace_ids ( self ) : cur = self . db . cursor ( ) namespace_ids = namedb_get_all_revealed_namespace_ids ( cur , self . lastblock ) return namespace_ids | Get all revealed namespace IDs that have not expired . | 55 | 10 |
224,557 | def get_all_preordered_namespace_hashes ( self ) : cur = self . db . cursor ( ) namespace_hashes = namedb_get_all_preordered_namespace_hashes ( cur , self . lastblock ) return namespace_hashes | Get all oustanding namespace preorder hashes that have not expired . Used for testing | 59 | 16 |
224,558 | def get_all_importing_namespace_hashes ( self ) : cur = self . db . cursor ( ) namespace_hashes = namedb_get_all_importing_namespace_hashes ( cur , self . lastblock ) return namespace_hashes | Get the set of all preordered and revealed namespace hashes that have not expired . | 59 | 16 |
224,559 | def get_name_preorder ( self , name , sender_script_pubkey , register_addr , include_failed = False ) : # name registered and not expired? name_rec = self . get_name ( name ) if name_rec is not None and not include_failed : return None # what namespace are we in? namespace_id = get_namespace_from_name ( name ) namespace = self . get_namespace ( namespace_id ) if namespace is None : return None # isn't currently registered, or we don't care preorder_hash = hash_name ( name , sender_script_pubkey , register_addr = register_addr ) preorder = namedb_get_name_preorder ( self . db , preorder_hash , self . lastblock ) if preorder is None : # doesn't exist or expired return None # preorder must be younger than the namespace lifetime # (otherwise we get into weird conditions where someone can preorder # a name before someone else, and register it after it expires) namespace_lifetime_multiplier = get_epoch_namespace_lifetime_multiplier ( self . lastblock , namespace_id ) if preorder [ 'block_number' ] + ( namespace [ 'lifetime' ] * namespace_lifetime_multiplier ) <= self . lastblock : log . debug ( "Preorder is too old (accepted at {}, namespace lifetime is {}, current block is {})" . format ( preorder [ 'block_number' ] , namespace [ 'lifetime' ] * namespace_lifetime_multiplier , self . lastblock ) ) return None return preorder | Get the current preorder for a name given the name the sender s script pubkey and the registration address used to calculate the preorder hash . | 353 | 29 |
224,560 | def get_names_with_value_hash ( self , value_hash ) : cur = self . db . cursor ( ) names = namedb_get_names_with_value_hash ( cur , value_hash , self . lastblock ) return names | Get the list of names with the given value hash at the current block height . This excludes revoked names and expired names . | 55 | 24 |
224,561 | def get_atlas_zonefile_info_at ( self , block_id ) : nameops = self . get_all_blockstack_ops_at ( block_id ) ret = [ ] for nameop in nameops : if nameop . has_key ( 'op' ) and op_get_opcode_name ( nameop [ 'op' ] ) in [ 'NAME_UPDATE' , 'NAME_IMPORT' , 'NAME_REGISTRATION' , 'NAME_RENEWAL' ] : assert nameop . has_key ( 'value_hash' ) assert nameop . has_key ( 'name' ) assert nameop . has_key ( 'txid' ) if nameop [ 'value_hash' ] is not None : ret . append ( { 'name' : nameop [ 'name' ] , 'value_hash' : nameop [ 'value_hash' ] , 'txid' : nameop [ 'txid' ] } ) return ret | Get the blockchain - ordered sequence of names value hashes and txids . added at the given block height . The order will be in tx - order . | 218 | 30 |
224,562 | def get_namespace_reveal ( self , namespace_id , include_history = True ) : cur = self . db . cursor ( ) namespace_reveal = namedb_get_namespace_reveal ( cur , namespace_id , self . lastblock , include_history = include_history ) return namespace_reveal | Given the name of a namespace get it if it is currently being revealed . | 71 | 15 |
224,563 | def is_name_registered ( self , name ) : name_rec = self . get_name ( name ) # won't return the name if expired if name_rec is None : return False if name_rec [ 'revoked' ] : return False return True | Given the fully - qualified name is it registered not revoked and not expired at the current block? | 56 | 19 |
224,564 | def is_namespace_ready ( self , namespace_id ) : namespace = self . get_namespace ( namespace_id ) if namespace is not None : return True else : return False | Given a namespace ID determine if the namespace is ready at the current block . | 40 | 15 |
224,565 | def is_namespace_preordered ( self , namespace_id_hash ) : namespace_preorder = self . get_namespace_preorder ( namespace_id_hash ) if namespace_preorder is None : return False else : return True | Given a namespace preorder hash determine if it is preordered at the current block . | 53 | 17 |
224,566 | def is_namespace_revealed ( self , namespace_id ) : namespace_reveal = self . get_namespace_reveal ( namespace_id ) if namespace_reveal is not None : return True else : return False | Given the name of a namespace has it been revealed but not made ready at the current block? | 50 | 19 |
224,567 | def is_name_owner ( self , name , sender_script_pubkey ) : if not self . is_name_registered ( name ) : # no one owns it return False owner = self . get_name_owner ( name ) if owner != sender_script_pubkey : return False else : return True | Given the fully - qualified name and a sender s script pubkey determine if the sender owns the name . | 67 | 21 |
224,568 | def is_new_preorder ( self , preorder_hash , lastblock = None ) : if lastblock is None : lastblock = self . lastblock preorder = namedb_get_name_preorder ( self . db , preorder_hash , lastblock ) if preorder is not None : return False else : return True | Given a preorder hash of a name determine whether or not it is unseen before . | 72 | 17 |
224,569 | def is_new_namespace_preorder ( self , namespace_id_hash , lastblock = None ) : if lastblock is None : lastblock = self . lastblock preorder = namedb_get_namespace_preorder ( self . db , namespace_id_hash , lastblock ) if preorder is not None : return False else : return True | Given a namespace preorder hash determine whether or not is is unseen before . | 78 | 15 |
224,570 | def is_name_revoked ( self , name ) : name = self . get_name ( name ) if name is None : return False if name [ 'revoked' ] : return True else : return False | Determine if a name is revoked at this block . | 45 | 12 |
224,571 | def get_value_hash_txids ( self , value_hash ) : cur = self . db . cursor ( ) return namedb_get_value_hash_txids ( cur , value_hash ) | Get the list of txids by value hash | 45 | 9 |
224,572 | def nameop_set_collided ( cls , nameop , history_id_key , history_id ) : nameop [ '__collided__' ] = True nameop [ '__collided_history_id_key__' ] = history_id_key nameop [ '__collided_history_id__' ] = history_id | Mark a nameop as collided | 78 | 6 |
224,573 | def nameop_put_collision ( cls , collisions , nameop ) : # these are supposed to have been put here by nameop_set_collided history_id_key = nameop . get ( '__collided_history_id_key__' , None ) history_id = nameop . get ( '__collided_history_id__' , None ) try : assert cls . nameop_is_collided ( nameop ) , "Nameop not collided" assert history_id_key is not None , "Nameop missing collision info" assert history_id is not None , "Nameop missing collision info" except Exception , e : log . exception ( e ) log . error ( "FATAL: BUG: bad collision info" ) os . abort ( ) if not collisions . has_key ( history_id_key ) : collisions [ history_id_key ] = [ history_id ] else : collisions [ history_id_key ] . append ( history_id ) | Record a nameop as collided with another nameop in this block . | 218 | 14 |
224,574 | def extract_consensus_op ( self , opcode , op_data , processed_op_data , current_block_number ) : ret = { } consensus_fields = op_get_consensus_fields ( opcode ) quirk_fields = op_get_quirk_fields ( opcode ) for field in consensus_fields + quirk_fields : try : # assert field in processed_op_data or field in op_data, 'Missing consensus field "{}"'.format(field) assert field in processed_op_data , 'Missing consensus field "{}"' . format ( field ) except Exception as e : # should NEVER happen log . exception ( e ) log . error ( "FATAL: BUG: missing consensus field {}" . format ( field ) ) log . error ( "op_data:\n{}" . format ( json . dumps ( op_data , indent = 4 , sort_keys = True ) ) ) log . error ( "processed_op_data:\n{}" . format ( json . dumps ( op_data , indent = 4 , sort_keys = True ) ) ) os . abort ( ) ret [ field ] = processed_op_data [ field ] return ret | Using the operation data extracted from parsing the virtualchain operation ( | 260 | 12 |
224,575 | def commit_operation ( self , input_op_data , accepted_nameop , current_block_number ) : # have to have read-write disposition if self . disposition != DISPOSITION_RW : log . error ( "FATAL: borrowing violation: not a read-write connection" ) traceback . print_stack ( ) os . abort ( ) cur = self . db . cursor ( ) canonical_op = None op_type_str = None # for debugging opcode = accepted_nameop . get ( 'opcode' , None ) try : assert opcode is not None , "Undefined op '%s'" % accepted_nameop [ 'op' ] except Exception , e : log . exception ( e ) log . error ( "FATAL: unrecognized op '%s'" % accepted_nameop [ 'op' ] ) os . abort ( ) if opcode in OPCODE_PREORDER_OPS : # preorder canonical_op = self . commit_state_preorder ( accepted_nameop , current_block_number ) op_type_str = "state_preorder" elif opcode in OPCODE_CREATION_OPS : # creation canonical_op = self . commit_state_create ( accepted_nameop , current_block_number ) op_type_str = "state_create" elif opcode in OPCODE_TRANSITION_OPS : # transition canonical_op = self . commit_state_transition ( accepted_nameop , current_block_number ) op_type_str = "state_transition" elif opcode in OPCODE_TOKEN_OPS : # token operation canonical_op = self . commit_token_operation ( accepted_nameop , current_block_number ) op_type_str = "token_operation" else : raise Exception ( "Unknown operation {}" . format ( opcode ) ) if canonical_op is None : log . error ( "FATAL: no canonical op generated (for {})" . format ( op_type_str ) ) os . abort ( ) log . debug ( "Extract consensus fields for {} in {}, as part of a {}" . format ( opcode , current_block_number , op_type_str ) ) consensus_op = self . extract_consensus_op ( opcode , input_op_data , canonical_op , current_block_number ) return consensus_op | Commit an operation thereby carrying out a state transition . | 526 | 11 |
224,576 | def commit_token_operation ( self , token_op , current_block_number ) : # have to have read-write disposition if self . disposition != DISPOSITION_RW : log . error ( "FATAL: borrowing violation: not a read-write connection" ) traceback . print_stack ( ) os . abort ( ) cur = self . db . cursor ( ) opcode = token_op . get ( 'opcode' , None ) clean_token_op = self . sanitize_op ( token_op ) try : assert token_operation_is_valid ( token_op ) , 'Invalid token operation' assert opcode is not None , 'No opcode given' assert 'txid' in token_op , 'No txid' assert 'vtxindex' in token_op , 'No vtxindex' except Exception as e : log . exception ( e ) log . error ( 'FATAL: failed to commit token operation' ) self . db . rollback ( ) os . abort ( ) table = token_operation_get_table ( token_op ) account_payment_info = token_operation_get_account_payment_info ( token_op ) account_credit_info = token_operation_get_account_credit_info ( token_op ) # fields must be set try : for key in account_payment_info : assert account_payment_info [ key ] is not None , 'BUG: payment info key {} is None' . format ( key ) for key in account_credit_info : assert account_credit_info [ key ] is not None , 'BUG: credit info key {} is not None' . format ( key ) # NOTE: do not check token amount and type, since in the future we want to support converting # between tokens except Exception as e : log . exception ( e ) log . error ( "FATAL: invalid token debit or credit info" ) os . abort ( ) self . log_accept ( current_block_number , token_op [ 'vtxindex' ] , token_op [ 'op' ] , token_op ) # NOTE: this code is single-threaded, but this code must be atomic self . commit_account_debit ( token_op , account_payment_info , current_block_number , token_op [ 'vtxindex' ] , token_op [ 'txid' ] ) self . commit_account_credit ( token_op , account_credit_info , current_block_number , token_op [ 'vtxindex' ] , token_op [ 'txid' ] ) namedb_history_save ( cur , opcode , token_op [ 'address' ] , None , None , current_block_number , token_op [ 'vtxindex' ] , token_op [ 'txid' ] , clean_token_op ) return clean_token_op | Commit a token operation that debits one account and credits another | 625 | 13 |
224,577 | def commit_account_vesting ( self , block_height ) : # save all state log . debug ( "Commit all database state before vesting" ) self . db . commit ( ) if block_height in self . vesting : traceback . print_stack ( ) log . fatal ( "Tried to vest tokens twice at {}" . format ( block_height ) ) os . abort ( ) # commit all vesting in one transaction cur = self . db . cursor ( ) namedb_query_execute ( cur , 'BEGIN' , ( ) ) res = namedb_accounts_vest ( cur , block_height ) namedb_query_execute ( cur , 'END' , ( ) ) self . vesting [ block_height ] = True return True | vest any tokens at this block height | 165 | 7 |
224,578 | def is_name_valid ( fqn ) : if not isinstance ( fqn , ( str , unicode ) ) : return False if fqn . count ( "." ) != 1 : return False name , namespace_id = fqn . split ( "." ) if len ( name ) == 0 or len ( namespace_id ) == 0 : return False if not is_b40 ( name ) or "+" in name or "." in name : return False if not is_namespace_valid ( namespace_id ) : return False if len ( fqn ) > LENGTHS [ 'blockchain_id_name' ] : # too long return False return True | Is a fully - qualified name acceptable? Return True if so Return False if not | 147 | 16 |
224,579 | def is_namespace_valid ( namespace_id ) : if not is_b40 ( namespace_id ) or "+" in namespace_id or namespace_id . count ( "." ) > 0 : return False if len ( namespace_id ) == 0 or len ( namespace_id ) > LENGTHS [ 'blockchain_id_namespace_id' ] : return False return True | Is a namespace ID valid? | 84 | 6 |
224,580 | def price_namespace ( namespace_id , block_height , units ) : price_table = get_epoch_namespace_prices ( block_height , units ) if price_table is None : return None if len ( namespace_id ) >= len ( price_table ) or len ( namespace_id ) == 0 : return None return price_table [ len ( namespace_id ) ] | Calculate the cost of a namespace . Returns the price on success Returns None if the namespace is invalid or if the units are invalid | 85 | 27 |
224,581 | def find_by_opcode ( checked_ops , opcode ) : if type ( opcode ) != list : opcode = [ opcode ] ret = [ ] for opdata in checked_ops : if op_get_opcode_name ( opdata [ 'op' ] ) in opcode : ret . append ( opdata ) return ret | Given all previously - accepted operations in this block find the ones that are of a particular opcode . | 75 | 20 |
224,582 | def get_public_key_hex_from_tx ( inputs , address ) : ret = None for inp in inputs : input_scriptsig = inp [ 'script' ] input_script_code = virtualchain . btc_script_deserialize ( input_scriptsig ) if len ( input_script_code ) == 2 : # signature pubkey pubkey_candidate = input_script_code [ 1 ] pubkey = None try : pubkey = virtualchain . BitcoinPublicKey ( pubkey_candidate ) except Exception as e : traceback . print_exc ( ) log . warn ( "Invalid public key {}" . format ( pubkey_candidate ) ) continue if address != pubkey . address ( ) : continue # success! return pubkey_candidate return None | Given a list of inputs and the address of one of the inputs find the public key . | 170 | 18 |
224,583 | def check_name ( name ) : if type ( name ) not in [ str , unicode ] : return False if not is_name_valid ( name ) : return False return True | Verify the name is well - formed | 39 | 8 |
224,584 | def check_namespace ( namespace_id ) : if type ( namespace_id ) not in [ str , unicode ] : return False if not is_namespace_valid ( namespace_id ) : return False return True | Verify that a namespace ID is well - formed | 47 | 10 |
224,585 | def check_token_type ( token_type ) : return check_string ( token_type , min_length = 1 , max_length = LENGTHS [ 'namespace_id' ] , pattern = '^{}$|{}' . format ( TOKEN_TYPE_STACKS , OP_NAMESPACE_PATTERN ) ) | Verify that a token type is well - formed | 77 | 10 |
224,586 | def check_subdomain ( fqn ) : if type ( fqn ) not in [ str , unicode ] : return False if not is_subdomain ( fqn ) : return False return True | Verify that the given fqn is a subdomain | 45 | 12 |
224,587 | def check_block ( block_id ) : if type ( block_id ) not in [ int , long ] : return False if BLOCKSTACK_TEST : if block_id <= 0 : return False else : if block_id < FIRST_BLOCK_MAINNET : return False if block_id > 1e7 : # 1 million blocks? not in my lifetime return False return True | Verify that a block ID is valid | 85 | 8 |
224,588 | def check_offset ( offset , max_value = None ) : if type ( offset ) not in [ int , long ] : return False if offset < 0 : return False if max_value and offset > max_value : return False return True | Verify that an offset is valid | 51 | 7 |
224,589 | def check_string ( value , min_length = None , max_length = None , pattern = None ) : if type ( value ) not in [ str , unicode ] : return False if min_length and len ( value ) < min_length : return False if max_length and len ( value ) > max_length : return False if pattern and not re . match ( pattern , value ) : return False return True | verify that a string has a particular size and conforms to a particular alphabet | 89 | 16 |
224,590 | def check_address ( address ) : if not check_string ( address , min_length = 26 , max_length = 35 , pattern = OP_ADDRESS_PATTERN ) : return False try : keylib . b58check_decode ( address ) return True except : return False | verify that a string is a base58check address | 63 | 11 |
224,591 | def check_account_address ( address ) : 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 ) | 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_ | 102 | 45 |
224,592 | 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 ( 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 | Verify that the list of transaction outputs are acceptable | 146 | 10 |
224,593 | def address_as_b58 ( addr ) : 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 ) ) | Given a b58check or c32check address return the b58check encoding | 66 | 16 |
224,594 | def verify ( address , plaintext , scriptSigb64 ) : 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)" ) | Verify that a given plaintext is signed by the given scriptSig given the address | 216 | 18 |
224,595 | def verify_singlesig ( address , hash_hex , 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 ) | Verify that a p2pkh address is signed by the given pay - to - pubkey - hash scriptsig | 199 | 24 |
224,596 | def verify_multisig ( address , hash_hex , 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 | verify that a p2sh address is signed by the given scriptsig | 383 | 15 |
224,597 | 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 ) : return False missing = txt_entry . split ( ',' ) try : for m in missing : m = int ( m ) except ValueError : return False return True | Does a given parsed zone file TXT record encode a missing - zonefile vector? Return True if so Return False if not | 97 | 25 |
224,598 | 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_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 ) | Does a given parsed zone file TXT record ( | 170 | 10 |
224,599 | def get_subdomain_info ( fqn , db_path = None , atlasdb_path = None , zonefiles_dir = None , check_pending = False , include_did = False ) : 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 | 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 . | 322 | 31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.