Skip to content

Commit

Permalink
Optimize for zero or negative interruptStep.
Browse files Browse the repository at this point in the history
If interruptStep is <= 0, avoid calling setTimeout, and calculate result
immediately, passing it to callback.
  • Loading branch information
dchest committed May 10, 2015
1 parent 6b010d0 commit 49510e0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
42 changes: 28 additions & 14 deletions scrypt-async.js
Original file line number Diff line number Diff line change
Expand Up @@ -424,11 +424,11 @@ function scrypt(password, salt, logN, r, dkLen, interruptStep, callback, encodin
})();
}

function getResult() {
function getResult(enc) {
var result = PBKDF2_HMAC_SHA256_OneIter(password, B, dkLen);
if (encoding === 'base64')
if (enc === 'base64')
return bytesToBase64(result);
else if (encoding === 'hex')
else if (enc === 'hex')
return bytesToHex(result);
else
return result;
Expand All @@ -448,23 +448,37 @@ function scrypt(password, salt, logN, r, dkLen, interruptStep, callback, encodin
encoding = interruptStep;
}

if (!isSync) {
// Async variant, calls callback with result.
if (isSync) {
//
// Sync variant, returns result.
//
smixStart();
interruptedFor(0, N, interruptStep*2, smixStep1, function() {
interruptedFor(0, N, interruptStep*2, smixStep2, function () {
smixFinish();
callback(getResult());
});
});
smixStep1(0, N);
smixStep2(0, N);
smixFinish();
return getResult(encoding);

} else {
// Sync variant, returns result.
} else if (interruptStep <= 0) {
//
// Blocking async variant, calls callback.
//
smixStart();
smixStep1(0, N);
smixStep2(0, N);
smixFinish();
return getResult();
callback(getResult(encoding));

} else {
//
// Async variant with interruptions, calls callback.
//
smixStart();
interruptedFor(0, N, interruptStep*2, smixStep1, function() {
interruptedFor(0, N, interruptStep*2, smixStep2, function () {
smixFinish();
callback(getResult(encoding));
});
});
}
}

Expand Down
7 changes: 7 additions & 0 deletions test/unittests.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,13 @@ describe('argument order test', function() {
}, "hex");
});

it('all arguments, zero interruptStep', function(done) {
scrypt(v.password, v.salt, v.logN, v.r, v.dkLen, 0, function(out) {
assert.equal(v.hexResult, out);
done();
}, "hex");
});

it('drop encoding', function(done) {
scrypt(v.password, v.salt, v.logN, v.r, v.dkLen, 1000, function(out) {
assert.deepEqual(v.result, out);
Expand Down

0 comments on commit 49510e0

Please sign in to comment.