unlock wallet so it can be used for payments

@param          $options ['primary_private_key' => key] OR ['passphrase' => pass]
@param callable $fn
@return bool
@throws \Exception
499122
public function unlock($options, callable $fn = null) {
        // explode the wallet data
        $password = isset($options['passphrase']) ? $options['passphrase'] : (isset($options['password']) ? $options['password'] : null);
        $encryptedPrimarySeed = $this->encryptedPrimarySeed;
        $encryptedSecret = $this->encryptedSecret;
        $primaryPrivateKey = isset($options['primary_private_key']) ? $options['primary_private_key'] : null;

        if (isset($options['secret'])) {
            $this->secret = $options['secret'];
        }
        if (isset($options['primary_seed'])) {
            $this->primarySeed = $options['primary_seed'];
        }

        if (!$primaryPrivateKey) {
            if (!$password) {
                throw new \InvalidArgumentException("Can't init wallet with Primary Seed without a passphrase");
            } elseif (!$encryptedSecret) {
                throw new \InvalidArgumentException("Can't init wallet with Primary Seed without a encrypted secret");
            }
        }

        if ($primaryPrivateKey) {
            if (!($primaryPrivateKey instanceof HierarchicalKey) && !($primaryPrivateKey instanceof BIP32Key)) {
                $primaryPrivateKey = HierarchicalKeyFactory::fromExtended($primaryPrivateKey);
            }
        } else {
            if (!($this->secret = CryptoJSAES::decrypt($encryptedSecret, $password))) {
                throw new WalletDecryptException("Failed to decrypt secret with password");
            }
            // convert the mnemonic to a seed using BIP39 standard
            if (!($this->primarySeed = CryptoJSAES::decrypt($encryptedPrimarySeed, $this->secret))) {
                throw new WalletDecryptException("Failed to decrypt primary seed with secret");
            }
            $seedBuffer = new Buffer($this->primarySeed, 32);
            // create BIP32 private key from the seed
            $primaryPrivateKey = HierarchicalKeyFactory::fromEntropy($seedBuffer);
        }

        $this->primaryPrivateKey = $primaryPrivateKey instanceof BIP32Key ? $primaryPrivateKey : BIP32Key::create($primaryPrivateKey, "m");

        // create checksum (address) of the primary privatekey to compare to the stored checksum
        $checksum = $this->primaryPrivateKey->publicKey()->getAddress()->getAddress();
        if ($checksum != $this->checksum) {
            throw new \Exception("Checksum [{$checksum}] does not match [{$this->checksum}], most likely due to incorrect password");
        }

        $this->locked = false;

        // if the response suggests we should upgrade to a different blocktrail cosigning key then we should
        if (array_key_exists('upgrade_key_index', $options)) {
            $this->upgradeKeyIndex($options['upgrade_key_index']);
        }

        if ($fn) {
            $fn($this);
            $this->lock();
        }
    }
577997
protected function configureInstanceAssoc(array $options)
    {
        if (array_key_exists('access_token', $options)) {
            $this->setToken($options['access_token']);
        }

        if (array_key_exists('expires_in', $options)) {
            $this->setTokenExpiresIn($options['expires_in']);
        }

        return $this;
    }
145352
function WalletOptions(options) {
  if (!(this instanceof WalletOptions))
    return new WalletOptions(options);

  this.network = Network.primary;
  this.logger = Logger.global;
  this.workers = null;
  this.client = null;
  this.feeRate = 0;

  this.prefix = null;
  this.location = null;
  this.db = 'memory';
  this.maxFiles = 64;
  this.cacheSize = 16 << 20;
  this.compression = true;
  this.bufferKeys = layout.binary;

  this.spv = false;
  // this.witness = false; cfc
  this.witness = true; // ctl
  this.checkpoints = false;
  this.startHeight = 0;
  this.keepBlocks = this.network.block.keepBlocks;
  this.wipeNoReally = false;
  this.apiKey = null;
  this.walletAuth = false;
  this.noAuth = false;
  this.ssl = false;
  this.host = '127.0.0.1';
  this.port = this.network.rpcPort + 2;
  this.listen = false;

  if (options)
    this.fromOptions(options);
}
1038726
function unlock($path, $locktoken) {
        $this->_path = $this->translate_uri($path);
        $this->header_unset();
        $this->create_basic_request('UNLOCK');
        $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
        $this->send_request();
        $this->get_respond();
        $response = $this->process_respond();
        if ($response['status']['http-version'] == 'HTTP/1.1' ||
            $response['status']['http-version'] == 'HTTP/1.0') {
            /* seems to be http ... proceed
            rfc 2518 says:
            204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
             */
                return $response['status']['status-code'];
            }
        return false;
    }
501960
protected function tryAgainIfCausedByLostConnection(Exception $e, $dsn, $username, $password, $options)
    {
        if ($this->causedByLostConnection($e)) {
            return $this->createPdoConnection($dsn, $username, $password, $options);
        }

        throw $e;
    }
916261
public static function Encrypt ($data, $key, $options = []) {
		$options = static::_AdjustOptions($options);

		$td = static::_OpenMcrypt($key, $options);
		$block_size = mcrypt_enc_get_block_size($td);

		$pad = $block_size - (strlen($data) % $block_size);
		$data .= str_repeat(chr($pad), $pad);

		$data = mcrypt_generic($td, $data);
		static::_CloseMcrypt($td);

		return $data;
	}
1037353
public function setAdapter($options = null)
    {
        if (is_string($options)) {
            $adapter = $options;
        } elseif (isset($options['adapter'])) {
            $adapter = $options['adapter'];
            unset($options['adapter']);
        } else {
            $adapter = 'BlockCipher';
        }

        if (!is_array($options)) {
            $options = [];
        }

        if (class_exists('Zend\Filter\Encrypt\\' . ucfirst($adapter))) {
            $adapter = 'Zend\Filter\Encrypt\\' . ucfirst($adapter);
        } elseif (!class_exists($adapter)) {
            throw new Exception\DomainException(
                sprintf(
                    '%s expects a valid registry class name; received "%s", which did not resolve',
                    __METHOD__,
                    $adapter
                )
            );
        }

        $this->adapter = new $adapter($options);
        if (!$this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) {
            throw new Exception\InvalidArgumentException(
                "Encoding adapter '" . $adapter
                . "' does not implement Zend\\Filter\\Encrypt\\EncryptionAlgorithmInterface"
            );
        }

        return $this;
    }
933377
public function createConnection($dsn, array $config, array $options)
    {
        list($username, $password) = [
            Arr::get($config, 'username'), Arr::get($config, 'password'),
        ];

        try {
            return $this->createPdoConnection(
                $dsn,
                $username,
                $password,
                $options
            );
        } catch (Exception $e) {
            return $this->tryAgainIfCausedByLostConnection(
                $e,
                $dsn,
                $username,
                $password,
                $options
            );
        }
    }
59994
public function get($name, $default = null, array $options = [])
    {
        $options = $this->options($options);
        $value   = $this->helper()->arr()->get($this->storage(), $name, $default);

        return $value === null || $value === $default ? $default : $this->decrypt($value, $options);
    }
362148
public function getUser($accessToken = null, array $options = [])
    {
        if (null === $accessToken) {
            $options['access_token'] = $this->blizzardClient->getAccessToken();
        } else {
            $options['access_token'] = $accessToken;
        }

        return $this->request('/account/user', $options);
    }
1327042
public function beginTransaction(array $options = [])
    {
        if (!$this->isConnected()) {
            $this->connect();
        }
        
        if (!$this->inTransaction() || !empty($options['new'])) {
            $this->workSavepoint(
                'beginTransaction',
                'SAVEPOINT ' . $this->savePointName()
            );
            $this->transactions[] = true;
        } else {
            $this->transactions[] = false;
        }
    }
401136
public function transactional(callable $fn)
    {
        $pdo = $this->getPdo();
        $pdo->beginTransaction();
        try {
            call_user_func($fn);
            $pdo->commit();
        } catch (\Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
    }
184432
protected function validateOptions($options)
    {
        foreach ($options as $key => $value) {
            if (!in_array($key, $this->allowed_options)) {
                throw new FilestackException("Invalid policy option: $key:$value", 400);
            }
        }

        return true;
    }
831470
public function exchangeConsumerRequestForAccessToken ( $token, $options = array() )
    {
        $new_token  = $this->generateKey(true);
        $new_secret = $this->generateKey();

        // Maximum time to live for this token
        if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
        {
            $ttl_sql = '(NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\')';
        }
        else
        {
            $ttl_sql = "'9999-12-31'";
        }

         if (isset($options['verifier'])) {
             $verifier = $options['verifier'];

             // 1.0a Compatibility : check token against oauth_verifier
             $this->query('
                         UPDATE oauth_server_token
                         SET ost_token            = \'%s\',
                             ost_token_secret    = \'%s\',
                             ost_token_type        = \'access\',
                             ost_timestamp        = NOW(),
                             ost_token_ttl       = '.$ttl_sql.'
                         WHERE ost_token      = \'%s\'
                           AND ost_token_type = \'request\'
                           AND ost_authorized = \'1\'
                           AND ost_token_ttl  >= NOW()
                           AND ost_verifier = \'%s\'
                         ', $new_token, $new_secret, $token, $verifier);
         } else {

             // 1.0
             $this->query('
                         UPDATE oauth_server_token
                         SET ost_token            = \'%s\',
                             ost_token_secret    = \'%s\',
                             ost_token_type        = \'access\',
                             ost_timestamp        = NOW(),
                             ost_token_ttl       = '.$ttl_sql.'
                         WHERE ost_token      = \'%s\'
                           AND ost_token_type = \'request\'
                           AND ost_authorized = \'1\'
                           AND ost_token_ttl  >= NOW()
                         ', $new_token, $new_secret, $token);
        }

        if ($this->query_affected_rows() != 1)
        {
            throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized');
        }

        $ret = array('token' => $new_token, 'token_secret' => $new_secret);
        $ttl = $this->query_one('
                    SELECT    (CASE WHEN ost_token_ttl >= \'9999-12-31\' THEN NULL ELSE ost_token_ttl - NOW() END) as token_ttl
                    FROM oauth_server_token
                    WHERE ost_token = \'%s\'', $new_token);

        if (is_numeric($ttl))
        {
            $ret['token_ttl'] = intval($ttl);
        }
        return $ret;
    }
584570
private function auth($options)
    {
        OssUtil::validateOptions($options);
        //验证bucket，list_bucket时不需要验证
        $this->authPrecheckBucket($options);
        //验证object
        $this->authPrecheckObject($options);
        //Object名称的编码必须是utf8
        $this->authPrecheckObjectEncoding($options);
        //验证ACL
        $this->authPrecheckAcl($options);
        // 获得当次请求使用的协议头，是https还是http
        $scheme = $this->useSSL ? 'https://' : 'http://';
        // 获得当次请求使用的hostname，如果是公共域名或者专有域名，bucket拼在前面构成三级域名
        $hostname = $this->generateHostname($options[self::OSS_BUCKET]);
        $string_to_sign = '';
        $headers = $this->generateHeaders($options, $hostname);
        $signable_query_string_params = $this->generateSignableQueryStringParam($options);
        $signable_query_string = OssUtil::toQueryString($signable_query_string_params);
        $resource_uri = $this->generateResourceUri($options);
        //生成请求URL
        $conjunction = '?';
        $non_signable_resource = '';
        if (isset($options[self::OSS_SUB_RESOURCE])) {
            $conjunction = '&';
        }
        if ($signable_query_string !== '') {
            $signable_query_string = $conjunction . $signable_query_string;
            $conjunction = '&';
        }
        $query_string = $this->generateQueryString($options);
        if ($query_string !== '') {
            $non_signable_resource .= $conjunction . $query_string;
            $conjunction = '&';
        }
        $this->requestUrl = $scheme . $hostname . $resource_uri . $signable_query_string . $non_signable_resource;

        //创建请求
        $request = new RequestCore($this->requestUrl);
        $request->set_useragent($this->generateUserAgent());
        // Streaming uploads
        if (isset($options[self::OSS_FILE_UPLOAD])) {
            if (is_resource($options[self::OSS_FILE_UPLOAD])) {
                $length = null;

                if (isset($options[self::OSS_CONTENT_LENGTH])) {
                    $length = $options[self::OSS_CONTENT_LENGTH];
                } elseif (isset($options[self::OSS_SEEK_TO])) {
                    $stats = fstat($options[self::OSS_FILE_UPLOAD]);
                    if ($stats && $stats[self::OSS_SIZE] >= 0) {
                        $length = $stats[self::OSS_SIZE] - (integer)$options[self::OSS_SEEK_TO];
                    }
                }
                $request->set_read_stream($options[self::OSS_FILE_UPLOAD], $length);
            } else {
                $request->set_read_file($options[self::OSS_FILE_UPLOAD]);
                $length = $request->read_stream_size;
                if (isset($options[self::OSS_CONTENT_LENGTH])) {
                    $length = $options[self::OSS_CONTENT_LENGTH];
                } elseif (isset($options[self::OSS_SEEK_TO]) && isset($length)) {
                    $length -= (integer)$options[self::OSS_SEEK_TO];
                }
                $request->set_read_stream_size($length);
            }
        }
        if (isset($options[self::OSS_SEEK_TO])) {
            $request->set_seek_position((integer)$options[self::OSS_SEEK_TO]);
        }
        if (isset($options[self::OSS_FILE_DOWNLOAD])) {
            if (is_resource($options[self::OSS_FILE_DOWNLOAD])) {
                $request->set_write_stream($options[self::OSS_FILE_DOWNLOAD]);
            } else {
                $request->set_write_file($options[self::OSS_FILE_DOWNLOAD]);
            }
        }

        if (isset($options[self::OSS_METHOD])) {
            $request->set_method($options[self::OSS_METHOD]);
            $string_to_sign .= $options[self::OSS_METHOD] . "\n";
        }

        if (isset($options[self::OSS_CONTENT])) {
            $request->set_body($options[self::OSS_CONTENT]);
            if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') {
                $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream';
            }

            $headers[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]);
            $headers[self::OSS_CONTENT_MD5] = base64_encode(md5($options[self::OSS_CONTENT], true));
        }

        if (isset($options[self::OSS_CALLBACK])) {
            $headers[self::OSS_CALLBACK] = base64_encode($options[self::OSS_CALLBACK]);
        }
        if (isset($options[self::OSS_CALLBACK_VAR])) {
            $headers[self::OSS_CALLBACK_VAR] = base64_encode($options[self::OSS_CALLBACK_VAR]);
        }

        if (!isset($headers[self::OSS_ACCEPT_ENCODING])) {
            $headers[self::OSS_ACCEPT_ENCODING] = '';
        }

        uksort($headers, 'strnatcasecmp');

        foreach ($headers as $header_key => $header_value) {
            $header_value = str_replace(array("\r", "\n"), '', $header_value);
            if ($header_value !== '' || $header_key === self::OSS_ACCEPT_ENCODING) {
                $request->add_header($header_key, $header_value);
            }

            if (
                strtolower($header_key) === 'content-md5' ||
                strtolower($header_key) === 'content-type' ||
                strtolower($header_key) === 'date' ||
                (isset($options['self::OSS_PREAUTH']) && (integer)$options['self::OSS_PREAUTH'] > 0)
            ) {
                $string_to_sign .= $header_value . "\n";
            } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) {
                $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
            }
        }
        // 生成 signable_resource
        $signable_resource = $this->generateSignableResource($options);
        $string_to_sign .= rawurldecode($signable_resource) . urldecode($signable_query_string);

        //对?后面的要签名的string字母序排序
        $string_to_sign_ordered = $this->stringToSignSorted($string_to_sign);

        $signature = base64_encode(hash_hmac('sha1', $string_to_sign_ordered, $this->accessKeySecret, true));
        $request->add_header('Authorization', 'OSS ' . $this->accessKeyId . ':' . $signature);

        if (isset($options[self::OSS_PREAUTH]) && (integer)$options[self::OSS_PREAUTH] > 0) {
            $signed_url = $this->requestUrl . $conjunction . self::OSS_URL_ACCESS_KEY_ID . '=' . rawurlencode($this->accessKeyId) . '&' . self::OSS_URL_EXPIRES . '=' . $options[self::OSS_PREAUTH] . '&' . self::OSS_URL_SIGNATURE . '=' . rawurlencode($signature);
            return $signed_url;
        } elseif (isset($options[self::OSS_PREAUTH])) {
            return $this->requestUrl;
        }

        if ($this->timeout !== 0) {
            $request->timeout = $this->timeout;
        }
        if ($this->connectTimeout !== 0) {
            $request->connect_timeout = $this->connectTimeout;
        }

        try {
            $request->send_request();
        } catch (RequestCore_Exception $e) {
            throw(new OssException('RequestCoreException: ' . $e->getMessage()));
        }
        $response_header = $request->get_response_header();
        $response_header['oss-request-url'] = $this->requestUrl;
        $response_header['oss-redirects'] = $this->redirects;
        $response_header['oss-stringtosign'] = $string_to_sign;
        $response_header['oss-requestheaders'] = $request->request_headers;

        $data = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code());
        //retry if OSS Internal Error
        if ((integer)$request->get_response_code() === 500) {
            if ($this->redirects <= $this->maxRetries) {
                //设置休眠
                $delay = (integer)(pow(4, $this->redirects) * 100000);
                usleep($delay);
                $this->redirects++;
                $data = $this->auth($options);
            }
        }
        
        $this->redirects = 0;
        return $data;
    }
412310
public function requestPassword($options = []) {
		$options = Hash::merge($this->getConfig('requestPassword'), $options);
		$entity = $this->UserTable->newEntity(null, [
			'validate' => 'requestPassword'
		]);

		if ($this->_getRequest()->is('post')) {
			$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), [
				'validate' => 'requestPassword'
			]);

			if (!$entity->errors($options['field']) && $this->_initPasswordReset($entity, $options)) {
				return true;
			}

			if ($options['setEntity']) {
				if ($entity->dirty('email') && !$entity->errors('email')) {
					$entity->email = '';
				}
				$this->_setViewVar('userEntity', $entity);
			}
			unset($this->_getRequest()->data[$options['field']]);

			return false;
		}

		if ($options['setEntity']) {
			$this->getController()->set('userEntity', $entity);
		}
	}
1206431
public static function Encrypt ($data, $key, $options = []) {
		$options = static::_AdjustOptions($options);
		return openssl_encrypt($data, $options['method'], $key, $options['openssl_options'], $options['iv']);
	}