Set an expectation that Ali will send a message, and flush the request

@return {promise} which resolves to the ciphertext for Bob's device.
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;
    });
}
430906
function (cb) {
            if (cb) {
                if (isPromise(cb)) {
                    cb = cb.errback;
                }
                if (this.__fired && this.__error) {
                    this.__callNextTick(cb, this.__error);
                } else {
                    this.__errorCbs.push(cb);
                }
            }
            return this;
        }
428311
function (e) {
                if (e instanceof java.util.NoSuchElementException || e.message.startsWith("java.util.NoSuchElementException")) {
                    // Empty stream
                    return Promise.resolve();
                }
                return Promise.reject(e);
            }
323412
function () {
            var result = new $.Deferred();
            this.storage.load()
                .then(function (data) {
                    var oldKeys = this.getKeys();
                    this.data = data;
                    result.resolve();
                    this.trigger(PREFERENCE_CHANGE, {
                        ids: _.union(this.getKeys(), oldKeys)
                    });
                }.bind(this))
                .fail(function (error) {
                    result.reject(error);
                });
            return result.promise();
        }
1353679
function PromiseFactory() {
	var deferred = whenjs.defer();
	//var timeout = setTimeout(function () { console.log(t, 'Promise timed out')}, 3000);

	this.reject = function (err) {
		deferred.reject(err);
	};
	this.resolve = function (val) {
	//	clearTimeout(timeout);
		deferred.resolve(val);
	};
	this.promise = function () {
		return deferred.promise;
	};
}
1358281
def send(notice, promise)
      return will_not_deliver(notice) if @unsent.size >= @unsent.max

      @unsent << [notice, promise]
      promise
    end
403293
function (azurePromise) {
      var deferred = $q.defer();
      azurePromise.done(function (items) {
        deferred.resolve(items);
      }, function (err) {
        deferred.reject(err);
      });
      return deferred.promise;
    }
473778
function(deferred, message) {
			var that = this;
			if(message){
				that.setProgressMessage(message);
				var finish = function(){
					if(message === that.progressMessage){
						that.setProgressMessage("");
					}
				};
				deferred.then(finish, finish);
			}
			return deferred;
		}
1274558
function() {
    return new Promise((resolve, reject) => {
      let instance;
      if (this.modelElement.name === this.node.getName()) {
        instance = this.node;
      } else {
        instance = this.mapper.getObject(this.modelElement.path());
      }

      if (instance) {
        if (instance.isStarted()) {
          instance.__update__(timesUp('update(...)', 30000, (err) => {
            if (err) {
              this.log.error('Unable to update ' + instance.getPath());
              reject(err);
            } else {
              this.log.debug(instance.getPath());
              this.node.kCore.emitter.emit('instanceUpdated', instance);
              resolve();
            }
          }));
        }
      } else {
        reject(new Error(this.toString() + ' error: unable to update instance ' + this.modelElement.name));
      }
    });
  }
79017
function go() {
    return new Promise(handler)
      // Check for invalid `authCode`, this seems to happen at random intervals
      // within the neulion API, so we will only know when a request fails
      .catch(Errors.AuthenticationError, function(err) {

        // Authenticate and then try one more time
        return self
          .auth()
          .then(function() {
            return new Promise(handler)
          })
      })
  }
759664
function HttpBackend() {
    this.requests = [];
    this.expectedRequests = [];
    const self = this;

    // All the promises our flush requests have returned. When all these promises are
    // resolved or rejected, there are no more flushes in progress.
    // For simplicity we never remove promises from this loop: this is a mock utility
    // for short duration tests, so this keeps it simpler.
    this._flushPromises = [];

    // the request function dependency that the SDK needs.
    this.requestFn = function(opts, callback) {
        const req = new Request(opts, callback);
        console.log(`${Date.now()} HTTP backend received request: ${req}`);
        self.requests.push(req);

        const abort = function() {
            const idx = self.requests.indexOf(req);
            if (idx >= 0) {
                console.log("Aborting HTTP request: %s %s", opts.method,
                            opts.uri);
                self.requests.splice(idx, 1);
                req.callback("aborted");
            }
        };

        return {
            abort: abort,
        };
    };

    // very simplistic mapping from the whatwg fetch interface onto the request
    // interface, so we can use the same mock backend for both.
    this.fetchFn = function(input, init) {
        init = init || {};
        const requestOpts = {
            uri: input,
            method: init.method || 'GET',
            body: init.body,
        };

        return new Promise((resolve, reject) => {
            function callback(err, response, body) {
                if (err) {
                    reject(err);
                }
                resolve({
                    ok: response.statusCode >= 200 && response.statusCode < 300,
                    json: () => JSON.parse(body),
                });
            };

            const req = new Request(requestOpts, callback);
            console.log(`HTTP backend received request: ${req}`);
            self.requests.push(req);
        });
    };
}
946584
function(password, keyFile) {
    var that = this;
    this.ready = Promise.all([
        this.setPassword(password),
        this.setKeyFile(keyFile)
    ]).then(function() {
        return that;
    });
}
679059
function SessionCipher(crypto) {
    const self = this;

    const ratchet = new Ratchet(crypto);

    /**
     * Encrypt a message using the session.
     * <p>
     * If this method succeeds, the passed in session should be destroyed. This method must never be called with
     * that session again.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} message - the message bytes to be encrypted (optionally padded)
     * @return {Promise.<Object, Error>} an object containing the encrypted message bytes as well as a new session
     */
    this.encryptMessage = co.wrap(function*(session, message) {
        var newSession = new Session(session);
        var whisperMessage = yield createWhisperMessage(newSession, message);

        yield ratchet.clickSubRatchet(newSession.mostRecentState().sendingChain);

        if (newSession.mostRecentState().pendingPreKey) {
            return {
                isPreKeyWhisperMessage: true,
                body: createPreKeyWhisperMessage(newSession, whisperMessage),
                session: newSession
            };
        } else {
            return {
                isPreKeyWhisperMessage: false,
                body: whisperMessage,
                session: newSession
            };
        }
    });

    /**
     * Unwrap the WhisperMessage from a PreKeyWhisperMessage and attempt to decrypt it using session.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} preKeyWhisperMessageBytes
     * @returns {Promise.<Object, InvalidMessageException>} an object containing the decrypted message and a new session
     */
    this.decryptPreKeyWhisperMessage = (session, preKeyWhisperMessageBytes) => {
        var preKeyWhisperMessage = Messages.decodePreKeyWhisperMessage(preKeyWhisperMessageBytes);
        return self.decryptWhisperMessage(session, preKeyWhisperMessage.message.message);
    };

    /**
     * Decrypt a WhisperMessage using session.
     * <p>
     * If this method succeeds, the passed in session should be destroyed. This method must never be called with
     * that session again.
     *
     * @method
     * @param {Session} session
     * @param {ArrayBuffer} whisperMessageBytes - the encrypted message bytes
     * @returns {Promise.<Object, InvalidMessageException>} an object containing the decrypted message and a new session
     */
    this.decryptWhisperMessage = co.wrap(function*(session, whisperMessageBytes) {
        var newSession = new Session(session);
        var exceptions = [];
        for (var state of newSession.states) {
            var clonedSessionState = new SessionState(state);
            var promise = decryptWhisperMessageWithSessionState(clonedSessionState, whisperMessageBytes);
            var result = yield promise.catch((e) => {
                exceptions.push(e);
            });
            if (result !== undefined) {
                newSession.removeState(state);
                newSession.addState(clonedSessionState);
                return {
                    message: result,
                    session: newSession
                };
            }
        }
        var messages = exceptions.map((e) => e.toString());
        throw new InvalidMessageException("Unable to decrypt message: " + messages);
    });

    /**
     * Attempt to decrypt a WhisperMessage using sessionState.
     * <p>
     * Failure of this method is not necessarily fatal as it may be possible to decrypt the message using another
     * session state.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} whisperMessageBytes
     * @returns {Promise.<ArrayBuffer, InvalidMessageException>}
     */
    var decryptWhisperMessageWithSessionState = co.wrap(function*(sessionState, whisperMessageBytes) {
        var whisperMessage = Messages.decodeWhisperMessage(whisperMessageBytes);
        var macInputTypes = Messages.decodeWhisperMessageMacInput(whisperMessageBytes);

        if (whisperMessage.version.current !== sessionState.sessionVersion) {
            throw new InvalidMessageException("Message version doesn't match session version");
        }

        var message = whisperMessage.message;
        var theirEphemeralPublicKey = message.ratchetKey;

        var receivingChain = yield getOrCreateReceivingChain(sessionState, theirEphemeralPublicKey);
        var messageKeys = yield getOrCreateMessageKeys(theirEphemeralPublicKey, receivingChain, message.counter);
        var isValid = yield isValidMac(macInputTypes, messageKeys.macKey, whisperMessage.version.current,
            sessionState.remoteIdentityKey, sessionState.localIdentityKey, whisperMessage.mac);

        if (!isValid) {
            throw new InvalidMessageException("Bad mac");
        }

        // TODO: Support for version 2: Use CTR mode instead of CBC
        var plaintext = yield crypto.decrypt(messageKeys.cipherKey, message.ciphertext, messageKeys.iv);

        sessionState.pendingPreKey = null;

        return plaintext;
    });

    /**
     * Verifies the MAC of a WhisperMessage.
     *
     * @method
     * @private
     * @param {ArrayBuffer} data - the data to calculate the MAC over
     * @param {ArrayBuffer} macKey - the MAC key
     * @param {number} messageVersion
     * @param {ArrayBuffer} senderIdentityKey
     * @param {ArrayBuffer} receiverIdentityKey
     * @param {ArrayBuffer} theirMac - the MAC to check
     * @return {Promise.<Boolean, Error>} true if theirMac is valid, false otherwise.
     */
    var isValidMac = co.wrap(function*(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey, theirMac) {
        var ourMac = yield getMac(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey);
        return ArrayBufferUtils.areEqual(ourMac, theirMac);
    });

    /**
     * Calculate the MAC of a WhisperMessage.
     *
     * @method
     * @private
     * @param {ArrayBuffer} data - the data to calculate the MAC over
     * @param {ArrayBuffer} macKey - the MAC key
     * @param {number} messageVersion
     * @param {ArrayBuffer} senderIdentityKey
     * @param {ArrayBuffer} receiverIdentityKey
     * @return {Promise.<ArrayBuffer, Error>} the MAC bytes.
     */
    var getMac = co.wrap(function*(data, macKey, messageVersion, senderIdentityKey, receiverIdentityKey) {
        var macInputs = (messageVersion >= 3) ? [senderIdentityKey, receiverIdentityKey] : [];
        macInputs.push(data);
        var macBytes = yield crypto.hmac(macKey, ArrayBufferUtils.concat(macInputs));
        return macBytes.slice(0, ProtocolConstants.macByteCount);
    });

    /**
     * Create an encrypted WhisperMessage.
     *
     * @method
     * @private
     * @param {Session} session
     * @param {ArrayBuffer} paddedMessage
     * @return {Promise.<ArrayBuffer, Error>} the bytes of an encoded WhisperMessage
     */
    var createWhisperMessage = co.wrap(function*(session, paddedMessage) {
        var messageKeys = yield ratchet.deriveMessageKeys(session.mostRecentState().sendingChain.key);
        // TODO: Should use CTR mode in version 2 of protocol
        var ciphertext = yield crypto.encrypt(messageKeys.cipherKey, paddedMessage, messageKeys.iv);

        var version = {
            current: session.mostRecentState().sessionVersion,
            max: ProtocolConstants.currentVersion
        };
        var message = {
            ratchetKey: session.mostRecentState().senderRatchetKeyPair.public,
            counter: session.mostRecentState().sendingChain.index,
            previousCounter: session.mostRecentState().previousCounter,
            ciphertext: ciphertext
        };
        var macInputBytes = Messages.encodeWhisperMessageMacInput({
            version: version,
            message: message
        });

        return Messages.encodeWhisperMessage({
            version: version,
            message: message,
            mac: yield getMac(macInputBytes, messageKeys.macKey, session.mostRecentState().sessionVersion,
                session.mostRecentState().localIdentityKey,
                session.mostRecentState().remoteIdentityKey)
        });
    });

    /**
     * Create an encrypted PreKeyWhisperMessage.
     *
     * @method
     * @private
     * @param {Session} session
     * @param {ArrayBuffer} whisperMessage - the bytes of an encoded WhisperMessage
     * @return {Promise.<ArrayBuffer, Error>} the bytes of an encoded PreKeyWhisperMessage
     */
    var createPreKeyWhisperMessage = (session, whisperMessage) => {
        var pendingPreKey = session.mostRecentState().pendingPreKey;
        return Messages.encodePreKeyWhisperMessage({
            version: {
                current: session.mostRecentState().sessionVersion,
                max: ProtocolConstants.currentVersion
            },
            message: {
                registrationId: session.mostRecentState().localRegistrationId,
                preKeyId: pendingPreKey.preKeyId,
                signedPreKeyId: pendingPreKey.signedPreKeyId,
                baseKey: pendingPreKey.baseKey,
                identityKey: session.mostRecentState().localIdentityKey,
                message: whisperMessage
            }
        });
    };

    /**
     * Find the chain for decryption that corresponds to the ephemeral key sent in their message.
     * <p>
     * This method handles stepping the main ratchet, if necessary.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} theirEphemeralPublicKey - the ephemeral key sent in the message.
     * @return {Promise.<Chain, Error>} the receiving chain
     */
    var getOrCreateReceivingChain = co.wrap(function*(sessionState, theirEphemeralPublicKey) {
        // If they've sent us multiple messages before receiving a reply from us, then those messages will be sent using
        // the same ephemeral key (i.e. the main ratchet will not click forward).
        var chain = sessionState.findReceivingChain(theirEphemeralPublicKey);
        if (chain) {
            return chain;
        }
        // This is the first message in a new chain.
        return yield clickMainRatchet(sessionState, theirEphemeralPublicKey);
    });

    /**
     * Find the message keys for decryption that correspond to the ephemeral key sent in their message.
     * <p>
     * This method handles stepping the sub ratchet, if necessary.
     *
     * @method
     * @private
     * @param {ArrayBuffer} theirEphemeralPublicKey - the ephemeral key sent in the message.
     * @param {Chain} chain - the chain for decryption.
     * @param {number} counter - the counter sent in the message.
     * @return {Promise.<MessageKeys, Error>} the message keys for decryption
     */
    var getOrCreateMessageKeys = co.wrap(function*(theirEphemeralPublicKey, chain, counter) {
        if (chain.index > counter) {
            // The message is an old message that has been delivered out of order. We should still have the message
            // key cached unless this is a duplicate message that we've seen before.
            var cachedMessageKeys = chain.messageKeys[counter];
            if (!cachedMessageKeys) {
                throw new DuplicateMessageException("Received message with old counter");
            }
            // We don't want to be able to decrypt this message again, for forward secrecy.
            delete chain.messageKeys[counter];
            return cachedMessageKeys;
        } else {
            // Otherwise, the message is a new message in the chain and we must click the sub ratchet forwards.
            if (counter - chain.index > ProtocolConstants.maximumMissedMessages) {
                throw new InvalidMessageException("Too many skipped messages");
            }
            while (chain.index < counter) {
                // Some messages have not yet been delivered ("skipped") and so we need to catch the sub ratchet up
                // while keeping the message keys for when the messages are eventually delivered.
                chain.messageKeys[chain.index] = yield ratchet.deriveMessageKeys(chain.key);
                yield ratchet.clickSubRatchet(chain);
            }
            var messageKeys = yield ratchet.deriveMessageKeys(chain.key);
            // As we have received the message, we should click the sub ratchet forwards so we can't decrypt it again
            yield ratchet.clickSubRatchet(chain);
            return messageKeys;
        }
    });

    /**
     * "clicks" the Diffie-Hellman ratchet two steps forwards. Once to catch up with the other party and once
     * more so that the next message we send will be one ahead.
     *
     * @method
     * @private
     * @param {SessionState} sessionState
     * @param {ArrayBuffer} theirEphemeralPublicKey
     * @return {Promise.<Chain, Error>} the next chain for decryption
     */
    var clickMainRatchet = co.wrap(function*(sessionState, theirEphemeralPublicKey) {
        var {
            rootKey: theirRootKey,
            chain: nextReceivingChain
        } = yield ratchet.deriveNextRootKeyAndChain(sessionState.rootKey, theirEphemeralPublicKey,
                sessionState.senderRatchetKeyPair.private);
        var ourNewEphemeralKeyPair = yield crypto.generateKeyPair();
        var {
            rootKey,
            chain: nextSendingChain
        } = yield ratchet.deriveNextRootKeyAndChain(theirRootKey,
                theirEphemeralPublicKey, ourNewEphemeralKeyPair.private);
        sessionState.rootKey = rootKey;
        sessionState.addReceivingChain(theirEphemeralPublicKey, nextReceivingChain);
        sessionState.previousCounter = Math.max(sessionState.sendingChain.index - 1, 0);
        sessionState.sendingChain = nextSendingChain;
        sessionState.senderRatchetKeyPair = ourNewEphemeralKeyPair;
        return nextReceivingChain;
    });

    Object.freeze(self);
}
306154
function (callback) {
        return new Promise((resolve, reject) => {
          this.end(result => {
            try {
              resolve(callback(result))
            } catch (err) {
              reject(err)
            }
          })
        })
      }
351903
async function() {
    const oThis = this
    ;
    const addressObj = new generateAddress({chain: 'utility', passphrase: oThis.reservePassphrase})
      , addressResponse = await addressObj.perform();
    if (addressResponse.isFailure()) {
      logger.error("* Reserve address generation failed with error:", addressResponse);
      process.exit(1);
    }
    return Promise.resolve(addressResponse);
  }
628892
function () {
	    	var deferred = $q.defer();
	    	var promise = deferred.promise;
            
            function ok(value){
                deferred.resolve(value);
            }
            
            function errorCallback(error){
                deferred.reject(new Error(error));
            }
            
            if($window.plugins){
                $window.plugins.appPreferences.show()
                    .then(ok, errorCallback);
            } else {
                deferred.reject(new Error(this.pluginNotEnabledMessage));
            }
	    	
	    	this.decoratePromise(promise);
	    	return promise;
	    }
217177
async function () {
    const oThis = this
    ;

    try {
      const getReceiptObj = new getReceipt({transaction_hash: oThis.transactionHash, chain: oThis.chain});
      const receiptResponse = await getReceiptObj.perform();
      return Promise.resolve(receiptResponse);
    } catch (err) {
      let errObj = responseHelper.error({
        internal_error_identifier: 's_sam_gas_1',
        api_error_identifier: 'something_went_wrong',
        error_config: basicHelper.fetchErrorConfig()
      });
      return Promise.resolve(errObj);
    }
  }