Process a Block inventory payload.

        Args:
            inventory (neo.Network.Inventory):
354343
def HandleBlockReceived(self, inventory):
        
        block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block')
        if not block:
            return

        blockhash = block.Hash.ToBytes()
        try:
            if blockhash in BC.Default().BlockRequests:
                BC.Default().BlockRequests.remove(blockhash)
        except KeyError:
            pass
        try:
            if blockhash in self.myblockrequests:
                # logger.debug(f"{self.prefix} received block: {block.Index}")
                self.heart_beat(HEARTBEAT_BLOCKS)
                self.myblockrequests.remove(blockhash)
        except KeyError:
            pass
        self.leader.InventoryReceived(block)
724965
def inventory(self):
        

        for chassis in self.chassis_list.values():
            chassis.inventory(modules_inventory=True)
1366914
def import_block(self, block: BaseBlock) -> BaseBlock:
        
        if self.block.number != block.number:
            raise ValidationError(
                "This VM can only import blocks at number #{}, the attempted block was #{}".format(
                    self.block.number,
                    block.number,
                )
            )

        self.block = self.block.copy(
            header=self.configure_header(
                coinbase=block.header.coinbase,
                gas_limit=block.header.gas_limit,
                timestamp=block.header.timestamp,
                extra_data=block.header.extra_data,
                mix_hash=block.header.mix_hash,
                nonce=block.header.nonce,
                uncles_hash=keccak(rlp.encode(block.uncles)),
            ),
            uncles=block.uncles,
        )
        # we need to re-initialize the `state` to update the execution context.
        self._state = self.build_state(self.chaindb.db, self.header, self.previous_hashes)

        # run all of the transactions.
        new_header, receipts, _ = self.apply_all_transactions(block.transactions, self.header)

        self.block = self.set_block_transactions(
            self.block,
            new_header,
            block.transactions,
            receipts,
        )

        return self.mine_block()
145805
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1):
    
    limit = limit or float('inf')
    processed = 0
    while processed < limit:
        # Change ``blpop`` to ``brpop`` to process as LIFO.
        ret = r.blpop(keys, timeout)
        # If data is found before the timeout then we consider we are done.
        if ret is None:
            time.sleep(wait)
            continue

        source, data = ret
        try:
            item = json.loads(data)
        except Exception:
            logger.exception("Failed to load item:\n%r", pprint.pformat(data))
            continue

        try:
            name = item.get('name') or item.get('title')
            url = item.get('url') or item.get('link')
            logger.debug("[%s] Processing item: %s <%s>", source, name, url)
        except KeyError:
            logger.exception("[%s] Failed to process item:\n%r",
                             source, pprint.pformat(item))
            continue

        processed += 1
        if processed % log_every == 0:
            logger.info("Processed %s items", processed)
673819
def make_inventory(
    inventory_filename,
    deploy_dir=None,
    ssh_port=None,
    ssh_user=None,
    ssh_key=None,
    ssh_key_password=None,
    ssh_password=None,
):
    '''
    
    '''

    if ssh_port is not None:
        ssh_port = int(ssh_port)

    file_groupname = None

    # If we're not a valid file we assume a list of comma separated hostnames
    if not path.exists(inventory_filename):
        groups = {
            'all': inventory_filename.split(','),
        }
    else:
        groups = _get_groups_from_filename(inventory_filename)
        # Used to set all the hosts to an additional group - that of the filename
        # ie inventories/dev.py means all the hosts are in the dev group, if not present
        file_groupname = path.basename(inventory_filename).rsplit('.')[0]

    all_data = {}

    if 'all' in groups:
        all_hosts = groups.pop('all')

        if isinstance(all_hosts, tuple):
            all_hosts, all_data = all_hosts

    # Build all out of the existing hosts if not defined
    else:
        all_hosts = []
        for hosts in groups.values():
            # Groups can be a list of hosts or tuple of (hosts, data)
            hosts = hosts[0] if isinstance(hosts, tuple) else hosts

            for host in hosts:
                # Hosts can be a hostname or tuple of (hostname, data)
                hostname = host[0] if isinstance(host, tuple) else host

                if hostname not in all_hosts:
                    all_hosts.append(hostname)

    groups['all'] = (all_hosts, all_data)

    # Apply the filename group if not already defined
    if file_groupname and file_groupname not in groups:
        groups[file_groupname] = all_hosts

    # In pyinfra an inventory is a combination of (hostnames + data). However, in CLI
    # mode we want to be define this in separate files (inventory / group data). The
    # issue is we want inventory access within the group data files - but at this point
    # we're not ready to make an Inventory. So here we just create a fake one, and
    # attach it to pseudo_inventory while we import the data files.
    logger.debug('Creating fake inventory...')

    fake_groups = {
        # In API mode groups *must* be tuples of (hostnames, data)
        name: group if isinstance(group, tuple) else (group, {})
        for name, group in six.iteritems(groups)
    }
    fake_inventory = Inventory((all_hosts, all_data), **fake_groups)
    pseudo_inventory.set(fake_inventory)

    # Get all group data (group_data/*.py)
    group_data = _get_group_data(deploy_dir)

    # Reset the pseudo inventory
    pseudo_inventory.reset()

    # For each group load up any data
    for name, hosts in six.iteritems(groups):
        data = {}

        if isinstance(hosts, tuple):
            hosts, data = hosts

        if name in group_data:
            data.update(group_data.pop(name))

        # Attach to group object
        groups[name] = (hosts, data)

    # Loop back through any leftover group data and create an empty (for now)
    # group - this is because inventory @connectors can attach arbitrary groups
    # to hosts, so we need to support that.
    for name, data in six.iteritems(group_data):
        groups[name] = ([], data)

    return Inventory(
        groups.pop('all'),
        ssh_user=ssh_user,
        ssh_key=ssh_key,
        ssh_key_password=ssh_key_password,
        ssh_port=ssh_port,
        ssh_password=ssh_password,
        **groups
    ), file_groupname and file_groupname.lower()
173097
def handle_inv(self, message_header, inv_packet ):
        
        log.debug("handle inv of %s item(s)" % len(inv_packet.inventory))

        reply_inv = []

        for inv_info in inv_packet.inventory:
            inv_hash = "%064x" % inv_info.inv_hash
            if inv_info.inv_type == INVENTORY_TYPE["MSG_BLOCK"]:
                # only ask for the block if we need it
                if inv_hash in self.block_info.keys() and not self.block_info[inv_hash]['handled']:
                    log.debug("Will request block %s" % inv_hash)
                    reply_inv.append( inv_info )
                    inv_hash = None


        if len(reply_inv) > 0:
            getdata = GetData()
            getdata.inventory = reply_inv
            log.debug("send GetData in reply to Inv for %s item(s)" % len(reply_inv))
            self.send_message(getdata)

        else:
            if self.have_all_block_data():
                self.loop_exit()
604757
def _inventory(self):
        
        if self.dynamic_version_of:
            return self.dynamic_version_of._inventory

        if not hasattr(self, '_inventory_field'):
            self._inventory_field = limpyd_fields.SetField()
            self._inventory_field._attach_to_model(self._model)
            self._inventory_field._attach_to_instance(self._instance)
            self._inventory_field.lockable = True
            self._inventory.name = self.name

        return self._inventory_field
767785
def inventory(self):
        

        self.m_info = self.get_attributes()
        if 'NOTCFP' in self.m_info['m_cfptype']:
            a = self.get_attribute('m_portcount')
            m_portcount = int(a)
        else:
            m_portcount = int(self.get_attribute('m_cfpconfig').split()[0])
        for p_index in range(m_portcount):
            XenaPort(parent=self, index='{}/{}'.format(self.index, p_index)).inventory()
851998
def processDatasetBlocks(self, url, conn, inputdataset, order_counter):
        
        ordered_dict = {}
        srcblks = self.getSrcBlocks(url, dataset=inputdataset)
        if len(srcblks) < 0:
            e = "DBSMigration: No blocks in the required dataset %s found at source %s."%(inputdataset, url)
            dbsExceptionHandler('dbsException-invalid-input2', e, self.logger.exception, e)
        dstblks = self.blocklist.execute(conn, dataset=inputdataset)
	self.logger.debug("******* dstblks for dataset %s ***********" %inputdataset)
	self.logger.debug(dstblks)
        blocksInSrcNames = [ y['block_name'] for y in srcblks]
	blocksInDstNames = []
	for item in dstblks:
	    blocksInDstNames.append(item['block_name'])
        ordered_dict[order_counter] = []
        for ablk in blocksInSrcNames:
            if not ablk in blocksInDstNames:
                ordered_dict[order_counter].append(ablk)
        if ordered_dict[order_counter] != []:
	    self.logger.debug("**** ordered_dict dict length ****")
	    self.logger.debug(len(ordered_dict)) 	
            return ordered_dict
        else:
            return {}
1337059
def manage_inventory(self):
        
        self._write_inventory()
        self._remove_vars()
        if not self.links:
            self._add_or_update_vars()
        else:
            self._link_or_update_vars()
87433
def load_inventory_from_cache(self):
        '''  '''

        cache = open(self.cache_path_cache, 'r')
        json_inventory = cache.read()
        self.inventory = json.loads(json_inventory)
1018634
def invert_inventory(inventory):
    

    inverted = dict()
    for binding, items in inventory.iteritems():
        for item in items:
            if isinstance(item, dict):
                item = item.keys()[0]
            item = str(item)  # Key may be number

            if item in inverted:
                echo("Warning: Duplicate item found, "
                     "for \"%s: %s\"" % (binding, item))
                continue
            inverted[item] = binding

    return inverted
615529
def HandleInvMessage(self, payload):
        

        if self.sync_mode != MODE_MAINTAIN:
            return

        inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')
        if not inventory:
            return

        if inventory.Type == InventoryType.BlockInt:

            ok_hashes = []
            for hash in inventory.Hashes:
                hash = hash.encode('utf-8')
                if hash not in self.myblockrequests and hash not in BC.Default().BlockRequests:
                    ok_hashes.append(hash)
                    BC.Default().BlockRequests.add(hash)
                    self.myblockrequests.add(hash)
            if len(ok_hashes):
                message = Message("getdata", InvPayload(InventoryType.Block, ok_hashes))
                self.SendSerializedMessage(message)

        elif inventory.Type == InventoryType.TXInt:
            pass
        elif inventory.Type == InventoryType.ConsensusInt:
            pass
1231690
@Override
	protected void checkHandle(int handle) throws DataStoreException
    {
        if (handle < 0 ||
            handle >= blockCount ||
            allocatedSize[handle] == -1 ||
            (flags[handle] & FLAG_START_BLOCK) == 0)
            throw new DataStoreException("Invalid handle : "+handle);
    }
95463
def inventory(host, port, time, report_every_n_tags, antennas, tx_power,
              tari, session, mode_identifier,
              tag_population, reconnect, tag_filter_mask,
              impinj_extended_configuration,
              impinj_search_mode, impinj_reports, impinj_fixed_freq):
    """"""
    # XXX band-aid hack to provide many args to _inventory.main
    Args = namedtuple('Args', ['host', 'port', 'time', 'every_n', 'antennas',
                               'tx_power', 'tari', 'session',
                               'population', 'mode_identifier',
                               'reconnect', 'tag_filter_mask',
                               'impinj_extended_configuration',
                               'impinj_search_mode',
                               'impinj_reports',
                               'impinj_fixed_freq'])
    args = Args(host=host, port=port, time=time, every_n=report_every_n_tags,
                antennas=antennas, tx_power=tx_power,
                tari=tari, session=session, population=tag_population,
                mode_identifier=mode_identifier,
                reconnect=reconnect, tag_filter_mask=tag_filter_mask,
                impinj_extended_configuration=impinj_extended_configuration,
                impinj_search_mode=impinj_search_mode,
                impinj_reports=impinj_reports,
                impinj_fixed_freq=impinj_fixed_freq)
    logger.debug('inventory args: %s', args)
    _inventory.main(args)
637541
def ProcessNewBlock(self, block):
        
        added = set()
        changed = set()
        deleted = set()

        try:
            # go through the list of transactions in the block and enumerate
            # over their outputs
            for tx in block.FullTransactions:

                for index, output in enumerate(tx.outputs):

                    # check to see if the outputs in the tx are in this wallet
                    state = self.CheckAddressState(output.ScriptHash)

                    if state & AddressState.InWallet > 0:

                        # if it's in the wallet, check to see if the coin exists yet
                        key = CoinReference(tx.Hash, index)

                        # if it exists, update it, otherwise create a new one
                        if key in self._coins.keys():
                            coin = self._coins[key]
                            coin.State |= CoinState.Confirmed
                            changed.add(coin)
                        else:
                            newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx)
                            self._coins[key] = newcoin
                            added.add(newcoin)

                        if state & AddressState.WatchOnly > 0:
                            self._coins[key].State |= CoinState.WatchOnly
                            changed.add(self._coins[key])

            # now iterate over the inputs of the tx and do the same
            for tx in block.FullTransactions:

                for input in tx.inputs:

                    if input in self._coins.keys():
                        if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash:
                            coin = self._coins[input]
                            coin.State |= CoinState.Spent | CoinState.Confirmed
                            changed.add(coin)

                        else:
                            deleted.add(self._coins[input])
                            del self._coins[input]

            for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:

                for ref in claimTx.Claims:
                    if ref in self._coins.keys():
                        deleted.add(self._coins[ref])
                        del self._coins[ref]

            # update the current height of the wallet
            self._current_height += 1

            # in the case that another wallet implementation needs to do something
            # with the coins that have been changed ( ie persist to db ) this
            # method is called
            self.OnProcessNewBlock(block, added, changed, deleted)

            # this is not necessary at the moment, but any outside process
            # that wants to subscribe to the balance changed event could do
            # so from the BalanceChanged method
            if len(added) + len(deleted) + len(changed) > 0:
                self.BalanceChanged()

        except Exception as e:
            traceback.print_stack()
            traceback.print_exc()
            logger.error("could not process %s " % e)
834533
def do_blockrep(self, line):
        """"""
        mns = self._split_args(line, 1, -1)
        self._command_processor.get_session().get_replication_policy().add_blocked(mns)
        self._print_info_if_verbose(
            "Set {} as blocked replication target(s)".format(", ".join(mns))
        )