INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Verify the validity of a registration nameop. * the name must be well-formed * the namespace must be ready * the name does not collide * the name was preordered by the same sender as the last preorder * the Bitcoin or Stacks fee paid by the preorder must be high enough (for some namespace-version-sp...
def check_register( state_engine, nameop, block_id, checked_ops ): """ Verify the validity of a registration nameop. * the name must be well-formed * the namespace must be ready * the name does not collide * the name was preordered by the same sender as the last preorder * the Bitcoin or Sta...
Verify the validity of a renewal nameop. * the name must be well-formed * the namespace must be ready * the request must be sent by the owner. * the mining fee must be high enough. * the name must not be expired Return True if accepted. Return False if not.
def check_renewal( state_engine, nameop, block_id, checked_ops ): """ Verify the validity of a renewal nameop. * the name must be well-formed * the namespace must be ready * the request must be sent by the owner. * the mining fee must be high enough. * the name must not be expired Retur...
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 recipient: t...
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 name. The first three bytes (2 magic + 1 opcode) will not be present in bin_payload. The name will be directly represented by the bytes given. This works for registrations and renewals. Record format (pre F-day 2017): 0 2 3 ...
def parse(bin_payload, block_height): """ Interpret a block's nulldata back into a name. The first three bytes (2 magic + 1 opcode) will not be present in bin_payload. The name will be directly represented by the bytes given. This works for registrations and renewals. Record format (pre...
Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not.
def check( state_engine, nameop, block_id, checked_ops ): """ Given a NAMESPACE_PREORDER nameop, see if we can preorder it. It must be unqiue. Return True if accepted. Return False if not. """ namespace_id_hash = nameop['preorder_hash'] consensus_hash = nameop['consensus_hash'] tok...
Given the set of outputs, find the fee sent to our burn address. Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...} Return None if not found
def get_namespace_preorder_burn_info( outputs ): """ Given the set of outputs, find the fee sent to our burn address. Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...} Return None if not found """ if len(outputs) < 3: # not a well-formed preorde...
NOTE: the first three bytes will be missing wire format (Pre-STACKs Phase 1) 0 2 3 23 39 |-----|---|--------------------------------------|----------------| magic op hash(ns_id,script_pubkey,reveal_addr) consensus hash wire format (Post...
def parse( bin_payload, block_height ): """ NOTE: the first three bytes will be missing wire format (Pre-STACKs Phase 1) 0 2 3 23 39 |-----|---|--------------------------------------|----------------| magic op hash(ns_id,script_pubkey,...
Read the last 8 bytes of fd and interpret it as an int.
def snapshot_peek_number( fd, off ): """ Read the last 8 bytes of fd and interpret it as an int. """ # read number of 8 bytes fd.seek( off - 8, os.SEEK_SET ) value_hex = fd.read(8) if len(value_hex) != 8: return None try: value = int(value_hex, 16) except ValueEr...
Read the last :bytelen bytes of fd and interpret it as a base64-encoded string
def snapshot_peek_sigb64( fd, off, bytelen ): """ Read the last :bytelen bytes of fd and interpret it as a base64-encoded string """ fd.seek( off - bytelen, os.SEEK_SET ) sigb64 = fd.read(bytelen) if len(sigb64) != bytelen: return None try: base64.b64decode(sigb64) ...
Get the hex-encoded hash of the fd's data
def get_file_hash( fd, hashfunc, fd_len=None ): """ Get the hex-encoded hash of the fd's data """ h = hashfunc() fd.seek(0, os.SEEK_SET) count = 0 while True: buf = fd.read(65536) if len(buf) == 0: break if fd_len is not None: if count + len...
Append a signature to the end of a snapshot path with the given private key. If first is True, then don't expect the signature trailer. Return True on success Return False on error
def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ): """ Append a signature to the end of a snapshot path with the given private key. If first is True, then don't expect the signature trailer. Return True on success Return False on error """ if not os.path.exists...
Given the path to a directory, compress it and export it to the given path. Return {'status': True} on success Return {'error': ...} on failure
def fast_sync_snapshot_compress( snapshot_dir, export_path ): """ Given the path to a directory, compress it and export it to the given path. Return {'status': True} on success Return {'error': ...} on failure """ snapshot_dir = os.path.abspath(snapshot_dir) export_path = os.path.abspa...
Given the path to a snapshot file, decompress it and write its contents to the given output directory Return {'status': True} on success Return {'error': ...} on failure
def fast_sync_snapshot_decompress( snapshot_path, output_dir ): """ Given the path to a snapshot file, decompress it and write its contents to the given output directory Return {'status': True} on success Return {'error': ...} on failure """ if not tarfile.is_tarfile(snapshot_path): ...
Export all the local state for fast-sync. If block_number is given, then the name database at that particular block number will be taken. The exported tarball will be signed with the given private key, and the signature will be appended to the end of the file. Return True if we succeed Return ...
def fast_sync_snapshot(working_dir, export_path, private_key, block_number ): """ Export all the local state for fast-sync. If block_number is given, then the name database at that particular block number will be taken. The exported tarball will be signed with the given private key, and the sig...
Get the data for an import snapshot. Store it to a temporary path Return the path on success Return None on error
def fast_sync_fetch(working_dir, import_url): """ Get the data for an import snapshot. Store it to a temporary path Return the path on success Return None on error """ try: fd, tmppath = tempfile.mkstemp(prefix='.blockstack-fast-sync-', dir=working_dir) except Exception, e: ...
Inspect a snapshot, given its file descriptor. Get the signatures and payload size Return {'status': True, 'signatures': signatures, 'payload_size': payload size, 'sig_append_offset': offset} on success Return {'error': ...} on error
def fast_sync_inspect( fd ): """ Inspect a snapshot, given its file descriptor. Get the signatures and payload size Return {'status': True, 'signatures': signatures, 'payload_size': payload size, 'sig_append_offset': offset} on success Return {'error': ...} on er...
Inspect a snapshot Return useful information Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success Return {'error': ...} on error
def fast_sync_inspect_snapshot( snapshot_path ): """ Inspect a snapshot Return useful information Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success Return {'error': ...} on error """ with open(snapshot_path, 'r') as f: i...
Fast sync import. Verify the given fast-sync file from @import_path using @public_key, and then uncompress it into @working_dir. Verify that at least `num_required` public keys in `public_keys` signed. NOTE: `public_keys` needs to be in the same order as the private keys that signed.
def fast_sync_import(working_dir, import_url, public_keys=config.FAST_SYNC_PUBLIC_KEYS, num_required=len(config.FAST_SYNC_PUBLIC_KEYS), verbose=False): """ Fast sync import. Verify the given fast-sync file from @import_path using @public_key, and then uncompress it into @working_dir. Verify that a...
Restore the database from a backup in the backups/ directory. If block_number is None, then use the latest backup. NOT THREAD SAFE Return True on success Raise an exception on error
def blockstack_backup_restore(working_dir, block_number): """ Restore the database from a backup in the backups/ directory. If block_number is None, then use the latest backup. NOT THREAD SAFE Return True on success Raise an exception on error """ db = BlockstackDB.get_readwrite_instan...
See that there are no state-creating or state-preordering collisions at this block, for this history ID. Return True if collided; False if not
def state_check_collisions( state_engine, nameop, history_id_key, block_id, checked_ops, collision_checker ): """ See that there are no state-creating or state-preordering collisions at this block, for this history ID. Return True if collided; False if not """ # verify no collisions against already...
Decorator for the check() method on a state-preordering operation. Make sure that there are no duplicate preorders anywhere--either in this block, or in any previous blocks.
def state_preorder(collision_checker): """ Decorator for the check() method on a state-preordering operation. Make sure that there are no duplicate preorders anywhere--either in this block, or in any previous blocks. """ def wrap( check ): def wrapped_check( state_engine, nameop, block_i...
Decorator for the check() method on state-creating operations. Makes sure that: * there is a __preorder__ field set, which contains the state-creating operation's associated preorder * there is a __table__ field set, which contains the table into which to insert this state into * there is a __history_id...
def state_create(history_id_key, table_name, collision_checker, always_set=[]): """ Decorator for the check() method on state-creating operations. Makes sure that: * there is a __preorder__ field set, which contains the state-creating operation's associated preorder * there is a __table__ field set,...
Decorator for the check() method on state-transition operations. Make sure that: * there is a __table__ field set, which names the table in which this record is stored. * there is a __history_id_key__ field set, which identifies the table record's primary key. Any fields named in @always_set will alway...
def state_transition(history_id_key, table_name, always_set=[], may_spend_tokens=False): """ Decorator for the check() method on state-transition operations. Make sure that: * there is a __table__ field set, which names the table in which this record is stored. * there is a __history_id_key__ field ...
Decorator for the check() method on token operations. Make sure that there is a __account_payment_info__ and __account_credit_info__ set.
def token_operation(table_name): """ Decorator for the check() method on token operations. Make sure that there is a __account_payment_info__ and __account_credit_info__ set. """ def wrap( check ): def wrapped_check( state_engine, token_op, block_id, checked_ops ): rc = check( st...
Call this in a @state_create-decorated method. Identifies the account that must be debited.
def state_preorder_put_account_payment_info( nameop, account_addr, token_type, amount ): """ Call this in a @state_create-decorated method. Identifies the account that must be debited. """ assert amount is None or isinstance(amount, (int,long)), 'Amount is {} (type {})'.format(amount, type(amount)) ...
Is a nameop a valid state-preorder operation?
def state_create_is_valid( nameop ): """ Is a nameop a valid state-preorder operation? """ assert '__state_create__' in nameop, "Not tagged with @state_create" assert nameop['__state_create__'], "BUG: tagged False by @state_create" assert '__preorder__' in nameop, "No preorder" assert '__tab...
Is this a valid state transition?
def state_transition_is_valid( nameop ): """ Is this a valid state transition? """ assert '__state_transition__' in nameop, "Not tagged with @state_transition" assert nameop['__state_transition__'], "BUG: @state_transition tagged False" assert '__history_id_key__' in nameop, "Missing __history_i...
Call this in a @token_operation-decorated method. Identifies the account to be debited
def token_operation_put_account_payment_info(token_op, account_addr, token_type, amount): """ Call this in a @token_operation-decorated method. Identifies the account to be debited """ assert isinstance(amount, (int,long)), "BUG: amount is {} (type {})".format(amount, type(amount)) assert isinst...
Read and verify an atlas zone file
def _read_atlas_zonefile( zonefile_path, zonefile_hash ): """ Read and verify an atlas zone file """ with open(zonefile_path, "rb") as f: data = f.read() # sanity check if zonefile_hash is not None: if not verify_zonefile( data, zonefile_hash ): log.debug("Corrupt ...
Get a serialized cached zonefile from local disk Return None if not found
def get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=True ): """ Get a serialized cached zonefile from local disk Return None if not found """ zonefile_path = atlas_zonefile_path(zonefile_dir, zonefile_hash) zonefile_path_legacy = atlas_zonefile_path_legacy(zonefile_dir, zonefile_has...
Calculate the on-disk path to storing a zonefile's information, given the zone file hash. If the zonefile hash is abcdef1234567890, then the path will be $zonefile_dir/ab/cd/abcdef1234567890.txt Returns the path.
def atlas_zonefile_path( zonefile_dir, zonefile_hash ): """ Calculate the on-disk path to storing a zonefile's information, given the zone file hash. If the zonefile hash is abcdef1234567890, then the path will be $zonefile_dir/ab/cd/abcdef1234567890.txt Returns the path. """ # split into direc...
Calculate the *legacy* on-disk path to storing a zonefile's information, given the zonefile hash. If the zonefile hash is abcdef1234567890, then the path will be $zonefile_dir/ab/cd/ef/12/34/56/78/90/zonefile.txt This format is no longer used to create new zonefiles, since it takes a lot of inodes to store com...
def atlas_zonefile_path_legacy( zonefile_dir, zonefile_hash ): """ Calculate the *legacy* on-disk path to storing a zonefile's information, given the zonefile hash. If the zonefile hash is abcdef1234567890, then the path will be $zonefile_dir/ab/cd/ef/12/34/56/78/90/zonefile.txt This format is no longe...
Do we have the cached zonefile? It's okay if it's a non-standard zonefile. if @validate is true, then check that the data in zonefile_dir_path/zonefile.txt matches zonefile_hash Return True if so Return False if not
def is_zonefile_cached( zonefile_hash, zonefile_dir, validate=False): """ Do we have the cached zonefile? It's okay if it's a non-standard zonefile. if @validate is true, then check that the data in zonefile_dir_path/zonefile.txt matches zonefile_hash Return True if so Return False if not """ ...
Store a validated zonefile. zonefile_data should be a dict. The caller should first authenticate the zonefile. Return True on success Return False on error
def store_atlas_zonefile_data(zonefile_data, zonefile_dir, fsync=True): """ Store a validated zonefile. zonefile_data should be a dict. The caller should first authenticate the zonefile. Return True on success Return False on error """ if not os.path.exists(zonefile_dir): os.make...
Remove a cached zonefile. Idempotent; returns True if deleted or it didn't exist. Returns False on error
def remove_atlas_zonefile_data( zonefile_hash, zonefile_dir ): """ Remove a cached zonefile. Idempotent; returns True if deleted or it didn't exist. Returns False on error """ if not os.path.exists(zonefile_dir): return True zonefile_path = atlas_zonefile_path( zonefile_dir, zonefil...
Add a zone file to the atlas zonefiles Return True on success Return False on error
def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True): """ Add a zone file to the atlas zonefiles Return True on success Return False on error """ rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync) if not rc: zonefile_hash = get_zonefile_data_has...
Verify that data for a transfer is valid. Return True on success Raise Exception on error
def transfer_sanity_check( name, consensus_hash ): """ Verify that data for a transfer is valid. Return True on success Raise Exception on error """ if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1): raise Exception("Name '%s' has non-base-38 characters" ...
Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation. @name_rec is the current name record, before this NAME_TRANSFER. @block_id is the current block height. @vtxindex is the relative index of this transaction in this block. @nameop_consensus_hash is the consensus hash...
def find_transfer_consensus_hash( name_rec, block_id, vtxindex, nameop_consensus_hash ): """ Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation. @name_rec is the current name record, before this NAME_TRANSFER. @block_id is the current block height. @vtxindex is t...
Verify the validity of a name's transferrance to another private key. The name must exist, not be revoked, and be owned by the sender. The recipient must not exceed the maximum allowed number of names per keypair, and the recipient cannot own an equivalent name. NAME_TRANSFER isn't allowed during an im...
def check( state_engine, nameop, block_id, checked_ops ): """ Verify the validity of a name's transferrance to another private key. The name must exist, not be revoked, and be owned by the sender. The recipient must not exceed the maximum allowed number of names per keypair, and the recipient cannot...
Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. Required: sender: the script_pubkey (as a hex string) of the principal that sent the transfer transaction address: the address from the sender script recipient: the script_pubke...
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: sender: the script_pubkey (as a hex string) of the principal that sent the transfer tr...
# NOTE: first three bytes were stripped
def parse(bin_payload, recipient): """ # NOTE: first three bytes were stripped """ if len(bin_payload) != 1 + LENGTHS['name_hash'] + LENGTHS['consensus_hash']: log.error("Invalid transfer payload length %s" % len(bin_payload)) return None disposition_char = bin_payload[0:1] ...
Get the "canonical form" of this operation, putting it into a form where it can be serialized to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases. For NAME_TRANSFER, this means: * add 'keep_data' flag
def canonicalize(parsed_op): """ Get the "canonical form" of this operation, putting it into a form where it can be serialized to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases. For NAME_TRANSFER, this means: * add 'keep_data' flag """ ass...
Get or instantiate our bitcoind client. Optionally re-set the bitcoind options.
def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ): """ Get or instantiate our bitcoind client. Optionally re-set the bitcoind options. """ global bitcoind if reset: bitcoind = None elif not new and bitcoind is not None: return bitcoind if new or bitcoind is None:...
Get the PID file path.
def get_pidfile_path(working_dir): """ Get the PID file path. """ pid_filename = virtualchain_hooks.get_virtual_chain_name() + ".pid" return os.path.join( working_dir, pid_filename )
Put a PID into a pidfile
def put_pidfile( pidfile_path, pid ): """ Put a PID into a pidfile """ with open( pidfile_path, "w" ) as f: f.write("%s" % pid) os.fsync(f.fileno()) return
Get the logfile path for our service endpoint.
def get_logfile_path(working_dir): """ Get the logfile path for our service endpoint. """ logfile_filename = virtualchain_hooks.get_virtual_chain_name() + ".log" return os.path.join( working_dir, logfile_filename )
Get the bitcoin block index range. Mask connection failures with timeouts. Always try to reconnect. The last block will be the last block to search for names. This will be NUM_CONFIRMATIONS behind the actual last-block the cryptocurrency node knows about.
def get_index_range(working_dir): """ Get the bitcoin block index range. Mask connection failures with timeouts. Always try to reconnect. The last block will be the last block to search for names. This will be NUM_CONFIRMATIONS behind the actual last-block the cryptocurrency node knows abou...
Get the cost of a name, given the fully-qualified name. Do so by finding the namespace it belongs to (even if the namespace is being imported). Return {'amount': ..., 'units': ...} on success Return None if the namespace has not been declared
def get_name_cost( db, name ): """ Get the cost of a name, given the fully-qualified name. Do so by finding the namespace it belongs to (even if the namespace is being imported). Return {'amount': ..., 'units': ...} on success Return None if the namespace has not been declared """ lastblock...
Get the cost of a namespace. Returns {'amount': ..., 'units': ..., 'namespace': ...}
def get_namespace_cost( db, namespace_id ): """ Get the cost of a namespace. Returns {'amount': ..., 'units': ..., 'namespace': ...} """ lastblock = db.lastblock namespace_units = get_epoch_namespace_price_units(lastblock) namespace_fee = price_namespace( namespace_id, lastblock, namespace_u...
Start the global RPC server thread Returns the RPC server thread
def rpc_start( working_dir, port, subdomain_index=None, thread=True ): """ Start the global RPC server thread Returns the RPC server thread """ rpc_srv = BlockstackdRPCServer( working_dir, port, subdomain_index=subdomain_index ) log.debug("Starting RPC on port {}".format(port)) if thread: ...
Flush the global RPC server cache, and tell the rpc server that we've reached the given block height at the given time.
def rpc_chain_sync(server_state, new_block_height, finish_time): """ Flush the global RPC server cache, and tell the rpc server that we've reached the given block height at the given time. """ rpc_srv = server_state['rpc'] if rpc_srv is not None: rpc_srv.cache_flush() rpc_srv.set...
Stop the global RPC server thread
def rpc_stop(server_state): """ Stop the global RPC server thread """ rpc_srv = server_state['rpc'] if rpc_srv is not None: log.info("Shutting down RPC") rpc_srv.stop_server() rpc_srv.join() log.info("RPC joined") else: log.info("RPC already joined") ...
Stop a the optimistic GC thread
def gc_stop(): """ Stop a the optimistic GC thread """ global gc_thread if gc_thread: log.info("Shutting down GC thread") gc_thread.signal_stop() gc_thread.join() log.info("GC thread joined") gc_thread = None else: log.info("GC thread already ...
Start the global API server Returns the API server thread
def api_start(working_dir, host, port, thread=True): """ Start the global API server Returns the API server thread """ api_srv = BlockstackdAPIServer( working_dir, host, port ) log.info("Starting API server on port {}".format(port)) if thread: api_srv.start() return api_srv
Stop the global API server thread
def api_stop(server_state): """ Stop the global API server thread """ api_srv = server_state['api'] if api_srv is not None: log.info("Shutting down API") api_srv.stop_server() api_srv.join() log.info("API server joined") else: log.info("API already joined...
Start up atlas functionality
def atlas_init(blockstack_opts, db, recover=False, port=None): """ Start up atlas functionality """ if port is None: port = blockstack_opts['rpc_port'] # start atlas node atlas_state = None if is_atlas_enabled(blockstack_opts): atlas_seed_peers = filter( lambda x: len(x) > 0...
Read the PID from the PID file
def read_pid_file(pidfile_path): """ Read the PID from the PID file """ try: fin = open(pidfile_path, "r") except Exception, e: return None else: pid_data = fin.read().strip() fin.close() try: pid = int(pid_data) return pid ...
Stop the blockstackd server.
def stop_server( working_dir, clean=False, kill=False ): """ Stop the blockstackd server. """ timeout = 1.0 dead = False for i in xrange(0, 5): # try to kill the main supervisor pid_file = get_pidfile_path(working_dir) if not os.path.exists(pid_file): dead =...
Virtualchain tx filter function: * only take txs whose OP_RETURN payload starts with 'id'
def blockstack_tx_filter( tx ): """ Virtualchain tx filter function: * only take txs whose OP_RETURN payload starts with 'id' """ if not 'nulldata' in tx: return False if tx['nulldata'] is None: return False payload = binascii.unhexlify( tx['nulldata'] ) if payload....
Determine if the given process is running
def check_server_running(pid): """ Determine if the given process is running """ if pid == os.getpid(): # special case--we're in Docker or some other kind of container # (or we got really unlucky and got the same PID twice). # this PID does not correspond to another running serve...
Index the blockchain: * find the range of blocks * synchronize our state engine up to them Return True if we should continue indexing Return False if not Aborts on error
def index_blockchain(server_state, expected_snapshots=GENESIS_SNAPSHOT): """ Index the blockchain: * find the range of blocks * synchronize our state engine up to them Return True if we should continue indexing Return False if not Aborts on error """ working_dir = server_state['work...
Make sure the genesis block is good to go. Load and instantiate it.
def genesis_block_load(module_path=None): """ Make sure the genesis block is good to go. Load and instantiate it. """ if os.environ.get('BLOCKSTACK_GENESIS_BLOCK_PATH') is not None: log.warning('Using envar-given genesis block') module_path = os.environ['BLOCKSTACK_GENESIS_BLOCK_PATH...
Shut down server subsystems. Remove PID file.
def server_shutdown(server_state): """ Shut down server subsystems. Remove PID file. """ set_running( False ) # stop API servers rpc_stop(server_state) api_stop(server_state) # stop atlas node server_atlas_shutdown(server_state) # stopping GC gc_stop() # clear PID...
Run blockstackd. Optionally daemonize. Return 0 on success Return negative on error
def run_server(working_dir, foreground=False, expected_snapshots=GENESIS_SNAPSHOT, port=None, api_port=None, use_api=None, use_indexer=None, indexer_url=None, recover=False): """ Run blockstackd. Optionally daemonize. Return 0 on success Return negative on error """ global rpc_server global...
Do one-time initialization. Call this to set up global state.
def setup(working_dir, interactive=False): """ Do one-time initialization. Call this to set up global state. """ # set up our implementation log.debug("Working dir: {}".format(working_dir)) if not os.path.exists( working_dir ): os.makedirs( working_dir, 0700 ) node_config = load...
Reconfigure blockstackd.
def reconfigure(working_dir): """ Reconfigure blockstackd. """ configure(working_dir, force=True, interactive=True) print "Blockstack successfully reconfigured." sys.exit(0)
Verify that a database is consistent with a known-good consensus hash. Return True if valid. Return False if not
def verify_database(trusted_consensus_hash, consensus_block_height, untrusted_working_dir, trusted_working_dir, start_block=None, expected_snapshots={}): """ Verify that a database is consistent with a known-good consensus hash. Return True if valid. Return False if not """ db = BlockstackDB...
Go through argv and find any special command-line flags that set environment variables that affect multiple modules. If any of them are given, then set them in this process's environment and re-exec the process without the CLI flags. argv should be like sys.argv: argv[0] is the binary Does not r...
def check_and_set_envars( argv ): """ Go through argv and find any special command-line flags that set environment variables that affect multiple modules. If any of them are given, then set them in this process's environment and re-exec the process without the CLI flags. argv should be like sy...
Load expected consensus hashes from a .snapshots file. Return the snapshots as a dict on success Return None on error
def load_expected_snapshots( snapshots_path ): """ Load expected consensus hashes from a .snapshots file. Return the snapshots as a dict on success Return None on error """ # use snapshots? snapshots_path = os.path.expanduser(snapshots_path) expected_snapshots = {} # legacy chainsta...
Loads and audits the genesis block, optionally using an alternative key
def do_genesis_block_audit(genesis_block_path=None, key_id=None): """ Loads and audits the genesis block, optionally using an alternative key """ signing_keys = GENESIS_BLOCK_SIGNING_KEYS if genesis_block_path is not None: # alternative genesis block genesis_block_load(genesis_block_...
Set up the recovery metadata so we can fully recover secondary state, like subdomains.
def setup_recovery(working_dir): """ Set up the recovery metadata so we can fully recover secondary state, like subdomains. """ db = get_db_state(working_dir) bitcoind_session = get_bitcoind(new=True) assert bitcoind_session is not None _, current_block = virtualchain.get_index_range('b...
Do we need to recover on start-up?
def check_recovery(working_dir): """ Do we need to recover on start-up? """ recovery_start_block, recovery_end_block = get_recovery_range(working_dir) if recovery_start_block is not None and recovery_end_block is not None: local_current_block = virtualchain_hooks.get_last_block(working_dir) ...
run blockstackd
def run_blockstackd(): """ run blockstackd """ special_args, new_argv = check_and_set_envars( sys.argv ) working_dir = special_args.get('working_dir') if working_dir is None: working_dir = os.path.expanduser('~/.{}'.format(virtualchain_hooks.get_virtual_chain_name())) # if w...
Got too many requests. Send back a (precompiled) XMLRPC response saying as much
def overloaded(self, client_address): """ Got too many requests. Send back a (precompiled) XMLRPC response saying as much """ body = { 'status': False, 'indexing': False, 'lastblock': -1, 'error': 'overloaded', 'http_sta...
Make a standard "success" response, which contains some ancilliary data. Also, detect if this node is too far behind the Bitcoin blockchain, and if so, convert this into an error message.
def success_response(self, method_resp, **kw): """ Make a standard "success" response, which contains some ancilliary data. Also, detect if this node is too far behind the Bitcoin blockchain, and if so, convert this into an error message. """ resp = { ...
sanitize a name/namespace record before returning it. * canonicalize it * remove quirk fields
def sanitize_rec(self, rec): """ sanitize a name/namespace record before returning it. * canonicalize it * remove quirk fields """ opcode = rec['opcode'] canonical_op = op_canonicalize(opcode, rec) # don't return internally-used quirk fields quirk...
Get some extra name information, given a db-loaded name record. Return the updated name_record
def load_name_info(self, db, name_record): """ Get some extra name information, given a db-loaded name record. Return the updated name_record """ name = str(name_record['name']) name_record = self.sanitize_rec(name_record) namespace_id = get_namespace_from_name(n...
Get the whois-related info for a name (not a subdomain). Optionally include the history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error
def get_name_record(self, name, include_expired=False, include_history=False): """ Get the whois-related info for a name (not a subdomain). Optionally include the history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ if not ...
Get the whois-related info for a subdomain. Optionally include the history for the domain. Return {'status': True, 'record': rec} on success Return {'error': ...} on error
def get_subdomain_record(self, fqn, include_history=False): """ Get the whois-related info for a subdomain. Optionally include the history for the domain. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ if not check_subdomain(f...
Get the curernt state of a name or subdomain, excluding its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error
def rpc_get_name_record(self, name, **con_info): """ Get the curernt state of a name or subdomain, excluding its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ res = None if check_name(name): res = self.ge...
Get a name's DID info Returns None if not found
def get_name_DID_info(self, name): """ Get a name's DID info Returns None if not found """ db = get_db_state(self.working_dir) did_info = db.get_name_DID_info(name) if did_info is None: return {'error': 'No such name', 'http_status': 404} retu...
Given a name or subdomain, return its DID.
def rpc_get_name_DID(self, name, **con_info): """ Given a name or subdomain, return its DID. """ did_info = None if check_name(name): did_info = self.get_name_DID_info(name) elif check_subdomain(name): did_info = self.get_subdomain_DID_info(name) ...
Given a DID for a name, return the name record. Return {'record': ...} on success Return {'error': ...} on error
def get_name_DID_record(self, did): """ Given a DID for a name, return the name record. Return {'record': ...} on success Return {'error': ...} on error """ try: did_info = parse_DID(did) assert did_info['name_type'] == 'name' except Except...
Given a DID for subdomain, get the subdomain record Return {'record': ...} on success Return {'error': ...} on error
def get_subdomain_DID_record(self, did): """ Given a DID for subdomain, get the subdomain record Return {'record': ...} on success Return {'error': ...} on error """ try: did_info = parse_DID(did) assert did_info['name_type'] == 'subdomain' ...
Lookup all blockchain state for a name or subdomain, including its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error
def rpc_get_name_blockchain_record(self, name, **con_info): """ Lookup all blockchain state for a name or subdomain, including its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ res = None if check_name(name): ...
Given a DID, return the name or subdomain it corresponds to
def rpc_get_DID_record(self, did, **con_info): """ Given a DID, return the name or subdomain it corresponds to """ if not isinstance(did, (str,unicode)): return {'error': 'Invalid DID: not a string', 'http_status': 400} try: did_info = parse_DID(did) ...
Get the list of history entries for a name or subdomain's history, paginated. Small pages correspond to later history (page = 0 is the page of last updates) Page size is 20 rows. Return {'status': True, 'history': [...]} on success Return {'error': ...} on error
def rpc_get_name_history_page(self, name, page, **con_info): """ Get the list of history entries for a name or subdomain's history, paginated. Small pages correspond to later history (page = 0 is the page of last updates) Page size is 20 rows. Return {'status': True, 'history': [...
Was a zone file hash issued by a name? Return {'result': True/False}
def rpc_is_name_zonefile_hash(self, name, zonefile_hash, **con_info): """ Was a zone file hash issued by a name? Return {'result': True/False} """ if not check_name(name) and not check_subdomain(name): return {'error': 'invalid name', 'http_status': 400} if not chec...
Get all the states the name was in at a particular block height. Does NOT work on expired names. Return {'status': true, 'record': ...}
def rpc_get_name_at( self, name, block_height, **con_info ): """ Get all the states the name was in at a particular block height. Does NOT work on expired names. Return {'status': true, 'record': ...} """ if not check_name(name): return {'error': 'invalid name...
Get the number of Blockstack transactions that occured at the given block. Returns {'count': ..} on success Returns {'error': ...} on error
def rpc_get_num_blockstack_ops_at(self, block_id, **con_info): """ Get the number of Blockstack transactions that occured at the given block. Returns {'count': ..} on success Returns {'error': ...} on error """ if not check_block(block_id): return {'error': 'I...
Get the name operations that occured in the given block. Does not include account operations. Returns {'nameops': [...]} on success. Returns {'error': ...} on error
def rpc_get_blockstack_ops_at(self, block_id, offset, count, **con_info): """ Get the name operations that occured in the given block. Does not include account operations. Returns {'nameops': [...]} on success. Returns {'error': ...} on error """ if not check_blo...
Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error
def rpc_get_blockstack_ops_hash_at( self, block_id, **con_info ): """ Get the hash over the sequence of names and namespaces altered at the given block. Used by SNV clients. Returns {'status': True, 'ops_hash': ops_hash} on success Returns {'error': ...} on error """ ...
Get cached bitcoind info. Returns {...} on success Return None if it is stale
def get_cached_bitcoind_info(self): """ Get cached bitcoind info. Returns {...} on success Return None if it is stale """ cached_bitcoind_info = self.cache.get('bitcoind_info', None) if cached_bitcoind_info is None: # not cached return None...
Get cached consensus info. Returns {...} on success Return None if it is stale
def get_cached_consensus_info(self): """ Get cached consensus info. Returns {...} on success Return None if it is stale """ cached_consensus_info = self.cache.get('consensus_info', None) if cached_consensus_info is None: # not cached return...
Get bitcoind info. Try the cache, and on cache miss, fetch from bitcoind and cache.
def get_bitcoind_info(self): """ Get bitcoind info. Try the cache, and on cache miss, fetch from bitcoind and cache. """ cached_bitcoind_info = self.get_cached_bitcoind_info() if cached_bitcoind_info: return cached_bitcoind_info bitcoind_opts = defa...
Get block height and consensus hash. Try the cache, and on cache miss, fetch from the db
def get_consensus_info(self): """ Get block height and consensus hash. Try the cache, and on cache miss, fetch from the db """ cached_consensus_info = self.get_cached_consensus_info() if cached_consensus_info: return cached_consensus_info db = get_db...
Get information from the running server: * last_block_seen: the last block height seen * consensus: the consensus hash for that block * server_version: the server version * last_block_processed: the last block processed * server_alive: True * [optional] zonefile_count: th...
def rpc_getinfo(self, **con_info): """ Get information from the running server: * last_block_seen: the last block height seen * consensus: the consensus hash for that block * server_version: the server version * last_block_processed: the last block processed * ser...
Get the list of subdomains owned by an address. Return {'status': True, 'subdomains': ...} on success Return {'error': ...} on error
def rpc_get_subdomains_owned_by_address(self, address, **con_info): """ Get the list of subdomains owned by an address. Return {'status': True, 'subdomains': ...} on success Return {'error': ...} on error """ if not check_address(address): return {'error': 'In...
Get the list of names owned by an address. Return {'status': True, 'names': ...} on success Return {'error': ...} on error
def rpc_get_names_owned_by_address(self, address, **con_info): """ Get the list of names owned by an address. Return {'status': True, 'names': ...} on success Return {'error': ...} on error """ if not check_address(address): return {'error': 'Invalid address',...
Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error
def rpc_get_historic_names_by_address(self, address, offset, count, **con_info): """ Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error """ ...