Download the signed chain of trust artifacts.

    Args:
        chain (ChainOfTrust): the chain of trust to add to.

    Raises:
        BaseDownloadError: on failure.
551275
async def download_cot(chain):
    
    artifact_tasks = []
    # only deal with chain.links, which are previously finished tasks with
    # signed chain of trust artifacts.  ``chain.task`` is the current running
    # task, and will not have a signed chain of trust artifact yet.
    for link in chain.links:
        task_id = link.task_id
        parent_dir = link.cot_dir
        urls = []

        unsigned_url = get_artifact_url(chain.context, task_id, 'public/chain-of-trust.json')
        urls.append(unsigned_url)
        if chain.context.config['verify_cot_signature']:
            urls.append(
                get_artifact_url(chain.context, task_id, 'public/chain-of-trust.json.sig')
            )

        artifact_tasks.append(
            asyncio.ensure_future(
                download_artifacts(
                    chain.context, urls, parent_dir=parent_dir,
                    valid_artifact_task_ids=[task_id]
                )
            )
        )

    artifacts_paths = await raise_future_exceptions(artifact_tasks)

    for path in artifacts_paths:
        sha = get_hash(path[0])
        log.debug("{} downloaded; hash is {}".format(path[0], sha))
248737
public void checkServerTrusted(X509Certificate[] chain, String authType)
                 throws CertificateException {
         try {
             pkixTrustManager.checkServerTrusted(chain, authType);
         } catch (CertificateException excep) {
             /*
              * Possibly pop up a dialog box asking whether to trust the
              * cert chain.
              */
         }
     }
1329305
def import_ownertrust(cls, trustdb=None):
    
    if trustdb is None:
        trustdb = os.path.join(cls.homedir, 'trustdb.gpg')

    import_proc = cls._open_subprocess(['--import-ownertrust'])

    try:
        tdb = open(trustdb, 'rb')
    except (OSError, IOError):
        log.error("trustdb file %s does not exist!" % trustdb)

    _util._threaded_copy_data(tdb, import_proc.stdin)
    import_proc.wait()
848121
def acquire(self, **kwargs):
        
        return config.download_data(self.temp_filename, self.url,
                                    self.sha256)
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;
  }
31182
def chain(self, **kwargs):
        
        chain = self.build_chain(**kwargs)
        self._patterns.append(chain)
        return chain
98297
def verify_header_chain(cls, path, chain=None):
        
        if chain is None:
            chain = SPVClient.load_header_chain( path )

        prev_header = chain[0]
        
        for i in xrange(1, len(chain)):
            header = chain[i]
            height = header.get('block_height')
            prev_hash = prev_header.get('hash')
            if prev_hash != header.get('prev_block_hash'):
                log.error("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')))
                return False

            bits, target = SPVClient.get_target( path, height/BLOCK_DIFFICULTY_CHUNK_SIZE, chain)
            if bits != header.get('bits'):
                log.error("bits mismatch: %s vs %s" % (bits, header.get('bits')))
                return False

            _hash = header.get('hash')
            if int('0x'+_hash, 16) > target:
                log.error("insufficient proof of work: %s vs target %s" % (int('0x'+_hash, 16), target))
                return False

            prev_header = header

        return True
1352885
def upload(local_path, remote_path, properties = {}, headers = {})
      artifact = Resource::Artifact.new(local_path: local_path)
      artifact.upload(key, remote_path, properties, headers)
    end
1165530
def build_chain(self, **kwargs):
        
        set_defaults(self._chain_defaults, kwargs)
        set_defaults(self._defaults, kwargs)
        return Chain(self, **kwargs)
976293
def checksum_chain(self):
        

        checksums = []
        for certificate in self.certificates:
            checksums.append(certificate.checksum)

        return "::".join(checksums)
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))
381379
def load_cert_chain(chain_file):
    
    if hasattr(chain_file, 'read'):
        cert_chain = chain_file.read() 
    else:
        with open(chain_file, 'rb') as f:
            cert_chain = f.read()       
    
    if not cert_chain:
        raise ValueError('Certificate chain file is empty!')

    cert_type_matches = []
    for match in _PEM_RE.finditer(cert_chain):
        cert_type_matches.append((match.group(1), match.group(0)))
    
    if not cert_type_matches:
        raise ValueError('No certificate types were found. Valid types '
            'are: {}'.format(CERT_TYPES))

    return cert_type_matches
17490
public static void verifyChain(List<X509Certificate> chain)
	{
		if (chain == null || chain.isEmpty())
			throw new IllegalArgumentException("Must provide a chain that is non-null and non-empty");

		for (int i = 0; i < chain.size(); i++)
		{
			final X509Certificate certificate = chain.get(i);
			final int issuerIndex = (i != 0) ?
			                        i - 1 :
			                        0; // The index of the issuer is the previous cert (& the root must, of course, sign itself)
			final X509Certificate issuer = chain.get(issuerIndex);

			// Verify the certificate was indeed issued by the previous certificate in the chain
			try
			{
				certificate.verify(issuer.getPublicKey());
			}
			catch (GeneralSecurityException e)
			{
				final String msg = "Failure verifying " + certificate + " against claimed issuer " + issuer;

				throw new IllegalArgumentException(msg + ": " + e.getMessage(), e);
			}
		}
	}
926474
def choice_download(self):
        
        Download(path="", url=self.dwn_srcs, repo="sbo").start()
        raise SystemExit()
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")
482036
public static X500Principal getSubjectDNFromChain(List<X509Certificate> chain)
	{
		if (chain == null || chain.isEmpty())
			throw new IllegalArgumentException("Must provide a chain that is non-null and non-empty");

		X509Certificate cert = chain.get(chain.size() - 1);

		return cert.getSubjectX500Principal();
	}
1159025
def save(self, path="chain.dat"):
        
        # create dictionary for data
        dic = {}
        dic['chain'] = self._chain.tolist()
        dic['step_count'] = self._step_count.tolist()
        dic['n_samples'] = self._n_samples
        dic['n_accepted'] = self._n_accepted
        dic['x'] = self._X['x'].tolist()
        dic['f'] = self._X['f'].tolist()
        dic['J'] = self._X['J'].tolist()

        # write data to file
        file = open(path, 'w')
        json.dump(dic, file)
        file.close()