Build and verify the chain of trust.

    Args:
        chain (ChainOfTrust): the chain we're operating on

    Raises:
        CoTError: on failure
493600
async def verify_chain_of_trust(chain):
    
    log_path = os.path.join(chain.context.config["task_log_dir"], "chain_of_trust.log")
    scriptworker_log = logging.getLogger('scriptworker')
    with contextual_log_handler(
        chain.context, path=log_path, log_obj=scriptworker_log,
        formatter=AuditLogFormatter(
            fmt=chain.context.config['log_fmt'],
            datefmt=chain.context.config['log_datefmt'],
        )
    ):
        try:
            # build LinkOfTrust objects
            await build_task_dependencies(chain, chain.task, chain.name, chain.task_id)
            # download the signed chain of trust artifacts
            await download_cot(chain)
            # verify the signatures and populate the ``link.cot``s
            verify_cot_signatures(chain)
            # download all other artifacts needed to verify chain of trust
            await download_cot_artifacts(chain)
            # verify the task types, e.g. decision
            task_count = await verify_task_types(chain)
            check_num_tasks(chain, task_count)
            # verify the worker_impls, e.g. docker-worker
            await verify_worker_impls(chain)
            await trace_back_to_tree(chain)
        except (BaseDownloadError, KeyError, AttributeError) as exc:
            log.critical("Chain of Trust verification error!", exc_info=True)
            if isinstance(exc, CoTError):
                raise
            else:
                raise CoTError(str(exc))
        log.info("Good.")
728861
def broadcast_transaction(hex_tx, blockchain_client):
    
    if not isinstance(blockchain_client, ChainComClient):
        raise Exception('A ChainComClient object is required')

    auth = blockchain_client.auth
    if not auth or len(auth) != 2:
        raise Exception('ChainComClient object must have auth credentials.')

    url = CHAIN_API_BASE_URL + '/bitcoin/transactions/send'
    payload = json.dumps({ 'signed_hex': hex_tx })
    r = requests.post(url, data=payload, auth=auth)

    try:
        data = r.json()
    except ValueError, e:
        raise Exception('Received non-JSON from chain.com.')

    if 'transaction_hash' in data:
        reply = {}
        reply['tx_hash'] = data['transaction_hash']
        reply['success'] = True
        return reply
    else:
        raise Exception('Tx hash missing from chain.com response: ' + str(data) + '\noriginal: ' + str(payload))
916447
def check_chain_dir_exists(self, warn_migration=False):
        
        chain_path = os.path.join(self.DATA_DIR_PATH, 'Chains')

        if not os.path.exists(chain_path):
            try:
                os.makedirs(chain_path)
                logger.info("Created 'Chains' directory at %s " % chain_path)
            except Exception as e:
                logger.error("Could not create 'Chains' directory at %s %s" % (chain_path, e))

        warn_migration = False
        # Add a warning for migration purposes if we created a chain dir
        if warn_migration and ROOT_INSTALL_PATH != self.DATA_DIR_PATH:
            if os.path.exists(os.path.join(ROOT_INSTALL_PATH, 'Chains')):
                logger.warning("[MIGRATION] You are now using the blockchain data at %s, but it appears you have existing data at %s/Chains" % (
                    chain_path, ROOT_INSTALL_PATH))
                logger.warning(
                    "[MIGRATION] If you would like to use your existing data, please move any data at %s/Chains to %s " % (ROOT_INSTALL_PATH, chain_path))
                logger.warning("[MIGRATION] Or you can continue using your existing data by starting your script with the `--datadir=.` flag")
894492
def commit_chain(chain_names, content)
      params = { 'CommitChainMsg' => get_chain_commit(chain_names, content) }
      raw_post "/v1/commit-chain/", params.to_json, content_type: :json
    end
1220347
def mine_blocks(num_blocks: int, chain: MiningChain) -> MiningChain:
    
    if not isinstance(chain, MiningChain):
        raise ValidationError('`mine_block` may only be used on MiningChain instances')
    for _ in range(num_blocks):
        chain.mine_block()
    return chain
623924
function(required, cb) {
      var chain = new Chain(config);
      chain.on(required, cb);
      return chain;
    }
656759
private Chain<ApiResponse> createResponseChain(IAsyncHandler<ApiResponse> responseHandler) {
        ResponseChain chain = new ResponseChain(policyImpls, context);
        chain.headHandler(responseHandler);
        chain.policyFailureHandler(result -> {
            if (apiConnectionResponse != null) {
            apiConnectionResponse.abort();
            }
            policyFailureHandler.handle(result);
        });
        chain.policyErrorHandler(result -> {
            if (apiConnectionResponse != null) {
            apiConnectionResponse.abort();
            }
            policyErrorHandler.handle(result);
        });
        return chain;
    }
1165530
def build_chain(self, **kwargs):
        
        set_defaults(self._chain_defaults, kwargs)
        set_defaults(self._defaults, kwargs)
        return Chain(self, **kwargs)
892349
protected void doProcessFailure(PolicyFailure failure, IPolicyContext context, C config, IPolicyFailureChain chain) {
        chain.doFailure(failure);
    }
868942
function (chain, type) {
    const oThis = this;
    if (oThis.valueChain === chain) {
      if (oThis.typeRPC === type) {
        return require(rootPrefix + '/lib/web3/providers/value_rpc');
      } else if (oThis.typeWS === type) {
        return require(rootPrefix + '/lib/web3/providers/value_ws');
      }
    } else if (oThis.utilityChain === chain) {
      if (oThis.typeRPC === type) {
        return require(rootPrefix + '/lib/web3/providers/utility_rpc');
      } else if (oThis.typeWS === type) {
        return require(rootPrefix + '/lib/web3/providers/utility_ws');
      }
    }
    return null;
  }
60191
async def verify_task_types(chain):
    
    valid_task_types = get_valid_task_types()
    task_count = {}
    for obj in chain.get_all_links_in_chain():
        task_type = obj.task_type
        log.info("Verifying {} {} as a {} task...".format(obj.name, obj.task_id, task_type))
        task_count.setdefault(task_type, 0)
        task_count[task_type] += 1
        # Run tests synchronously for now.  We can parallelize if efficiency
        # is more important than a single simple logfile.
        await valid_task_types[task_type](chain, obj)
    return task_count
1232526
def issue(self, chain):
        

        blockchain_bytes = self.certificate_batch_handler.prepare_batch()

        for attempt_number in range(0, self.max_retry):
            try:
                txid = self.transaction_handler.issue_transaction(blockchain_bytes)
                self.certificate_batch_handler.finish_batch(txid, chain)
                logging.info('Broadcast transaction with txid %s', txid)
                return txid
            except BroadcastError:
                logging.warning(
                    'Failed broadcast reattempts. Trying to recreate transaction. This is attempt number %d',
                    attempt_number)
        logging.error('All attempts to broadcast failed. Try rerunning issuer.')
        raise BroadcastError('All attempts to broadcast failed. Try rerunning issuer.')
491363
def check_chain(table='filter', chain=None, family='ipv4'):
    '''
    
    '''

    if not chain:
        return 'Error: Chain needs to be specified'

    cmd = '{0}-save -t {1}'.format(_iptables_cmd(family), table)
    out = __salt__['cmd.run'](cmd).find(':{0} '.format(chain))

    if out != -1:
        out = True
    else:
        out = False

    return out
223794
def validate_proof(self, proof, target_hash, merkle_root):
        
        return validate_proof(proof, target_hash, merkle_root, self.hash_f)
1066676
def _set_chain_sid(chain_model, sid):
    
    if not sid:
        return
    if chain_model.sid and chain_model.sid.did != sid:
        raise d1_common.types.exceptions.ServiceFailure(
            0,
            'Attempted to modify existing SID. '
            'existing_sid="{}", new_sid="{}"'.format(chain_model.sid.did, sid),
        )
    chain_model.sid = d1_gmn.app.did.get_or_create_did(sid)
    chain_model.save()
34308
def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
    
    return authenticate_with_certificate_chain(
        reactor, base_url, [client_cert], client_key, ca_cert,
    )
751996
def chain_absent(name, table='filter', family='ipv4'):
    '''
    
    '''

    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    chain_check = __salt__['nftables.check_chain'](table, name, family)
    if not chain_check:
        ret['result'] = True
        ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}'
                          .format(name, table, family))
        return ret

    flush_chain = __salt__['nftables.flush'](table, name, family)
    if flush_chain:
        command = __salt__['nftables.delete_chain'](table, name, family)
        if command is True:
            ret['changes'] = {'locale': name}
            ret['result'] = True
            ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}'
                              .format(name, table, family))
        else:
            ret['result'] = False
            ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
                              .format(name, table, command.strip(), family))
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
            name,
            table,
            flush_chain.strip(),
            family
        )
    return ret