Generate oAuth nonce for parallel requests

I am requesting the Bitstamp API in parrallel:

// Simplified version

var async = require('async');
var bitstamp = require('bitstamp');

async.parallel([
    bitstamp.balance,
    bitstamp.ticker
    // ...
],
function() (err, result) {
    // process results
});

      

These two methods send signed requests to the Bitstamp API, including nonce .

Nonce is a regular integer. With every request, you must increase. More about this here. Example: if you set the nonce to 1 in your first request, you must set it to at least 2 in the second request. You are not required to start at 1. It is common practice to use unix time for this parameter.

The base library generates the traditional nonce way:

var nonce = new Date().getTime() + '' + new Date().getMilliseconds();

      

Problem

Due to asynchronous API calls, sometimes the nonce generates it for the very same millisecond, and the remote side wants them to increase.

Question

While keeping the queries parallel, any idea to reliably generate sequential nonces?

My obvious attempt:

this.nonce = new Date().getTime() + '' + new Date().getMilliseconds(); 
// ... on request
var nonce = this.nonce++;

      

But this does not solve the problem, the same millisecond just increases by one, but it is still equal.

+3


source to share


3 answers


npm module nonce now generates it correctly



0


source


(the author of the npm module is here)



I solved it by adding my counter at the end of the ms timestamp. This feature now supports up to 999 calls per ms because of this feature . For the first time it will generate something like 1409074885767000

, and if you need a new nonce for the same ms, it will generate 1409074885767001

, 1409074885767002

...

+3


source


I had exactly the same problem, so I took the askmike code and modified it a bit.

var nonce = new (function() {

    this.generate = function() {

        var now = Date.now();

        this.counter = (now === this.last? this.counter + 1 : 0);
        this.last    = now;

        // add padding to nonce
        var padding = 
            this.counter < 10 ? '000' : 
                this.counter < 100 ? '00' :
                    this.counter < 1000 ?  '0' : '';

        return now+padding+this.counter;
    };
})();

      

use it like this

nonce.generate();

      

check out jsfiddle with example

+1


source







All Articles