Bob sends a message, first querying (but not claiming) e2e keys. Set the
expectations and check the results.

@return {promise} which resolves to the ciphertext for Ali's device.
353557
function bobSendsReplyMessage() {
    return Promise.all([
        sendMessage(bobTestClient.client),
        expectBobQueryKeys()
            .then(expectBobSendMessageRequest),
    ]).spread(function(_, ciphertext) {
        return ciphertext;
    });
}
396840
function(app) {

    // Communication is the key to every succesful relationship
    app.status('Waiting for site to be ready.');

    // Grab the URL we want to check
    var site = app.url;

    // Ping the site until its ready to go
    return Promise.retry(function() {

      // Log the attempt
      log.debug(format('Checking to see if %s is ready.', site));

      // Send REST request.
      return new Promise(function(fulfill, reject) {

        // Make the actual request, lets make sure self-signed certs are OK
        rest.get(site, {rejectUnauthorized: false})

        // Log result and fulfil promise
        .on('success', function(data) {
          log.debug(format('%s is now ready.', site));
          fulfill(data);
        })

        // Throw an error on fail/error
        .on('fail', function(data, response) {

          // Get the codes and define codes that should indicate the site
          // is not ready yet
          var code = response.statusCode;
          var waitCodes = [400, 502];

          if (_.includes(waitCodes, code)) {
            log.debug(format('%s not yet ready with code %s.', site, code));
            reject(new Error(response));
          }
          else {
            log.debug(format('%s is now ready.', site));
            fulfill(data);
          }

        }).on('error', reject);

      });

    }, {max: 15})

    // We've been unable to get the correct status code so lets shoot out a
    // non-fatal warning to the user
    .catch(function() {
      log.warn(
        format('Unexpected status code returned. This MAY be a problem. ' +
        'Check your site at %s to verify. Restarting your app may help.', site)
      );
    });
  }
946584
function(password, keyFile) {
    var that = this;
    this.ready = Promise.all([
        this.setPassword(password),
        this.setKeyFile(keyFile)
    ]).then(function() {
        return that;
    });
}
182536
function expectAliSendMessageRequest() {
    return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) {
        aliMessages.push(content);
        expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
        const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()];
        expect(ciphertext).toBeTruthy();
        return ciphertext;
    });
}
959492
function openssl_req(options, ec) {
  if ('string' === typeof options)
    options = {self_sign: true, subjects: {CN: options}}

  return Promise.all([
      tmpfile(options.config),
      tmpfile(ec_pem.encodePrivateKey(ec)) ])
    .then(tmpList => {
      const [tmp_config, tmp_key] = tmpList
      let args = ['req', '-new', '-sha256', '-key', tmp_key.path]


      if (options.self_sign) {
        args.push('-x509', '-days', options.days || 1)
      }

      if (tmp_config) {
        args.push('-config', tmp_config.path, '-extensions', 'v3_req')
      }

      args = args.filter(e => e)
      return finallyCleanupTmpList(openssl_stdout(args, 5), tmpList) })}
460853
function bcrypt_hash (data) {
  return new Promise((resolve, reject) => {
    Bcrypt.genSalt(10, function (err, salt) {
      if (err) return reject(err)
      Bcrypt.hash(data, salt, function (err, hash) {
        if (err) return reject(err)
        resolve(hash)
      })
    })
  })
}
258613
function createPromiseWith(actual, expected, verb) {
  assertPromise(actual);
  const success = jasmine.createSpy('Promise success callback');
  const failure = jasmine.createSpy('Promise failure callback');

  actual.then(success, failure);
  createScope().$digest();

  const spy = verb === 'resolved' ? success : failure;
  let pass = false;
  let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`;

  if (isJasmine2 ? spy.calls.any() : spy.calls.length) {
    const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0];
    if (angular.isFunction(expected)) {
      expected(actualResult);
      pass = true;
    } else {
      pass = angular.equals(actualResult, expected);
    }

    message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \
${jasmine.pp(actualResult)}`;
  }

  return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message);
}
537591
function compare(data, encrypted) {
        var deferred = Q.defer();

        bcrypt.compare(data, encrypted, function (err, res) {
            err ? deferred.reject(err) : deferred.resolve(res);
        });

        return deferred.promise;
    }
837914
function toResolve() {
  return {
    compare(actual) {
      assertPromise(actual);
      const success = jasmine.createSpy('Promise success callback');
      actual.then(success, angular.noop);
      createScope().$digest();

      const pass = isJasmine2 ? success.calls.any() : success.calls.length > 0;
      const message = 'Expected promise {not} to have been resolved';
      return getResult('toResolve', pass, message);
    }
  };
}
1257463
function() {
        return new Promise(function(resolve, reject) {
            VkSdkLoginManager.authorize(function(error, result) {
                if (error) {
                    reject(error);
                } else {
                    resolve(result);
                }
            });
        });
    }
518112
async function hello () {
  const id = await Rpc.compose.deepProperties.rpcMethods.hello.call(this)
  this.rpcSessions[id].address = await this.address()
  return Promise.resolve(id)
}
637533
function(keyId) {
    var res = this.get("25519KeysignedKey" + keyId);
    if (res !== undefined) {
      if (!(res.pubKey instanceof ArrayBuffer)) {
        res.pubKey = convertToArrayBuffer(res.pubKey);
      }
      if (!(res.privKey instanceof ArrayBuffer)) {
        res.privKey = convertToArrayBuffer(res.privKey);
      }
      res = { pubKey: res.pubKey, privKey: res.privKey };
    }
    return Promise.resolve(res);
  }
1362705
function resolve(vResult0) {
			var fnThen;

			if (vResult0 === that) {
				reject(new TypeError("A promise cannot be resolved with itself."));
				return;
			}
			if (vResult0 instanceof SyncPromise) {
				if (vResult0.isFulfilled()) {
					resolve(vResult0.getResult());
					return;
				} else if (vResult0.isRejected()) {
					vResult0.caught(); // might have been uncaught so far
					reject(vResult0.getResult());
					return;
				} else {
					vResult0.caught(); // make sure it will never count as uncaught
					vResult0 = vResult0.getResult(); // unwrap to access native thenable
				}
			}

			iState = 0;
			vResult = vResult0;
			if (hasThen(vResult)) {
				try {
					fnThen = vResult.then;
				} catch (e) {
					// 2.3.3.2. If retrieving the property x.then results in a thrown exception e,
					// reject promise with e as the reason.
					reject(e);
					return;
				}
				if (typeof fnThen === "function") {
					call(fnThen.bind(vResult), resolve, reject);
					return;
				}
			}
			iState = 1;
			if (fnResolve) {
				fnResolve(vResult);
				fnReject = fnResolve = null; // be nice to the garbage collector
			}
		}
585614
function() {
		var that = this;
		return new Promise(function(resolve, reject) {
			that.resolve(function(err, val) {
				if (err) {
					reject(err);
				} else {
					resolve(val);
				}
			});
		});
	}
613731
function sendText(payload: {
  to: string,
  from: string,
  message: string,
  statusCallback: string,
}): Promise<null | TwilioResponse> {
  if (!(process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN)) {
    logErr(
      new Error(
        "Could not send text message, missing required Twilio env vars"
      ),
      { payload }
    );
    return Promise.resolve(null);
  } else if (!Twilio) {
    Twilio = require("twilio");
  }

  return new Twilio(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_AUTH_TOKEN
  ).messages.create({
    to: `+1${payload.to}`,
    from: `+1${payload.from}`,
    body: payload.message,
    statusCallback: payload.statusCallback,
  });
}
1144081
function reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn){
	var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey);
	console.log('will encrypt and send to '+recipient_device_address+': '+JSON.stringify(json));
	// encrypt to recipient's permanent pubkey before storing the message into outbox
	var objEncryptedPackage = createEncryptedPackage(json, recipient_device_pubkey);
	// if the first attempt fails, this will be the inner message
	var objDeviceMessage = {
		encrypted_package: objEncryptedPackage
	};
	var message_hash = objectHash.getBase64Hash(objDeviceMessage);
	conn = conn || db;
	conn.query(
		"INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)", 
		[message_hash, recipient_device_address, JSON.stringify(objDeviceMessage)], 
		function(){
			if (callbacks && callbacks.onSaved)
				callbacks.onSaved();
			sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks);
		}
	);
}
583563
function() {

        /* Prepare our message */
        var message = { proxy: { proxy: clone, arguments: arguments }};

        /* Is this "new F()" or a normal call? */
        if (this instanceof Invocable) {
          message.newInstance = true;
          ProxyPromise.call(this, message, send);
          this.asProxy(true);
        } else {
          return new ProxyPromise(message, send);
        }
      }