inital commit

This commit is contained in:
Matthew Little 2014-01-06 15:17:35 -05:00
commit 59bb062dac
69 changed files with 6941 additions and 0 deletions

18
blockNotify.js Normal file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env node
var net = require('net');
var client = net.connect({port: 8124}, function() {
console.log('client connected');
client.write(JSON.stringify(process.argv) + '\n');
});
client.on('data', function(data) {
console.log(data.toString());
//client.end();
});
client.on('end', function() {
console.log('client disconnected');
//process.exit();
});

53
blockTemplate.js Normal file
View File

@ -0,0 +1,53 @@
var merkleTree = require('./merkleTree.js');
var coinbase = require('./coinbase.js');
var util = require('./util.js');
var BlockTemplate = module.exports = function BlockTemplate(jobId, rpcData, address){
//private members
function getMerkleHashes(steps){
return steps.map(function(step){
return util.reverseBuffer(step).toString('hex');
});
}
function getTransactionBuffers(txs){
var txHashes = txs.map(function(tx){
return util.uint256BufferFromHash(tx.hash);
});
return [null].concat(txHashes);
}
//public members
this.rpcData = rpcData;
this.jobId = jobId;
this.merkleTree = new merkleTree(getTransactionBuffers(rpcData.transactions));
this.merkleBranch = getMerkleHashes(this.merkleTree.steps);
this.coinbase = new coinbase.GenerationTransaction(
rpcData.coinbasevalue,
rpcData.coinbaseaux.flags,
rpcData.height,
address
);
this.getJobParams = function(){
if (!this.jobParams){
this.jobParams = [
this.jobId,
util.reverseHex(this.rpcData.previousblockhash),
this.coinbase.serialized[0].toString('hex'),
this.coinbase.serialized[1].toString('hex'),
this.merkleBranch,
binpack.packInt32(this.rpcData.version, 'big').toString('hex'),
this.rpcData.bits,
binpack.packUInt32(this.rpcData.curtime, 'big').toString('hex'),
true
];
}
return this.jobParams;
}
}

151
coinbase.js Normal file
View File

@ -0,0 +1,151 @@
var binpack = require('/usr/lib/node_modules/binpack');
var buffertools = require('/usr/lib/node_modules/buffertools');
var util = require('./util.js');
function COutPoint(){
this.hash = 0;
this.n = 0;
}
COutPoint.prototype = {
deserialize: function(f){
this.hash = util.hexFromReversedBuffer(f.read(32));
this.n = f.read(4).readUInt32LE(0);
},
serialize: function(){
return Buffer.concat([
util.uint256BufferFromHash(this.hash),
binpack.packUInt32(this.n, 'little')
]);
}
};
function CTxIn(){
this.prevout = new COutPoint();
this.scriptSig = "";
this.nSequence = 0;
}
CTxIn.prototype = {
deserialize: function(f){
this.prevout = new COutPoint();
this.prevout.deserialize(f);
this.scriptSig = util.deser_string(f);
this.nSequence = f.read(4).readUInt32LE(0);
},
serialize: function(){
return Buffer.concat([
this.prevout.serialize(),
util.ser_string(this.scriptSig),
binpack.packUInt32(this.nSequence, 'little')
]);
}
};
function CTxOut(){
this.nValue = 0;
this.scriptPubKey = '';
}
CTxOut.prototype = {
deserialize: function(f){
this.nValue = f.read(8).readInt64LE(0);
this.scriptPubKey = util.deser_string(f);
},
serialize: function(){
return Buffer.concat([
binpack.packInt64(this.nValue, 'little'),
util.ser_string(this.scriptPubKey)
]);
}
};
function CTransaction(){
this.nVersion = 1;
this.vin = [];
this.vout = [];
this.nLockTime = 0;
this.sha256 = null;
};
CTransaction.prototype = {
deserialize: function(f){
util.makeBufferReadable(f);
this.nVersion = f.read(4).readInt32LE(0);
this.vin = util.deser_vector(f, CTxIn);
this.vout = util.deser_vector(f, CTxOut);
this.nLockTime = r.read(4).readUInt32LE(0);
this.sha256 = null;
},
serialize: function(){
return Buffer.concat([
binpack.packInt32(this.nVersion, 'little'),
util.ser_vector(this.vin),
util.ser_vector(this.vout),
binpack.packUInt32(this.nLockTime, 'little')
]);
}
};
exports.CTransaction = CTransaction;
var extranonce_placeholder = new Buffer('f000000ff111111f', 'hex');
exports.extranonce_size = extranonce_placeholder.length;
function GenerationTransaction(coinbaseValue, coinbaseAuxFlags, height, address){
var CTrans = new CTransaction();
var tx_in = new CTxIn();
tx_in.prevout.hash = 0;
tx_in.prevout.n = Math.pow(2, 32) - 1;
tx_in._scriptSig_template = [
Buffer.concat([
util.serializeNumber(height),
new Buffer(coinbaseAuxFlags, 'hex'),
util.serializeNumber(Date.now() / 1000 | 0),
new Buffer([exports.extranonce_size])
]),
util.ser_string('/stratum/')
];
tx_in.scriptSig = Buffer.concat([
tx_in._scriptSig_template[0],
extranonce_placeholder,
tx_in._scriptSig_template[1]
]);
var tx_out = new CTxOut();
tx_out.nValue = coinbaseValue;
tx_out.scriptPubKey = util.script_to_address(address);
CTrans.vin.push(tx_in);
CTrans.vout.push(tx_out);
var cTransBin = CTrans.serialize();
var epIndex = buffertools.indexOf(cTransBin, extranonce_placeholder);
var p1 = cTransBin.slice(0, epIndex);
var p2 = cTransBin.slice(epIndex + extranonce_placeholder.length);
this.tx = CTrans;
this.serialized = [p1, p2];
}
GenerationTransaction.prototype = {
setExtraNonce: function(extraNonce){
if (extraNonce.length != exports.extranonce_size){
throw "Incorrect extranonce size";
}
var part1 = this.tx.vin[0]._scriptSig_template[0];
var part2 = this.tx.vin[0]._scriptSig_template[1];
this.tx.vin[0].scriptSig = Buffer.concat([
part1,
extraNonce,
part2
]);
}
};
exports.GenerationTransaction = GenerationTransaction;

110
daemon.js Normal file
View File

@ -0,0 +1,110 @@
var http = require('http');
var cp = require('child_process');
var events = require('events');
var startFailedTimeout = 120; //seconds
function DaemonInterface(options){
//private members
var _this = this;
(function init(){
isOnline(function(online){
if (online)
_this.emit('online');
else if (options.startIfOffline){
me.start();
emitOnline();
}
});
})();
function emitOnline(){
var startedTime = Date.now();
var checkFunc = function(){
isOnline(function(online){
if (online)
_this.emit('online');
else if (Date.now() - startedTime < startFailedTimeout * 1000)
setTimeout(checkFunc, 2000);
else
_this.emit('startFailed');
});
};
checkFunc();
}
function isOnline(callback){
this.cmd('getinfo', [], function(error, result){
if (error)
callback(false);
else
callback(true);
});
}
//public members
this.isOnline = isOnline;
this.start = function(){
var cmdArgs = [
'-rpcport=' + this.options.port,
'-rpcuser=' + this.options.user,
'-rpcpassword=' + this.options.password,
'-blocknotify=' + this.options.blocknotify
];
var child = cp.spawn(this.options.bin, cmdArgs, { detached: true, stdio: [ 'ignore', 'ignore', 'ignore' ] });
child.unref();
console.log('started daemon');
};
this.cmd = function(method, params, callback){
var requestJson = JSON.stringify({
id: Date.now() + Math.floor(Math.random() * 10),
method: method,
params: params
});
var options = {
hostname: 'localhost',
port: this.options.port,
method: 'POST',
auth: this.options.user + ':' + this.options.password,
headers: {
'Content-Length': requestJson.length
}
};
var req = http.request(options, function(res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function(){
var dataJson = JSON.parse(data);
callback(null, dataJson);
});
});
req.on('error', function(e) {
if (e.code === 'ECONNREFUSED')
callback({type: 'offline', message: e.message});
else
callback({type: 'request error', message: e.message});
});
req.end(requestJson);
}
}
DaemonInterface.prototype.__proto__ = events.EventEmitter.prototype;
exports.interface = DaemonInterface;

822
exampleBlockTemplate.json Normal file

File diff suppressed because one or more lines are too long

78
jobManager.js Normal file
View File

@ -0,0 +1,78 @@
var events = require('events');
var binpack = require('/usr/lib/node_modules/binpack');
var bignum = require('/usr/lib/node_modules/bignum');
var merkleTree = require('./merkleTree.js');
var coinbase = require('./coinbase.js');
var util = require('./util.js');
var blockTemplate = require('./blockTemplate.js');
/*
For each crypto currency have a templating instance which holds an array of jobs.
jobs all hold slightly modified block templates that all have the same prev hash.
any jobs with outdated prevhash should be purged.
*/
//Unique extranonce per subscriber
var ExtraNonceCounter = function(){
var instanceId = 31;
var counter = instanceId << 27;
var size = 4;
this.next = function(){
var extraNonce = binpack.packUInt32(counter++, 'big');
return extraNonce.toString('hex');
};
this.size = function(){
return size;
};
};
//Unique job per new block template
var JobCounter = function(){
var counter = 0;
this.next = function(){
counter++;
if (counter % 0xffff == 0)
counter = 1;
return counter.toString(16);
};
};
var JobManager = module.exports = function JobManager(options){
//private members
var _this = this;
var jobCounter = new JobCounter();
var jobs = {};
function CheckNewIfNewBlock(blockTemplate){
var newBlock = true;
for(var job in jobs){
if (jobs[job].rpcData.previousblockhash == blockTemplate.rpcData.previousblockhash)
newBlock = false;
}
if (newBlock)
_this.emit('newBlock', blockTemplate);
}
//public members
this.extraNonceCounter = new ExtraNonceCounter();
this.currentJob;
this.newTemplate = function(rpcData){
this.currentJob = new blockTemplate(jobCounter.next(), rpcData, options.address);
jobs[this.currentJob.jobId] = this.currentJob;
CheckNewIfNewBlock(this.currentJob);
};
};
JobManager.prototype.__proto__ = events.EventEmitter.prototype;

82
merkleTree.js Normal file
View File

@ -0,0 +1,82 @@
var util = require('./util.js');
/*var merkleJoin = function(h1, h2){
var buff1 = new Buffer(h1, 'hex');
var buff2 = new Buffer(h2, 'hex');
var buffJoined = Buffer.concat([buff2, buff1]);
var buffJSON = buffJoined.toJSON();
buffJSON.reverse();
var buffReversed = new Buffer(buffJSON);
var hash2 = util.doublesha(buffReversed);
var dhashJSON = hash2.toJSON();
dhashJSON.reverse();
var dhash = new Buffer(dhashJSON);
return dhash.toString('hex');
};*/
var MerkleTree = module.exports = function MerkleTree(data){
function merkleJoin(h1, h2){
var joined = Buffer.concat([h1, h2]);
var dhashed = util.doublesha(joined);
return dhashed;
}
function calculateSteps(data){
var L = data;
var steps = [];
var PreL = [null];
var StartL = 2;
var Ll = L.length;
if (Ll > 1){
while (true){
if (Ll == 1)
break;
steps.push(L[1]);
if (Ll % 2)
L.push(L[L.length - 1]);
var Ld = [];
var r = util.range(StartL, Ll, 2);
r.forEach(function(i){
Ld.push(merkleJoin(L[i], L[i + 1]));
});
L = PreL.concat(Ld);
Ll = L.length;
}
}
return steps;
}
this.data = data;
this.steps = calculateSteps(data);
}
MerkleTree.prototype = {
hashSteps: function(){
if (!this.stepsHash)
this.stepsHash = util.doublesha(Buffer.concat(this.steps));
return this.stepsHash;
},
withFirst: function(f){
this.steps.forEach(function(s){
f = util.doublesha(Buffer.concat([f, s]));
});
return f;
},
merkleRoot: function(){
return this.withFirst(this.data[0]);
}
};

2
node_modules/base58-native/.npmignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
build
node_modules

27
node_modules/base58-native/LICENSE generated vendored Normal file
View File

@ -0,0 +1,27 @@
Copyright 2013 BitPay, Inc.
Copyright (c) 2011 Stefan Thomas <justmoon@members.fsf.org>
Native extensions are
Copyright (c) 2011 Andrew Schaaf <andrew@andrewschaaf.com>
Parts of this software are based on BitcoinJ
Copyright (c) 2011 Google Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

29
node_modules/base58-native/README.md generated vendored Normal file
View File

@ -0,0 +1,29 @@
base58
======
An implementation of Base58 and Base58Check encodings for nodejs. Note, the
implementation of Base58Check differs slightly from that described on Wikipedia
in that it does not prepend a version byte onto the data being encoded. This
implementation uses the bignum library (which is a native module and uses the
openssl bignumber library functions).
NOTE: earlier versions of this package used native C code instead of bignum, but
it was found to be unstable in a production environment (likely due to bugs in the
C code). This version uses bignum and appears to be very stable, but slower. The
C version of this package is still available on the "native-module" branch. A few
additional methods added to bignum would probably bring the speed of this version
on part with with C version.
Installation
============
npm install base58-native
Usage
=====
var base58 = require('base58-native');
base58.encode(base58.decode('mqqa8xSMVDyf9QxihGnPtap6Mh6qemUkcu'));
var base58Check = require('base58-native').base58Check;
base58Check.encode(base58Check.decode('mqqa8xSMVDyf9QxihGnPtap6Mh6qemUkcu'));

116
node_modules/base58-native/base58.js generated vendored Normal file
View File

@ -0,0 +1,116 @@
var crypto = require('crypto');
var bignum = require('bignum');
var globalBuffer = new Buffer(1024);
var zerobuf = new Buffer(0);
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var ALPHABET_ZERO = ALPHABET[0];
var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii');
var ALPHABET_INV = {};
for(var i=0; i < ALPHABET.length; i++) {
ALPHABET_INV[ALPHABET[i]] = i;
};
// Vanilla Base58 Encoding
var base58 = {
encode: function(buf) {
var str;
var x = bignum.fromBuffer(buf);
var r;
if(buf.length < 512) {
str = globalBuffer;
} else {
str = new Buffer(buf.length << 1);
}
var i = str.length - 1;
while(x.gt(0)) {
r = x.mod(58);
x = x.div(58);
str[i] = ALPHABET_BUF[r.toNumber()];
i--;
}
// deal with leading zeros
var j=0;
while(buf[j] == 0) {
str[i] = ALPHABET_BUF[0];
j++; i--;
}
return str.slice(i+1,str.length).toString('ascii');
},
decode: function(str) {
if(str.length == 0) return zerobuf;
var answer = bignum(0);
for(var i=0; i<str.length; i++) {
answer.mul(58)
answer = answer.mul(58);
answer = answer.add(ALPHABET_INV[str[i]]);
};
var i = 0;
while(i < str.length && str[i] == ALPHABET_ZERO) {
i++;
}
if(i > 0) {
var zb = new Buffer(i);
zb.fill(0);
if(i == str.length) return zb;
answer = answer.toBuffer();
return Buffer.concat([zb, answer], i+answer.length);
} else {
return answer.toBuffer();
}
},
};
// Base58Check Encoding
function sha256(data) {
return new Buffer(crypto.createHash('sha256').update(data).digest('binary'), 'binary');
};
function doubleSHA256(data) {
return sha256(sha256(data));
};
var base58Check = {
encode: function(buf) {
var checkedBuf = new Buffer(buf.length + 4);
var hash = doubleSHA256(buf);
buf.copy(checkedBuf);
hash.copy(checkedBuf, buf.length);
return base58.encode(checkedBuf);
},
decode: function(s) {
var buf = base58.decode(s);
if (buf.length < 4) {
throw new Error("invalid input: too short");
}
var data = buf.slice(0, -4);
var csum = buf.slice(-4);
var hash = doubleSHA256(data);
var hash4 = hash.slice(0, 4);
if (csum.toString() != hash4.toString()) {
throw new Error("checksum mismatch");
}
return data;
},
};
// if you frequently do base58 encodings with data larger
// than 512 bytes, you can use this method to expand the
// size of the reusable buffer
exports.setBuffer = function(buf) {
globalBuffer = buf;
};
exports.base58 = base58;
exports.base58Check = base58Check;
exports.encode = base58.encode;
exports.decode = base58.decode;

56
node_modules/base58-native/package.json generated vendored Normal file
View File

@ -0,0 +1,56 @@
{
"name": "base58-native",
"description": "An Implementation of Base58 and Base58Check encoding using bignum library.",
"version": "0.1.3",
"author": {
"name": "Satoshi Nakamoto",
"email": "satoshin@gmx.com"
},
"contributors": [
{
"name": "Stefan Thomas",
"email": "moon@justmoon.net"
},
{
"name": "Andrew Schaaf",
"email": "andrew@andrewschaaf.com"
},
{
"name": "Jeff Garzik",
"email": "jgarzik@bitpay.com"
},
{
"name": "Stephen Pair",
"email": "stephen@bitpay.com"
}
],
"main": "./base58",
"keywords": [
"base58",
"base58check",
"base64",
"encoding"
],
"repository": {
"type": "git",
"url": "http://github.com/gasteve/node-base58.git"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"bignum": ">=0.6.1"
},
"devDependencies": {
"mocha": ">1.0.0"
},
"license": "MIT",
"readme": "base58\n======\n\nAn implementation of Base58 and Base58Check encodings for nodejs. Note, the\nimplementation of Base58Check differs slightly from that described on Wikipedia\nin that it does not prepend a version byte onto the data being encoded. This\nimplementation uses the bignum library (which is a native module and uses the\nopenssl bignumber library functions).\n\nNOTE: earlier versions of this package used native C code instead of bignum, but\nit was found to be unstable in a production environment (likely due to bugs in the\nC code). This version uses bignum and appears to be very stable, but slower. The\nC version of this package is still available on the \"native-module\" branch. A few\nadditional methods added to bignum would probably bring the speed of this version \non part with with C version. \n\nInstallation\n============\n\n npm install base58-native\n\nUsage\n=====\n\n var base58 = require('base58-native');\n base58.encode(base58.decode('mqqa8xSMVDyf9QxihGnPtap6Mh6qemUkcu'));\n\n var base58Check = require('base58-native').base58Check;\n base58Check.encode(base58Check.decode('mqqa8xSMVDyf9QxihGnPtap6Mh6qemUkcu'));\n",
"readmeFilename": "README.md",
"bugs": {
"url": "https://github.com/gasteve/node-base58/issues"
},
"homepage": "https://github.com/gasteve/node-base58",
"_id": "base58-native@0.1.3",
"_from": "base58-native@"
}

49
node_modules/base58-native/test/basic.js generated vendored Normal file
View File

@ -0,0 +1,49 @@
var assert = require('assert');
var base58 = require('..').base58;
var base58Check = require('..').base58Check;
var testData = [
["61", "2g", "C2dGTwc"],
["626262", "a3gV", "4jF5uERJAK"],
["636363", "aPEr", "4mT4krqUYJ"],
["73696d706c792061206c6f6e6720737472696e67", "2cFupjhnEsSn59qHXstmK2ffpLv2", "BXF1HuEUCqeVzZdrKeJjG74rjeXxqJ7dW"],
["00eb15231dfceb60925886b67d065299925915aeb172c06647", "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L", "13REmUhe2ckUKy1FvM7AMCdtyYq831yxM3QeyEu4"],
["516b6fcd0f", "ABnLTmg", "237LSrY9NUUas"],
["bf4f89001e670274dd", "3SEo3LWLoPntC", "GwDDDeduj1jpykc27e"],
["572e4794", "3EFU7m", "FamExfqCeza"],
["ecac89cad93923c02321", "EJDM8drfXA6uyA", "2W1Yd5Zu6WGyKVtHGMrH"],
["10c8511e", "Rt5zm", "3op3iuGMmhs"],
["00000000000000000000", "1111111111", "111111111146Momb"],
["", "", "3QJmnh"]
];
suite('basic');
test('allData', function() {
base58.encodeTest = function(raw, b58str) {
assert.equal(base58.encode(raw), b58str);
};
base58.decodeTest = function(raw, b58str) {
assert.equal(raw.toString('hex'), base58.decode(b58str).toString('hex'));
};
base58Check.encodeTest = function(raw, b58str) {
assert.equal(base58Check.encode(raw), b58str);
};
base58Check.decodeTest = function(raw, b58str) {
assert.equal(raw.toString('hex'), base58Check.decode(b58str).toString('hex'));
};
testData.forEach(function(datum) {
var raw = new Buffer(datum[0], 'hex');
var b58 = datum[1];
var b58Check = datum[2];
base58.encodeTest(raw, b58);
base58.decodeTest(raw, b58);
base58Check.encodeTest(raw, b58Check);
base58Check.decodeTest(raw, b58Check);
});
});

1
node_modules/base58-native/test/mocha.opts generated vendored Normal file
View File

@ -0,0 +1 @@
--ui qunit

1
node_modules/bignum/.npmignore generated vendored Normal file
View File

@ -0,0 +1 @@
build

5
node_modules/bignum/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.11"
- "0.10"
- "0.8"

327
node_modules/bignum/README.markdown generated vendored Normal file
View File

@ -0,0 +1,327 @@
bignum
======
Arbitrary precision integral arithmetic for Node.js using
OpenSSL.
This library is based on
[node-bigint](https://github.com/substack/node-bigint) by
[substack](https://github.com/substack), but instead of using libgmp,
it uses the builtin bignum functionality provided by OpenSSL. The
advantage is that OpenSSL is already part of Node.js, so this
library does not add any external dependency whatsoever.
differences
===========
When switching from node-bigint to node-bignum, please be aware of
these differences:
- Bignum rounds towards zero for integer divisions, e.g. `10 / -3 = -3`, whereas bigint
rounds towards negative infinity, e.g. `10 / -3 = -4`.
- Bitwise operations (and, or, xor) are implemented for positive numbers only.
- nextPrime() is not supported.
- sqrt() and root() are not supported.
(Patches for the missing functionality are welcome.)
example
=======
simple.js
---------
var bignum = require('bignum');
var b = bignum('782910138827292261791972728324982')
.sub('182373273283402171237474774728373')
.div(8)
;
console.log(b);
***
$ node simple.js
<Bignum 75067108192986261319312244199576>
perfect.js
----------
Generate the perfect numbers:
// If 2**n-1 is prime, then (2**n-1) * 2**(n-1) is perfect.
var bignum = require('bignum');
for (var n = 0; n < 100; n++) {
var p = bignum.pow(2, n).sub(1);
if (p.probPrime(50)) {
var perfect = p.mul(bignum.pow(2, n - 1));
console.log(perfect.toString());
}
}
***
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128
2658455991569831744654692615953842176
191561942608236107294793378084303638130997321548169216
methods[0]
==========
bignum(n, base=10)
------------------
Create a new `bignum` from `n` and a base. `n` can be a string, integer, or
another `bignum`.
If you pass in a string you can set the base that string is encoded in.
.toString(base=10)
------------------
Print out the `bignum` instance in the requested base as a string.
bignum.fromBuffer(buf, opts)
----------------------------
Create a new `bignum` from a `Buffer`.
The default options are:
{
endian : 'big',
size : 1, // number of bytes in each word
}
Note that endian doesn't matter when size = 1. If you wish to reverse the entire buffer byte by byte, pass size: 'auto'.
bignum.prime(bits, safe=true)
-----------------------------
Generate a probable prime of length `bits`. If `safe` is true, it will be a "safe" prime of the form p=2p'+1 where p' is also prime.
methods[1]
==========
For all of the instance methods below you can write either
bignum.method(x, y, z)
or if x is a `bignum` instance``
x.method(y, z)
.toNumber()
-----------
Turn a `bignum` into a `Number`. If the `bignum` is too big you'll lose
precision or you'll get ±`Infinity`.
.toBuffer(opts)
-------------
Return a new `Buffer` with the data from the `bignum`.
The default options are:
{
endian : 'big',
size : 1, // number of bytes in each word
}
Note that endian doesn't matter when size = 1. If you wish to reverse the entire buffer byte by byte, pass size: 'auto'.
.add(n)
-------
Return a new `bignum` containing the instance value plus `n`.
.sub(n)
-------
Return a new `bignum` containing the instance value minus `n`.
.mul(n)
-------
Return a new `bignum` containing the instance value multiplied by `n`.
.div(n)
-------
Return a new `bignum` containing the instance value integrally divided by `n`.
.abs()
------
Return a new `bignum` with the absolute value of the instance.
.neg()
------
Return a new `bignum` with the negative of the instance value.
.cmp(n)
-------
Compare the instance value to `n`. Return a positive integer if `> n`, a
negative integer if `< n`, and 0 if `== n`.
.gt(n)
------
Return a boolean: whether the instance value is greater than n (`> n`).
.ge(n)
------
Return a boolean: whether the instance value is greater than or equal to n
(`>= n`).
.eq(n)
------
Return a boolean: whether the instance value is equal to n (`== n`).
.lt(n)
------
Return a boolean: whether the instance value is less than n (`< n`).
.le(n)
------
Return a boolean: whether the instance value is less than or equal to n
(`<= n`).
.and(n)
-------
Return a new `bignum` with the instance value bitwise AND (&)-ed with `n`.
.or(n)
------
Return a new `bignum` with the instance value bitwise inclusive-OR (|)-ed with
`n`.
.xor(n)
-------
Return a new `bignum` with the instance value bitwise exclusive-OR (^)-ed with
`n`.
.mod(n)
-------
Return a new `bignum` with the instance value modulo `n`.
`m`.
.pow(n)
-------
Return a new `bignum` with the instance value raised to the `n`th power.
.powm(n, m)
-----------
Return a new `bignum` with the instance value raised to the `n`th power modulo
`m`.
.invertm(m)
-----------
Compute the multiplicative inverse modulo `m`.
.rand()
-------
.rand(upperBound)
-----------------
If `upperBound` is supplied, return a random `bignum` between the instance value
and `upperBound - 1`, inclusive.
Otherwise, return a random `bignum` between 0 and the instance value - 1,
inclusive.
.probPrime()
------------
Return whether the bignum is:
* certainly prime (true)
* probably prime ('maybe')
* certainly composite (false)
using [BN_is_prime_ex](http://www.openssl.org/docs/crypto/BN_generate_prime.html).
.sqrt()
-------
Return a new `bignum` that is the square root. This truncates.
.root(n)
-------
Return a new `bignum` that is the `nth` root. This truncates.
.shiftLeft(n)
-------------
Return a new `bignum` that is the `2^n` multiple. Equivalent of the `<<`
operator.
.shiftRight(n)
--------------
Return a new `bignum` of the value integer divided by
`2^n`. Equivalent of the `>>` operator.
.gcd(n)
-------
Return the greatest common divisor of the current `bignum` with `n` as a new
`bignum`.
.jacobi(n)
-------
Return the Jacobi symbol (or Legendre symbol if `n` is prime) of the current
`bignum` (= a) over `n`. Note that `n` must be odd and >= 3. 0 <= a < n.
Returns -1 or 1 as an int (NOT a bignum). Throws an error on failure.
.bitLength()
------------
Return the number of bits used to represent the current `bignum`.
install
=======
To compile the package, your system needs to be set up for building Node.js
modules.
You can install node-bignum with [npm](http://npmjs.org):
npm install bignum
develop
=======
You can clone the git repo and compile with
git clone git://github.com/justmoon/node-bignum.git
cd node-bignum
npm install
Run the tests with
npm test

972
node_modules/bignum/bignum.cc generated vendored Normal file
View File

@ -0,0 +1,972 @@
#include <stdint.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <v8.h>
#include <node.h>
#include <openssl/bn.h>
#include <map>
#include <utility>
using namespace v8;
using namespace node;
using namespace std;
#define REQ_STR_ARG(I, VAR) \
if (args.Length()<= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a string"))); \
Local<String> VAR = Local<String>::Cast(args[I]);
#define REQ_UTF8_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a utf8 string"))); \
String::Utf8Value VAR(args[I]->ToString());
#define REQ_INT32_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsInt32()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be an int32"))); \
int32_t VAR = args[I]->ToInt32()->Value();
#define REQ_UINT32_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsUint32()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a uint32"))); \
uint32_t VAR = args[I]->ToUint32()->Value();
#define REQ_INT64_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsNumber()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be an int64"))); \
int64_t VAR = args[I]->ToInteger()->Value();
#define REQ_UINT64_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsNumber()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a uint64"))); \
uint64_t VAR = args[I]->ToInteger()->Value();
#define REQ_BOOL_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsBoolean()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a boolean"))); \
bool VAR = args[I]->ToBoolean()->Value();
#define WRAP_RESULT(RES, VAR) \
Handle<Value> arg[1] = { External::New(static_cast<BigNum*>(RES)) }; \
Local<Object> VAR = constructor_template->GetFunction()->NewInstance(1, arg);
class AutoBN_CTX
{
protected:
BN_CTX* ctx;
BN_CTX* operator=(BN_CTX* ctx_new) { return ctx = ctx_new; }
public:
AutoBN_CTX()
{
ctx = BN_CTX_new();
// TODO: Handle ctx == NULL
}
~AutoBN_CTX()
{
if (ctx != NULL)
BN_CTX_free(ctx);
}
operator BN_CTX*() { return ctx; }
BN_CTX& operator*() { return *ctx; }
BN_CTX** operator&() { return &ctx; }
bool operator!() { return (ctx == NULL); }
};
/**
* BN_jacobi_priv() computes the Jacobi symbol of A with respect to N.
*
* Hence, *jacobi = 1 when the jacobi symbol is unity and *jacobi = -1 when the
* jacobi symbol is -1. N must be odd and >= 3. It is required that 0 <= A < N.
*
* When successful 0 is returned. -1 is returned on failure.
*
* This is an implementation of an iterative version of Algorithm 2.149 on page
* 73 of the book "Handbook of Applied Cryptography" by Menezes, Oorshot,
* Vanstone. Note that there is a typo in step 1. Step 1 should return the value
* 1. The algorithm has a running time of O((lg N)^2) bit operations.
*
* @author Adam L. Young
*/
int BN_jacobi_priv(const BIGNUM *A,const BIGNUM *N,int *jacobi,
BN_CTX *ctx)
{
int e,returnvalue=0,s,bit0,bit1,bit2,a1bit0,a1bit1;
BIGNUM *zero,*a1,*n1,*three,*tmp;
if (!jacobi)
return -1;
*jacobi = 1;
if ((!A) || (!N) || (!ctx))
return -1;
if (!BN_is_odd(N))
return -1; /* ERROR: BN_jacobi() given an even N */
if (BN_cmp(A,N) >= 0)
return -1;
n1=BN_new();zero=BN_new();a1=BN_new();three=BN_new();tmp=BN_new();
BN_set_word(zero,0);
BN_set_word(three,3);
if (BN_cmp(N,three) < 0)
{ /* This function was written by Adam L. Young */
returnvalue = -1;
goto endBN_jacobi;
}
if (BN_cmp(zero,A) > 0)
{
returnvalue = -1;
goto endBN_jacobi;
}
BN_copy(a1,A);
BN_copy(n1,N);
startjacobistep1:
if (BN_is_zero(a1)) /* step 1 */
goto endBN_jacobi; /* *jacobi = 1; */
if (BN_is_one(a1)) /* step 2 */
goto endBN_jacobi; /* *jacobi = 1; */
for (e=0;;e++) /* step 3 */
if (BN_is_odd(a1))
break;
else
BN_rshift1(a1,a1);
s = 1; /* step 4 */
bit0 = BN_is_odd(n1);
bit1 = BN_is_bit_set(n1,1);
if (e % 2)
{
bit2 = BN_is_bit_set(n1,2);
if ((!bit2) && (bit1) && (bit0))
s = -1;
if ((bit2) && (!bit1) && (bit0))
s = -1;
}
a1bit0 = BN_is_odd(a1); /* step 5 */
a1bit1 = BN_is_bit_set(a1,1);
if (((bit1) && (bit0)) && ((a1bit1) && (a1bit0)))
s = -s;
BN_mod(n1,n1,a1,ctx); /* step 6 */
BN_copy(tmp,a1);
BN_copy(a1,n1);
BN_copy(n1,tmp);
*jacobi *= s; /* step 7 */
goto startjacobistep1;
endBN_jacobi:
BN_clear_free(zero);
BN_clear_free(tmp);BN_clear_free(a1);
BN_clear_free(n1);BN_clear_free(three);
return returnvalue;
}
class BigNum : ObjectWrap {
public:
static void Initialize(Handle<Object> target);
BIGNUM bignum_;
static Persistent<Function> js_conditioner;
static void SetJSConditioner(Persistent<Function> constructor);
protected:
static Persistent<FunctionTemplate> constructor_template;
BigNum(const String::Utf8Value& str, uint64_t base);
BigNum(uint64_t num);
BigNum(int64_t num);
BigNum(BIGNUM *num);
BigNum();
~BigNum();
static Handle<Value> New(const Arguments& args);
static Handle<Value> ToString(const Arguments& args);
static Handle<Value> Badd(const Arguments& args);
static Handle<Value> Bsub(const Arguments& args);
static Handle<Value> Bmul(const Arguments& args);
static Handle<Value> Bdiv(const Arguments& args);
static Handle<Value> Uadd(const Arguments& args);
static Handle<Value> Usub(const Arguments& args);
static Handle<Value> Umul(const Arguments& args);
static Handle<Value> Udiv(const Arguments& args);
static Handle<Value> Umul_2exp(const Arguments& args);
static Handle<Value> Udiv_2exp(const Arguments& args);
static Handle<Value> Babs(const Arguments& args);
static Handle<Value> Bneg(const Arguments& args);
static Handle<Value> Bmod(const Arguments& args);
static Handle<Value> Umod(const Arguments& args);
static Handle<Value> Bpowm(const Arguments& args);
static Handle<Value> Upowm(const Arguments& args);
static Handle<Value> Upow(const Arguments& args);
static Handle<Value> Uupow(const Arguments& args);
static Handle<Value> Brand0(const Arguments& args);
static Handle<Value> Uprime0(const Arguments& args);
static Handle<Value> Probprime(const Arguments& args);
static Handle<Value> Bcompare(const Arguments& args);
static Handle<Value> Scompare(const Arguments& args);
static Handle<Value> Ucompare(const Arguments& args);
static Handle<Value> Bop(const Arguments& args, int op);
static Handle<Value> Band(const Arguments& args);
static Handle<Value> Bor(const Arguments& args);
static Handle<Value> Bxor(const Arguments& args);
static Handle<Value> Binvertm(const Arguments& args);
static Handle<Value> Bsqrt(const Arguments& args);
static Handle<Value> Broot(const Arguments& args);
static Handle<Value> BitLength(const Arguments& args);
static Handle<Value> Bgcd(const Arguments& args);
static Handle<Value> Bjacobi(const Arguments& args);
};
Persistent<FunctionTemplate> BigNum::constructor_template;
Persistent<Function> BigNum::js_conditioner;
void BigNum::SetJSConditioner(Persistent<Function> constructor) {
js_conditioner = constructor;
}
void BigNum::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("BigNum"));
NODE_SET_METHOD(constructor_template, "uprime0", Uprime0);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "tostring", ToString);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "badd", Badd);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bsub", Bsub);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bmul", Bmul);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bdiv", Bdiv);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "uadd", Uadd);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "usub", Usub);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "umul", Umul);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "udiv", Udiv);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "umul2exp", Umul_2exp);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "udiv2exp", Udiv_2exp);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "babs", Babs);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bneg", Bneg);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bmod", Bmod);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "umod", Umod);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bpowm", Bpowm);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "upowm", Upowm);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "upow", Upow);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "brand0", Brand0);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "probprime", Probprime);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bcompare", Bcompare);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "scompare", Scompare);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "ucompare", Ucompare);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "band", Band);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bor", Bor);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bxor", Bxor);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "binvertm", Binvertm);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bsqrt", Bsqrt);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "broot", Broot);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "bitLength", BitLength);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "gcd", Bgcd);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "jacobi", Bjacobi);
target->Set(String::NewSymbol("BigNum"), constructor_template->GetFunction());
}
BigNum::BigNum(const v8::String::Utf8Value& str, uint64_t base) : ObjectWrap ()
{
BN_init(&bignum_);
BN_zero(&bignum_);
BIGNUM *res = &bignum_;
const char *cstr = *str;
switch (base) {
case 2:
BN_init(&bignum_);
for (int i = 0, l = str.length(); i < l; i++) {
if (cstr[l-i-1] != '0') {
BN_set_bit(&bignum_, i);
}
}
break;
case 10:
BN_dec2bn(&res, cstr);
break;
case 16:
BN_hex2bn(&res, cstr);
break;
default:
ThrowException(Exception::Error(String::New("Invalid base, only 10 and 16 are supported")));
return;
}
}
BigNum::BigNum(uint64_t num) : ObjectWrap ()
{
BN_init(&bignum_);
BN_set_word(&bignum_, num);
}
BigNum::BigNum(int64_t num) : ObjectWrap ()
{
BN_init(&bignum_);
if (num > 0) {
BN_set_word(&bignum_, num);
} else {
BN_set_word(&bignum_, -num);
BN_set_negative(&bignum_, 1);
}
}
BigNum::BigNum(BIGNUM *num) : ObjectWrap ()
{
BN_init(&bignum_);
BN_copy(&bignum_, num);
}
BigNum::BigNum() : ObjectWrap ()
{
BN_init(&bignum_);
BN_zero(&bignum_);
}
BigNum::~BigNum()
{
BN_clear_free(&bignum_);
}
Handle<Value>
BigNum::New(const Arguments& args)
{
if (!args.IsConstructCall()) {
int len = args.Length();
Handle<Value>* newArgs = new Handle<Value>[len];
for (int i = 0; i < len; i++) {
newArgs[i] = args[i];
}
Handle<Value> newInst = constructor_template->GetFunction()->NewInstance(len, newArgs);
delete[] newArgs;
return newInst;
}
HandleScope scope;
BigNum *bignum;
uint64_t base;
if (args[0]->IsExternal()) {
bignum = static_cast<BigNum*>(External::Cast(*(args[0]))->Value());
} else {
int len = args.Length();
Local<Object> ctx = Local<Object>::New(Object::New());
Handle<Value>* newArgs = new Handle<Value>[len];
for (int i = 0; i < len; i++) {
newArgs[i] = args[i];
}
Local<Value> obj = js_conditioner->Call(ctx, args.Length(), newArgs);
delete[] newArgs;
if (!*obj) {
return ThrowException(Exception::Error(String::New("Invalid type passed to bignum constructor")));
}
String::Utf8Value str(obj->ToObject()->Get(String::NewSymbol("num"))->ToString());
base = obj->ToObject()->Get(String::NewSymbol("base"))->ToNumber()->Value();
bignum = new BigNum(str, base);
}
bignum->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value>
BigNum::ToString(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
uint64_t base = 10;
if (args.Length() > 0) {
REQ_UINT64_ARG(0, tbase);
base = tbase;
}
char *to = NULL;
switch (base) {
case 10:
to = BN_bn2dec(&bignum->bignum_);
break;
case 16:
to = BN_bn2hex(&bignum->bignum_);
break;
default:
return ThrowException(Exception::Error(String::New("Invalid base, only 10 and 16 are supported")));
}
Handle<Value> result = String::New(to);
free(to);
return scope.Close(result);
}
Handle<Value>
BigNum::Badd(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_add(&res->bignum_, &bignum->bignum_, &bn->bignum_);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bsub(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_sub(&res->bignum_, &bignum->bignum_, &bn->bignum_);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bmul(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_mul(&res->bignum_, &bignum->bignum_, &bn->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bdiv(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bi = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_div(&res->bignum_, NULL, &bignum->bignum_, &bi->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Uadd(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum(&bignum->bignum_);
BN_add_word(&res->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Usub(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum(&bignum->bignum_);
BN_sub_word(&res->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Umul(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum(&bignum->bignum_);
BN_mul_word(&res->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Udiv(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum(&bignum->bignum_);
BN_div_word(&res->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Umul_2exp(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum();
BN_lshift(&res->bignum_, &bignum->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Udiv_2exp(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum();
BN_rshift(&res->bignum_, &bignum->bignum_, x);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Babs(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *res = new BigNum(&bignum->bignum_);
BN_set_negative(&res->bignum_, 0);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bneg(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *res = new BigNum(&bignum->bignum_);
BN_set_negative(&res->bignum_, !BN_is_negative(&res->bignum_));
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bmod(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_div(NULL, &res->bignum_, &bignum->bignum_, &bn->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Umod(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *res = new BigNum();
BN_set_word(&res->bignum_, BN_mod_word(&bignum->bignum_, x));
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bpowm(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn1 = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *bn2 = ObjectWrap::Unwrap<BigNum>(args[1]->ToObject());
BigNum *res = new BigNum();
BN_mod_exp(&res->bignum_, &bignum->bignum_, &bn1->bignum_, &bn2->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Upowm(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[1]->ToObject());
BIGNUM exp;
BN_init(&exp);
BN_set_word(&exp, x);
BigNum *res = new BigNum();
BN_mod_exp(&res->bignum_, &bignum->bignum_, &exp, &bn->bignum_, ctx);
BN_clear_free(&exp);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Upow(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BIGNUM exp;
BN_init(&exp);
BN_set_word(&exp, x);
BigNum *res = new BigNum();
BN_exp(&res->bignum_, &bignum->bignum_, &exp, ctx);
BN_clear_free(&exp);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Brand0(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *res = new BigNum();
BN_rand_range(&res->bignum_, &bignum->bignum_);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Uprime0(const Arguments& args)
{
HandleScope scope;
REQ_UINT32_ARG(0, x);
REQ_BOOL_ARG(1, safe);
BigNum *res = new BigNum();
BN_generate_prime_ex(&res->bignum_, x, safe, NULL, NULL, NULL);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Probprime(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT32_ARG(0, reps);
return scope.Close(Number::New(BN_is_prime_ex(&bignum->bignum_, reps, ctx, NULL)));
}
Handle<Value>
BigNum::Bcompare(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
return scope.Close(Number::New(BN_cmp(&bignum->bignum_, &bn->bignum_)));
}
Handle<Value>
BigNum::Scompare(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_INT64_ARG(0, x);
BIGNUM bn;
BN_init(&bn);
if (x > 0) {
BN_set_word(&bn, x);
} else {
BN_set_word(&bn, -x);
BN_set_negative(&bn, 1);
}
int res = BN_cmp(&bignum->bignum_, &bn);
BN_clear_free(&bn);
return scope.Close(Number::New(res));
}
Handle<Value>
BigNum::Ucompare(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
REQ_UINT64_ARG(0, x);
BIGNUM bn;
BN_init(&bn);
BN_set_word(&bn, x);
int res = BN_cmp(&bignum->bignum_, &bn);
BN_clear_free(&bn);
return scope.Close(Number::New(res));
}
Handle<Value>
BigNum::Bop(const Arguments& args, int op)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
HandleScope scope;
if (BN_is_negative(&bignum->bignum_) || BN_is_negative(&bn->bignum_)) {
// Using BN_bn2mpi and BN_bn2mpi would make this more manageable; added in SSLeay 0.9.0
return ThrowException(Exception::Error(String::New("Bitwise operations on negative numbers are not supported")));
}
BigNum *res = new BigNum();
// Modified from https://github.com/Worlize/WebSocket-Node/blob/master/src/xor.cpp
// Portions Copyright (c) Agora S.A.
// Licensed under the MIT License.
int payloadSize = BN_num_bytes(&bignum->bignum_);
int maskSize = BN_num_bytes(&bn->bignum_);
int size = max(payloadSize, maskSize);
int offset = abs(payloadSize - maskSize);
int payloadOffset = 0;
int maskOffset = 0;
if (payloadSize < maskSize) {
payloadOffset = offset;
} else if (payloadSize > maskSize) {
maskOffset = offset;
}
uint8_t* payload = (uint8_t*) calloc(size, sizeof(char));
uint8_t* mask = (uint8_t*) calloc(size, sizeof(char));
BN_bn2bin(&bignum->bignum_, (unsigned char*) (payload + payloadOffset));
BN_bn2bin(&bn->bignum_, (unsigned char*) (mask + maskOffset));
uint32_t* pos32 = (uint32_t*) payload;
uint32_t* end32 = pos32 + (size / 4);
uint32_t* mask32 = (uint32_t*) mask;
switch (op) {
case 0: while (pos32 < end32) *(pos32++) &= *(mask32++); break;
case 1: while (pos32 < end32) *(pos32++) |= *(mask32++); break;
case 2: while (pos32 < end32) *(pos32++) ^= *(mask32++); break;
}
uint8_t* pos8 = (uint8_t*) pos32;
uint8_t* end8 = payload + size;
uint8_t* mask8 = (uint8_t*) mask32;
switch (op) {
case 0: while (pos8 < end8) *(pos8++) &= *(mask8++); break;
case 1: while (pos8 < end8) *(pos8++) |= *(mask8++); break;
case 2: while (pos8 < end8) *(pos8++) ^= *(mask8++); break;
}
BN_bin2bn((unsigned char*) payload, size, &res->bignum_);
WRAP_RESULT(res, result);
free(payload);
free(mask);
return scope.Close(result);
}
Handle<Value>
BigNum::Band(const Arguments& args)
{
return Bop(args, 0);
}
Handle<Value>
BigNum::Bor(const Arguments& args)
{
return Bop(args, 1);
}
Handle<Value>
BigNum::Bxor(const Arguments& args)
{
return Bop(args, 2);
}
Handle<Value>
BigNum::Binvertm(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_mod_inverse(&res->bignum_, &bignum->bignum_, &bn->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bsqrt(const Arguments& args)
{
//BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
return ThrowException(Exception::Error(String::New("sqrt is not supported by OpenSSL.")));
}
Handle<Value>
BigNum::Broot(const Arguments& args)
{
//BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
return ThrowException(Exception::Error(String::New("root is not supported by OpenSSL.")));
}
Handle<Value>
BigNum::BitLength(const Arguments& args)
{
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
int size = BN_num_bits(&bignum->bignum_);
Handle<Value> result = Integer::New(size);
return scope.Close(result);
}
Handle<Value>
BigNum::Bgcd(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bignum = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bi = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
BigNum *res = new BigNum();
BN_gcd(&res->bignum_, &bignum->bignum_, &bi->bignum_, ctx);
WRAP_RESULT(res, result);
return scope.Close(result);
}
Handle<Value>
BigNum::Bjacobi(const Arguments& args)
{
AutoBN_CTX ctx;
BigNum *bn_a = ObjectWrap::Unwrap<BigNum>(args.This());
HandleScope scope;
BigNum *bn_n = ObjectWrap::Unwrap<BigNum>(args[0]->ToObject());
int res = 0;
if (BN_jacobi_priv(&bn_a->bignum_, &bn_n->bignum_, &res, ctx) == -1)
return ThrowException(Exception::Error(String::New(
"Jacobi symbol calculation failed")));
return scope.Close(Integer::New(res));
}
static Handle<Value>
SetJSConditioner(const Arguments& args)
{
HandleScope scope;
BigNum::SetJSConditioner(Persistent<Function>::New(Local<Function>::Cast(args[0])));
return Undefined();
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
BigNum::Initialize(target);
NODE_SET_METHOD(target, "setJSConditioner", SetJSConditioner);
}
NODE_MODULE(bignum, init)

79
node_modules/bignum/binding.gyp generated vendored Normal file
View File

@ -0,0 +1,79 @@
{
'targets':
[
{
'target_name': 'bignum',
'sources': [ 'bignum.cc' ],
'conditions':
[
# For Windows, require either a 32-bit or 64-bit
# separately-compiled OpenSSL library.
# Currently set up to use with the following OpenSSL distro:
#
# http://slproweb.com/products/Win32OpenSSL.html
[
'OS=="win"',
{
'conditions':
[
[
'target_arch=="x64"',
{
'variables': {
'openssl_root%': 'C:/OpenSSL-Win64'
},
}, {
'variables': {
'openssl_root%': 'C:/OpenSSL-Win32'
}
}
]
],
'libraries': [
'-l<(openssl_root)/lib/libeay32.lib',
],
'include_dirs': [
'<(openssl_root)/include',
],
},
# Otherwise, if not Windows, link against the exposed OpenSSL
# in Node.
{
'conditions':
[
[
'target_arch=="ia32"',
{
'variables': {
'openssl_config_path': '<(nodedir)/deps/openssl/config/piii'
}
}
],
[
'target_arch=="x64"', {
'variables': {
'openssl_config_path': '<(nodedir)/deps/openssl/config/k8'
},
}
],
[
'target_arch=="arm"', {
'variables': {
'openssl_config_path': '<(nodedir)/deps/openssl/config/arm'
}
}
],
],
'include_dirs': [
"<(nodedir)/deps/openssl/openssl/include",
"<(openssl_config_path)"
]
}
]
]
}
]
}

332
node_modules/bignum/build/Makefile generated vendored Normal file
View File

@ -0,0 +1,332 @@
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= flock $(builddir)/linker.lock $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,bignum.target.mk)))),)
include bignum.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/matt/site/node_modules/bignum/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/matt/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/matt/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/matt/site/node_modules/bignum" binding.gyp
Makefile: $(srcdir)/../../../.node-gyp/0.10.24/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif

View File

@ -0,0 +1 @@
cmd_Release/bignum.node := rm -rf "Release/bignum.node" && cp -af "Release/obj.target/bignum.node" "Release/bignum.node"

View File

@ -0,0 +1 @@
cmd_Release/obj.target/bignum.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m64 -Wl,-soname=bignum.node -o Release/obj.target/bignum.node -Wl,--start-group Release/obj.target/bignum/bignum.o -Wl,--end-group

View File

@ -0,0 +1,59 @@
cmd_Release/obj.target/bignum/bignum.o := g++ '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/matt/.node-gyp/0.10.24/src -I/home/matt/.node-gyp/0.10.24/deps/uv/include -I/home/matt/.node-gyp/0.10.24/deps/v8/include -I/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include -I/home/matt/.node-gyp/0.10.24/deps/openssl/config/k8 -fPIC -Wall -Wextra -Wno-unused-parameter -pthread -m64 -O2 -fno-strict-aliasing -fno-tree-vrp -fno-omit-frame-pointer -fno-rtti -fno-exceptions -MMD -MF ./Release/.deps/Release/obj.target/bignum/bignum.o.d.raw -c -o Release/obj.target/bignum/bignum.o ../bignum.cc
Release/obj.target/bignum/bignum.o: ../bignum.cc \
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8.h \
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8stdint.h \
/home/matt/.node-gyp/0.10.24/src/node.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h \
/home/matt/.node-gyp/0.10.24/src/node_object_wrap.h \
/home/matt/.node-gyp/0.10.24/src/node.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/bn.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/bn/bn.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/e_os2.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../e_os2.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/opensslconf.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/opensslconf.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/../../config/opensslconf.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/ossl_typ.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/ossl_typ.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/crypto.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/crypto.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/stack.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/stack/stack.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/safestack.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/stack/safestack.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/opensslv.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/opensslv.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/symhacks.h \
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/symhacks.h
../bignum.cc:
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8.h:
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8stdint.h:
/home/matt/.node-gyp/0.10.24/src/node.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h:
/home/matt/.node-gyp/0.10.24/src/node_object_wrap.h:
/home/matt/.node-gyp/0.10.24/src/node.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/bn.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/bn/bn.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/e_os2.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../e_os2.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/opensslconf.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/opensslconf.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/../../config/opensslconf.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/ossl_typ.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/ossl_typ.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/crypto.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/crypto.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/stack.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/stack/stack.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/safestack.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/stack/safestack.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/opensslv.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/opensslv.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/symhacks.h:
/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include/openssl/../../crypto/symhacks.h:

BIN
node_modules/bignum/build/Release/bignum.node generated vendored Executable file

Binary file not shown.

0
node_modules/bignum/build/Release/linker.lock generated vendored Normal file
View File

BIN
node_modules/bignum/build/Release/obj.target/bignum.node generated vendored Executable file

Binary file not shown.

Binary file not shown.

134
node_modules/bignum/build/bignum.target.mk generated vendored Normal file
View File

@ -0,0 +1,134 @@
# This file is generated by gyp; do not edit.
TOOLSET := target
TARGET := bignum
DEFS_Debug := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION' \
'-DDEBUG' \
'-D_DEBUG'
# Flags passed to all source files.
CFLAGS_Debug := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-g \
-O0
# Flags passed to only C files.
CFLAGS_C_Debug :=
# Flags passed to only C++ files.
CFLAGS_CC_Debug := \
-fno-rtti \
-fno-exceptions
INCS_Debug := \
-I/home/matt/.node-gyp/0.10.24/src \
-I/home/matt/.node-gyp/0.10.24/deps/uv/include \
-I/home/matt/.node-gyp/0.10.24/deps/v8/include \
-I/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include \
-I/home/matt/.node-gyp/0.10.24/deps/openssl/config/k8
DEFS_Release := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION'
# Flags passed to all source files.
CFLAGS_Release := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-O2 \
-fno-strict-aliasing \
-fno-tree-vrp \
-fno-omit-frame-pointer
# Flags passed to only C files.
CFLAGS_C_Release :=
# Flags passed to only C++ files.
CFLAGS_CC_Release := \
-fno-rtti \
-fno-exceptions
INCS_Release := \
-I/home/matt/.node-gyp/0.10.24/src \
-I/home/matt/.node-gyp/0.10.24/deps/uv/include \
-I/home/matt/.node-gyp/0.10.24/deps/v8/include \
-I/home/matt/.node-gyp/0.10.24/deps/openssl/openssl/include \
-I/home/matt/.node-gyp/0.10.24/deps/openssl/config/k8
OBJS := \
$(obj).target/$(TARGET)/bignum.o
# Add to the list of files we specially track dependencies for.
all_deps += $(OBJS)
# CFLAGS et al overrides must be target-local.
# See "Target-specific Variable Values" in the GNU Make manual.
$(OBJS): TOOLSET := $(TOOLSET)
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# End of this set of suffix rules
### Rules for final target.
LDFLAGS_Debug := \
-pthread \
-rdynamic \
-m64
LDFLAGS_Release := \
-pthread \
-rdynamic \
-m64
LIBS :=
$(obj).target/bignum.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
$(obj).target/bignum.node: LIBS := $(LIBS)
$(obj).target/bignum.node: TOOLSET := $(TOOLSET)
$(obj).target/bignum.node: $(OBJS) FORCE_DO_CMD
$(call do_cmd,solink_module)
all_deps += $(obj).target/bignum.node
# Add target alias
.PHONY: bignum
bignum: $(builddir)/bignum.node
# Copy this to the executable output path.
$(builddir)/bignum.node: TOOLSET := $(TOOLSET)
$(builddir)/bignum.node: $(obj).target/bignum.node FORCE_DO_CMD
$(call do_cmd,copy)
all_deps += $(builddir)/bignum.node
# Short alias for building this executable.
.PHONY: bignum.node
bignum.node: $(obj).target/bignum.node $(builddir)/bignum.node
# Add executable to "all" target.
.PHONY: all
all: $(builddir)/bignum.node

6
node_modules/bignum/build/binding.Makefile generated vendored Normal file
View File

@ -0,0 +1,6 @@
# This file is generated by gyp; do not edit.
export builddir_name ?= build/./.
.PHONY: all
all:
$(MAKE) bignum

115
node_modules/bignum/build/config.gypi generated vendored Normal file
View File

@ -0,0 +1,115 @@
# Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"clang": 0,
"gcc_version": 48,
"host_arch": "x64",
"node_install_npm": "true",
"node_prefix": "/usr",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_openssl": "false",
"node_shared_v8": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_unsafe_optimizations": 0,
"node_use_dtrace": "false",
"node_use_etw": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"node_use_systemtap": "false",
"python": "/usr/bin/python",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_no_strict_aliasing": 1,
"v8_use_snapshot": "false",
"nodedir": "/home/matt/.node-gyp/0.10.24",
"copy_dev_lib": "true",
"standalone_static_library": 1,
"cache_lock_stale": "60000",
"sign_git_tag": "",
"always_auth": "",
"user_agent": "node/v0.10.24 linux x64",
"bin_links": "true",
"key": "",
"description": "true",
"fetch_retries": "2",
"heading": "npm",
"user": "",
"force": "",
"cache_min": "10",
"init_license": "ISC",
"editor": "vi",
"rollback": "true",
"cache_max": "null",
"userconfig": "/home/matt/.npmrc",
"engine_strict": "",
"init_author_name": "",
"init_author_url": "",
"tmp": "/home/matt/tmp",
"depth": "null",
"save_dev": "",
"usage": "",
"https_proxy": "",
"onload_script": "",
"rebuild_bundle": "true",
"save_bundle": "",
"shell": "/bin/bash",
"prefix": "/usr",
"registry": "https://registry.npmjs.org/",
"browser": "",
"cache_lock_wait": "10000",
"save_optional": "",
"searchopts": "",
"versions": "",
"cache": "/home/matt/.npm",
"ignore_scripts": "",
"searchsort": "name",
"version": "",
"local_address": "",
"viewer": "man",
"color": "true",
"fetch_retry_mintimeout": "10000",
"umask": "18",
"fetch_retry_maxtimeout": "60000",
"message": "%s",
"cert": "",
"global": "",
"link": "",
"save": "",
"unicode": "true",
"long": "",
"production": "",
"unsafe_perm": "true",
"node_version": "v0.10.24",
"tag": "latest",
"git_tag_version": "true",
"shrinkwrap": "true",
"fetch_retry_factor": "10",
"npat": "",
"proprietary_attribs": "true",
"strict_ssl": "true",
"username": "",
"dev": "",
"globalconfig": "/usr/etc/npmrc",
"init_module": "/home/matt/.npm-init.js",
"parseable": "",
"globalignorefile": "/usr/etc/npmignore",
"cache_lock_retries": "10",
"group": "1000",
"init_author_email": "",
"searchexclude": "",
"git": "git",
"optional": "true",
"email": "",
"json": ""
}
}

25
node_modules/bignum/examples/gen.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
// Generate two primes p and q to the Digital Signature Standard (DSS)
// http://www.itl.nist.gov/fipspubs/fip186.htm appendix 2.2
var bignum = require('../');
var assert = require('assert');
var q = bignum(2).pow(159).add(1).rand(bignum(2).pow(160)).nextPrime();
var L = 512 + 64 * Math.floor(Math.random() * 8);
do {
var X = bignum(2).pow(L-1).add(1).rand(bignum(2).pow(L));
var c = X.mod(q.mul(2));
var p = X.sub(c.sub(1)); // p is congruent to 1 % 2q somehow!
} while (p.lt(bignum.pow(2, L - 1)) || p.probPrime(50) === false)
assert.ok(q.gt(bignum.pow(2,159)), 'q > 2**159');
assert.ok(q.lt(bignum.pow(2,160)), 'q < 2**160');
assert.ok(p.gt(bignum.pow(2,L-1)), 'p > 2**(L-1)');
assert.ok(q.lt(bignum.pow(2,L)), 'p < 2**L');
assert.ok(q.mul(p.sub(1).div(q)).add(1).eq(p), 'q divides p - 1');
assert.ok(p.probPrime(50), 'p is not prime!');
assert.ok(q.probPrime(50), 'q is not prime!');
console.dir({ p : p, q : q });

10
node_modules/bignum/examples/perfect.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
// If 2**n-1 is prime, then (2**n-1) * 2**(n-1) is perfect.
var bignum = require('../');
for (var n = 0; n < 100; n++) {
var p = bignum.pow(2, n).sub(1);
if (p.probPrime(50)) {
var perfect = p.mul(bignum.pow(2, n - 1));
console.log(perfect.toString());
}
}

7
node_modules/bignum/examples/simple.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
var bignum = require('../');
var b = bignum('782910138827292261791972728324982')
.sub('182373273283402171237474774728373')
.div(8)
;
console.log(b);

433
node_modules/bignum/index.js generated vendored Normal file
View File

@ -0,0 +1,433 @@
try {
var cc = new require('./build/Debug/bignum');
} catch(e) {
var cc = new require('./build/Release/bignum');
}
var BigNum = cc.BigNum;
module.exports = BigNum;
BigNum.conditionArgs = function(num, base) {
if (typeof num !== 'string') num = num.toString(base || 10);
if (num.match(/e\+/)) { // positive exponent
if (!Number(num).toString().match(/e\+/)) {
return {
num: Math.floor(Number(num)).toString(),
base: 10
};
}
else {
var pow = Math.ceil(Math.log(num) / Math.log(2));
var n = (num / Math.pow(2, pow)).toString(2)
.replace(/^0/,'');
var i = n.length - n.indexOf('.');
n = n.replace(/\./,'');
for (; i <= pow; i++) n += '0';
return {
num : n,
base : 2,
};
}
}
else if (num.match(/e\-/)) { // negative exponent
return {
num : Math.floor(Number(num)).toString(),
base : base || 10
};
}
else {
return {
num : num,
base : base || 10,
};
}
};
cc.setJSConditioner(BigNum.conditionArgs);
BigNum.prototype.inspect = function () {
return '<BigNum ' + this.toString(10) + '>';
};
BigNum.prototype.toString = function (base) {
var value;
if (base) {
value = this.tostring(base);
} else {
value = this.tostring();
}
if (base > 10 && "string" === typeof value) {
value = value.toLowerCase();
}
return value;
};
BigNum.prototype.toNumber = function () {
return parseInt(this.toString(), 10);
};
[ 'add', 'sub', 'mul', 'div', 'mod' ].forEach(function (op) {
BigNum.prototype[op] = function (num) {
if (num instanceof BigNum) {
return this['b'+op](num);
}
else if (typeof num === 'number') {
if (num >= 0) {
return this['u'+op](num);
}
else if (op === 'add') {
return this.usub(-num);
}
else if (op === 'sub') {
return this.uadd(-num);
}
else {
var x = BigNum(num);
return this['b'+op](x);
}
}
else if (typeof num === 'string') {
var x = BigNum(num);
return this['b'+op](x);
}
else {
throw new TypeError('Unspecified operation for type '
+ (typeof num) + ' for ' + op);
}
};
});
BigNum.prototype.abs = function () {
return this.babs();
};
BigNum.prototype.neg = function () {
return this.bneg();
};
BigNum.prototype.powm = function (num, mod) {
var m, res;
if ((typeof mod) === 'number' || (typeof mod) === 'string') {
m = BigNum(mod);
}
else if (mod instanceof BigNum) {
m = mod;
}
if ((typeof num) === 'number') {
return this.upowm(num, m);
}
else if ((typeof num) === 'string') {
var n = BigNum(num);
return this.bpowm(n, m);
}
else if (num instanceof BigNum) {
return this.bpowm(num, m);
}
};
BigNum.prototype.mod = function (num, mod) {
var m, res;
if ((typeof mod) === 'number' || (typeof mod) === 'string') {
m = BigNum(mod);
}
else if (mod instanceof BigNum) {
m = mod;
}
if ((typeof num) === 'number') {
return this.umod(num, m);
}
else if ((typeof num) === 'string') {
var n = BigNum(num);
return this.bmod(n, m);
}
else if (num instanceof BigNum) {
return this.bmod(num, m);
}
};
BigNum.prototype.pow = function (num) {
if (typeof num === 'number') {
if (num >= 0) {
return this.upow(num);
}
else {
return BigNum.prototype.powm.call(this, num, this);
}
}
else {
var x = parseInt(num.toString(), 10);
return BigNum.prototype.pow.call(this, x);
}
};
BigNum.prototype.shiftLeft = function (num) {
if (typeof num === 'number') {
if (num >= 0) {
return this.umul2exp(num);
}
else {
return this.shiftRight(-num);
}
}
else {
var x = parseInt(num.toString(), 10);
return BigNum.prototype.shiftLeft.call(this, x);
}
};
BigNum.prototype.shiftRight = function (num) {
if (typeof num === 'number') {
if (num >= 0) {
return this.udiv2exp(num);
}
else {
return this.shiftLeft(-num);
}
}
else {
var x = parseInt(num.toString(), 10);
return BigNum.prototype.shiftRight.call(this, x);
}
};
BigNum.prototype.cmp = function (num) {
if (num instanceof BigNum) {
return this.bcompare(num);
}
else if (typeof num === 'number') {
if (num < 0) {
return this.scompare(num);
}
else {
return this.ucompare(num);
}
}
else {
var x = BigNum(num);
return this.bcompare(x);
}
};
BigNum.prototype.gt = function (num) {
return this.cmp(num) > 0;
};
BigNum.prototype.ge = function (num) {
return this.cmp(num) >= 0;
};
BigNum.prototype.eq = function (num) {
return this.cmp(num) === 0;
};
BigNum.prototype.ne = function (num) {
return this.cmp(num) !== 0;
};
BigNum.prototype.lt = function (num) {
return this.cmp(num) < 0;
};
BigNum.prototype.le = function (num) {
return this.cmp(num) <= 0;
};
'and or xor'.split(' ').forEach(function (name) {
BigNum.prototype[name] = function (num) {
if (num instanceof BigNum) {
return this['b' + name](num);
}
else {
var x = BigNum(num);
return this['b' + name](x);
}
};
});
BigNum.prototype.sqrt = function() {
return this.bsqrt();
};
BigNum.prototype.root = function(num) {
if (num instanceof BigNum) {
return this.broot(num);
}
else {
var x = BigNum(num);
return this.broot(num);
}
};
BigNum.prototype.rand = function (to) {
if (to === undefined) {
if (this.toString() === '1') {
return BigNum(0);
}
else {
return this.brand0();
}
}
else {
var x = to instanceof BigNum
? to.sub(this)
: BigNum(to).sub(this);
return x.brand0().add(this);
}
};
BigNum.prototype.invertm = function (mod) {
if (mod instanceof BigNum) {
return this.binvertm(mod);
}
else {
var x = BigNum(mod);
return this.binvertm(x);
}
};
BigNum.prime = function (bits, safe) {
if ("undefined" === typeof safe) {
safe = true;
}
// Force uint32
bits >>>= 0;
return BigNum.uprime0(bits, !!safe);
};
BigNum.prototype.probPrime = function (reps) {
var n = this.probprime(reps || 10);
return { 1 : true, 0 : false }[n];
};
BigNum.prototype.nextPrime = function () {
var num = this;
do {
num = num.add(1);
} while (!num.probPrime());
return num;
};
BigNum.fromBuffer = function (buf, opts) {
if (!opts) opts = {};
var endian = { 1 : 'big', '-1' : 'little' }[opts.endian]
|| opts.endian || 'big'
;
var size = opts.size === 'auto' ? Math.ceil(buf.length) : (opts.size || 1);
if (buf.length % size !== 0) {
throw new RangeError('Buffer length (' + buf.length + ')'
+ ' must be a multiple of size (' + size + ')'
);
}
var hex = [];
for (var i = 0; i < buf.length; i += size) {
var chunk = [];
for (var j = 0; j < size; j++) {
chunk.push(buf[
i + (endian === 'big' ? j : (size - j - 1))
]);
}
hex.push(chunk
.map(function (c) {
return (c < 16 ? '0' : '') + c.toString(16);
})
.join('')
);
}
return BigNum(hex.join(''), 16);
};
BigNum.prototype.toBuffer = function (opts) {
if (typeof opts === 'string') {
if (opts !== 'mpint') return 'Unsupported Buffer representation';
var abs = this.abs();
var buf = abs.toBuffer({ size : 1, endian : 'big' });
var len = buf.length === 1 && buf[0] === 0 ? 0 : buf.length;
if (buf[0] & 0x80) len ++;
var ret = new Buffer(4 + len);
if (len > 0) buf.copy(ret, 4 + (buf[0] & 0x80 ? 1 : 0));
if (buf[0] & 0x80) ret[4] = 0;
ret[0] = len & (0xff << 24);
ret[1] = len & (0xff << 16);
ret[2] = len & (0xff << 8);
ret[3] = len & (0xff << 0);
// two's compliment for negative integers:
var isNeg = this.lt(0);
if (isNeg) {
for (var i = 4; i < ret.length; i++) {
ret[i] = 0xff - ret[i];
}
}
ret[4] = (ret[4] & 0x7f) | (isNeg ? 0x80 : 0);
if (isNeg) ret[ret.length - 1] ++;
return ret;
}
if (!opts) opts = {};
var endian = { 1 : 'big', '-1' : 'little' }[opts.endian]
|| opts.endian || 'big'
;
var hex = this.toString(16);
if (hex.charAt(0) === '-') throw new Error(
'converting negative numbers to Buffers not supported yet'
);
var size = opts.size === 'auto' ? Math.ceil(hex.length / 2) : (opts.size || 1);
var len = Math.ceil(hex.length / (2 * size)) * size;
var buf = new Buffer(len);
// zero-pad the hex string so the chunks are all `size` long
while (hex.length < 2 * len) hex = '0' + hex;
var hx = hex
.split(new RegExp('(.{' + (2 * size) + '})'))
.filter(function (s) { return s.length > 0 })
;
hx.forEach(function (chunk, i) {
for (var j = 0; j < size; j++) {
var ix = i * size + (endian === 'big' ? j : size - j - 1);
buf[ix] = parseInt(chunk.slice(j*2,j*2+2), 16);
}
});
return buf;
};
Object.keys(BigNum.prototype).forEach(function (name) {
if (name === 'inspect' || name === 'toString') return;
BigNum[name] = function (num) {
var args = [].slice.call(arguments, 1);
if (num instanceof BigNum) {
return num[name].apply(num, args);
}
else {
var bigi = BigNum(num);
return bigi[name].apply(bigi, args);
}
};
});

51
node_modules/bignum/package.json generated vendored Normal file

File diff suppressed because one or more lines are too long

495
node_modules/bignum/test/big.js generated vendored Normal file
View File

@ -0,0 +1,495 @@
var assert = require('assert');
var bignum = require('../');
exports.create = function () {
assert.eql(bignum(1337).toString(), '1337');
assert.eql(bignum('1337').toString(), '1337');
assert.eql(new bignum('100').toString(), '100');
assert.eql(
new bignum('55555555555555555555555555').toString(),
'55555555555555555555555555'
);
assert.eql(Number(bignum('1e+100').toString()), 1e+100);
assert.eql(bignum('1e+100').bitLength(), 333);
assert.eql(Number(bignum('1.23e+45').toString()), 1.23e+45);
for (var i = 0; i < 10; i++) {
assert.eql(
bignum('1.23456e+' + i).toString(),
Math.floor(1.23456 * Math.pow(10,i))
);
}
assert.eql(bignum('1.23e-45').toString(), '0');
assert.throws(function() { bignum(undefined); });
assert.throws(function() { bignum(null); });
};
exports.add = function () {
for (var i = -10; i < 10; i++) {
for (var j = -10; j < 10; j++) {
var is = i.toString();
var js = j.toString();
var ks = (i + j).toString();
assert.eql(bignum(i).add(j).toString(), ks);
assert.eql(bignum(i).add(js).toString(), ks);
assert.eql(bignum(i).add(bignum(j)).toString(), ks);
assert.eql(bignum.add(i, j).toString(), ks);
}
}
assert.eql(
bignum(
'201781752444966478956292456789265633588628356858680927185287861892'
+ '9889675589272409635031813235465496971529430565627918846694860512'
+ '1492948268400884893722767401972695174353441'
).add(
'939769862972759638577945343130228368606420083646071622223953046277'
+ '3784500359975110887672142614667937014937371109558223563373329424'
+ '0624814097369771481147215472578762824607080'
).toString(),
'1141551615417726117534237799919494002195048440504752549409240908170367'
+ '41759492475205227039558501334339864668016751861424100681899362117762'
+ '365770656374869982874551457998960521'
);
};
exports.sub = function () {
for (var i = -10; i < 10; i++) {
for (var j = -10; j < 10; j++) {
var is = i.toString();
var js = j.toString();
var ks = (i - j).toString();
assert.eql(bignum(i).sub(j).toString(), ks);
assert.eql(bignum(i).sub(js).toString(), ks);
assert.eql(bignum(i).sub(bignum(j)).toString(), ks);
assert.eql(bignum.sub(i, j).toString(), ks);
}
}
assert.eql(
bignum(
'635849762218952604062459342660379446997761295162166888134051068531'
+ '9813941775949841573516110003093332652267534768664621969514455380'
+ '8051168706779408804756208386011014197185296'
).sub(
'757617343536280696839135295661092954931163607913400460585109207644'
+ '7966483882748233585856350085641718822741649072106343655764769889'
+ '6399869016678013515043471880323279258685478'
).toString(),
'-121767581317328092776675953000713507933402312751233572451058139112815'
+ '25421067983920123402400825483861704741143034417216862503145088348700'
+ '309898604710287263494312265061500182'
);
};
exports.mul = function () {
for (var i = -10; i < 10; i++) {
for (var j = -10; j < 10; j++) {
var is = i.toString();
var js = j.toString();
var ks = (i * j).toString();
assert.eql(bignum(i).mul(j).toString(), ks);
assert.eql(bignum(i).mul(js).toString(), ks);
assert.eql(bignum(i).mul(bignum(j)).toString(), ks);
assert.eql(bignum.mul(i, j).toString(), ks);
}
}
assert.eql(
bignum(
'433593290010590489671135819286259593426549306666324008679782084292'
+ '2446494189019075159822930571858728009485237489829138626896756141'
+ '8738958337632249177044975686477011571044266'
).mul(
'127790264841901718791915669264129510947625523373763053776083279450'
+ '3886212911067061184379695097643279217271150419129022856601771338'
+ '794256383410400076210073482253089544155377'
).toString(),
'5540900136412485758752141142221047463857522755277604708501015732755989'
+ '17659432099233635577634197309727815375309484297883528869192732141328'
+ '99346769031695550850320602049507618052164677667378189154076988316301'
+ '23719953859959804490669091769150047414629675184805332001182298088891'
+ '58079529848220802017396422115936618644438110463469902675126288489182'
+ '82'
);
assert.eql(
bignum('10000000000000000000000000000').mul(-123).toString(),
'-1230000000000000000000000000000'
);
};
exports.div = function () {
for (var i = -10; i < 10; i++) {
for (var j = -10; j < 10; j++) {
var is = i.toString();
var js = j.toString();
var round = ((i/j) < 0) ? Math.ceil : Math.floor;
var ks = round(i / j).toString();
if (ks.match(/^-?\d+$/)) { // ignore exceptions
assert.eql(bignum(i).div(j).toString(), ks);
assert.eql(bignum(i).div(js).toString(), ks);
assert.eql(bignum(i).div(bignum(j)).toString(), ks);
assert.eql(bignum.div(i, j).toString(), ks);
}
}
}
assert.eql(
bignum(
'433593290010590489671135819286259593426549306666324008679782084292'
+ '2446494189019075159822930571858728009485237489829138626896756141'
+ '8738958337632249177044975686477011571044266'
).div(
'127790264841901718791915669264129510947625523373763053776083279450'
+ '3886212911067061184379695097643279217271150419129022856601771338'
+ '794256383410400076210073482253089544155377'
).toString(),
'33'
);
};
exports.abs = function () {
assert.eql(
bignum(
'433593290010590489671135819286259593426549306666324008679782084292'
+ '2446494189019075159822930571858728009485237489829138626896756141'
+ '8738958337632249177044975686477011571044266'
).abs().toString(),
'4335932900105904896711358192862595934265493066663240086797820842922446'
+ '49418901907515982293057185872800948523748982913862689675614187389583'
+ '37632249177044975686477011571044266'
);
assert.eql(
bignum(
'-43359329001059048967113581928625959342654930666632400867978208429'
+ '2244649418901907515982293057185872800948523748982913862689675614'
+ '18738958337632249177044975686477011571044266'
).abs().toString(),
'4335932900105904896711358192862595934265493066663240086797820842922446'
+ '49418901907515982293057185872800948523748982913862689675614187389583'
+ '37632249177044975686477011571044266'
);
};
exports.neg = function () {
assert.eql(
bignum(
'433593290010590489671135819286259593426549306666324008679782084292'
+ '2446494189019075159822930571858728009485237489829138626896756141'
+ '8738958337632249177044975686477011571044266'
).neg().toString(),
'-433593290010590489671135819286259593426549306666324008679782084292244'
+ '64941890190751598229305718587280094852374898291386268967561418738958'
+ '337632249177044975686477011571044266'
);
assert.eql(
bignum(
'-43359329001059048967113581928625959342654930666632400867978208429'
+ '2244649418901907515982293057185872800948523748982913862689675614'
+ '18738958337632249177044975686477011571044266'
).neg().toString(),
'4335932900105904896711358192862595934265493066663240086797820842922446'
+ '49418901907515982293057185872800948523748982913862689675614187389583'
+ '37632249177044975686477011571044266'
);
};
exports.mod = function () {
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
var is = i.toString();
var js = j.toString();
if (!isNaN(i % j)) {
var ks = (i % j).toString();
assert.eql(bignum(i).mod(j).toString(), ks);
assert.eql(bignum(i).mod(js).toString(), ks);
assert.eql(bignum(i).mod(bignum(j)).toString(), ks);
assert.eql(bignum.mod(i, j).toString(), ks);
}
}
}
assert.eql(
bignum('486541542410442549118519277483401413')
.mod('1802185856709793916115771381388554')
.toString()
,
'1753546955507985683376775889880387'
);
};
exports.cmp = function () {
for (var i = -10; i <= 10; i++) {
var bi = bignum(i);
for (var j = -10; j <= 10; j++) {
[ j, bignum(j) ].forEach(function (jj) {
assert.eql(bi.lt(jj), i < j);
assert.eql(bi.le(jj), i <= j);
assert.eql(bi.eq(jj), i === j);
assert.eql(bi.ne(jj), i !== j);
assert.eql(bi.gt(jj), i > j);
assert.eql(bi.ge(jj), i >= j);
});
}
}
};
exports.powm = function () {
var twos = [ 2, '2', bignum(2), bignum('2') ]
var tens = [ 100000, '100000', bignum(100000), bignum(100000) ];
twos.forEach(function (two) {
tens.forEach(function (t) {
assert.eql(
bignum('111111111').powm(two, t).toString(),
'54321'
);
});
});
assert.eql(
bignum('624387628734576238746587435')
.powm(2732, '457676874367586')
.toString()
,
'335581885073251'
);
};
exports.pow = function () {
[ 2, '2', bignum(2), bignum('2') ].forEach(function (two) {
assert.eql(
bignum('111111111').pow(two).toString(),
'12345678987654321'
);
});
assert.eql(
bignum('3487438743234789234879').pow(22).toString(),
'861281136448465709000943928980299119292959327175552412961995332536782980636409994680542395362634321718164701236369695670918217801815161694902810780084448291245512671429670376051205638247649202527956041058237646154753587769450973231275642223337064356190945030999709422512682440247294915605076918925272414789710234097768366414400280590151549041536921814066973515842848197905763447515344747881160891303219471850554054186959791307149715821010152303317328860351766337716947079041'
);
};
exports.and = function () {
for (var i = 0; i < 256; i += 7) {
for (var j = 0; j < 256; j += 7) {
var is = i.toString();
var js = j.toString();
var ks = (i & j).toString();
assert.eql(bignum(i).and(j).toString(), ks);
assert.eql(bignum(i).and(js).toString(), ks);
assert.eql(bignum(i).and(bignum(j)).toString(), ks);
assert.eql(bignum.and(i, j).toString(), ks);
}
}
assert.eql(bignum.and(bignum('111111', 16), bignum('111111', 16)).toString(16), '111111');
assert.eql(bignum.and(bignum('111110', 16), bignum('111111', 16)).toString(16), '111110');
assert.eql(bignum.and(bignum('111112', 16), bignum('111111', 16)).toString(16), '111110');
assert.eql(bignum.and(bignum('111121', 16), bignum('111111', 16)).toString(16), '111101');
assert.eql(bignum.and(bignum('111131', 16), bignum('111111', 16)).toString(16), '111111');
};
exports.or = function () {
for (var i = 0; i < 256; i += 7) {
for (var j = 0; j < 256; j += 7) {
var is = i.toString();
var js = j.toString();
var ks = (i | j).toString();
assert.eql(bignum(i).or(j).toString(), ks);
assert.eql(bignum(i).or(js).toString(), ks);
assert.eql(bignum(i).or(bignum(j)).toString(), ks);
assert.eql(bignum.or(i, j).toString(), ks);
}
}
assert.eql(bignum.or(bignum('111111', 16), bignum('111111', 16)).toString(16), '111111');
assert.eql(bignum.or(bignum('111110', 16), bignum('111111', 16)).toString(16), '111111');
assert.eql(bignum.or(bignum('111112', 16), bignum('111111', 16)).toString(16), '111113');
assert.eql(bignum.or(bignum('111121', 16), bignum('111111', 16)).toString(16), '111131');
};
exports.xor = function () {
for (var i = 0; i < 256; i += 7) {
for (var j = 0; j < 256; j += 7) {
var is = i.toString();
var js = j.toString();
var ks = (i ^ j).toString();
assert.eql(bignum(i).xor(j).toString(), ks);
assert.eql(bignum(i).xor(js).toString(), ks);
assert.eql(bignum(i).xor(bignum(j)).toString(), ks);
assert.eql(bignum.xor(i, j).toString(), ks);
}
}
assert.eql(bignum.xor(bignum('111111', 16), bignum('111111', 16)).toString(), 0);
assert.eql(bignum.xor(bignum('111110', 16), bignum('111111', 16)).toString(), 1);
assert.eql(bignum.xor(bignum('111112', 16), bignum('111111', 16)).toString(), 3);
assert.eql(bignum.xor(bignum('111121', 16), bignum('111111', 16)).toString(), 0x30);
};
exports.rand = function () {
for (var i = 1; i < 1000; i++) {
var x = bignum(i).rand().toNumber();
assert.ok(0 <= x && x < i);
var y = bignum(i).rand(i + 10).toNumber();
assert.ok(i <= y && y < i + 10);
var z = bignum.rand(i, i + 10).toNumber();
assert.ok(i <= z && z < i + 10);
}
};
exports.primes = function () {
var ps = { 2 : true, 3 : true, 5 : true, 7 : true };
for (var i = 0; i <= 10; i++) {
assert.eql(bignum(i).probPrime(), ps[i] ? true : false);
}
var ns = {
2 : 3,
3 : 5,
15313 : 15319,
222919 : 222931,
611939 : 611951,
334214459 : '334214467',
961748927 : '961748941',
9987704933 : '9987704953',
};
Object.keys(ns).forEach(function (n) {
assert.eql(
bignum(n).nextPrime().toString(),
ns[n].toString()
);
});
var uniques = [
'3', '11', '37', '101', '9091', '9901', '333667', '909091', '99990001',
'999999000001', '9999999900000001', '909090909090909091',
'1111111111111111111', '11111111111111111111111',
'900900900900990990990991',
];
var wagstaff = [
'3', '11', '43', '683', '2731', '43691', '174763', '2796203',
'715827883', '2932031007403', '768614336404564651',
'201487636602438195784363', '845100400152152934331135470251',
'56713727820156410577229101238628035243',
];
var big = [
'4669523849932130508876392554713407521319117239637943224980015676156491',
'54875133386847519273109693154204970395475080920935355580245252923343305939004903',
'204005728266090048777253207241416669051476369216501266754813821619984472224780876488344279',
'2074722246773485207821695222107608587480996474721117292752992589912196684750549658310084416732550077',
'5628290459057877291809182450381238927697314822133923421169378062922140081498734424133112032854812293',
];
[ uniques, wagstaff, big ].forEach(function (xs) {
xs.forEach(function (x) {
var p = bignum(x).probPrime();
assert.ok(p === true || p === 'maybe');
});
});
};
exports.invertm = function () {
// numbers from http://www.itl.nist.gov/fipspubs/fip186.htm appendix 5
var q = bignum('b20db0b101df0c6624fc1392ba55f77d577481e5', 16);
var k = bignum('79577ddcaafddc038b865b19f8eb1ada8a2838c6', 16);
var kinv = k.invertm(q);
assert.eql(kinv.toString(16), '2784e3d672d972a74e22c67f4f4f726ecc751efa');
};
exports.shift = function () {
assert.eql(bignum(37).shiftLeft(2).toString(), (37 << 2).toString()); // 148
assert.eql(bignum(37).shiftRight(2).toString(), (37 >> 2).toString()); // 9
assert.equal(
bignum(2).pow(Math.pow(2,10)).shiftRight(4).toString(),
bignum(2).pow(Math.pow(2,10)).div(16).toString()
);
};
exports.mod = function () {
assert.eql(bignum(55555).mod(2).toString(), '1');
assert.eql(
bignum('1234567').mod(
bignum('4321')
).toNumber(),
1234567 % 4321
);
};
exports.endian = function () {
var a = bignum(0x0102030405);
assert.eql(a.toBuffer({ endian: 'big', size: 2 }).toString('hex'), '000102030405');
assert.eql(a.toBuffer({ endian: 'little', size: 2 }).toString('hex'), '010003020504');
var b = bignum(0x0102030405);
assert.eql(a.toBuffer({ endian: 'big', size: 'auto' }).toString('hex'), '0102030405');
assert.eql(a.toBuffer({ endian: 'little', size: 'auto' }).toString('hex'), '0504030201');
var c = new Buffer("000102030405", 'hex');
assert.eql(bignum.fromBuffer(c, { endian: 'big', size: 'auto'}).toString(16), "0102030405");
assert.eql(bignum.fromBuffer(c, { endian: 'little', size: 'auto'}).toString(16), "050403020100");
};
exports.bitlength = function () {
var bl = bignum(
'433593290010590489671135819286259593426549306666324008679782084292'
+ '2446494189019075159822930571858728009485237489829138626896756141'
+ '873895833763224917704497568647701157104426'
).bitLength();
assert.equal(bl > 0, true);
};
exports.gcd = function () {
var b1 = bignum('234897235923342343242');
var b2 = bignum('234790237101762305340234');
var expected = bignum('6');
assert.equal(b1.gcd(b2).toString(), expected.toString());
};
exports.jacobi = function () {
// test case from p. 134 of D. R. Stinson
var b1 = bignum('7411');
var b2 = bignum('9283');
assert.equal(b1.jacobi(b2), -1);
// test case from p. 132 of D. R. Stinson
b1 = bignum('6278');
b2 = bignum('9975');
assert.equal(b1.jacobi(b2), -1);
// test case from p. 74 of Men. Oorsh. Vans.
b1 = bignum('158');
b2 = bignum('235');
assert.equal(b1.jacobi(b2), -1);
// test case from p. 216 of Kumanduri Romero
b1 = bignum('4');
b2 = bignum('7');
assert.equal(b1.jacobi(b2), 1);
// test case from p. 363 of K. R. Rosen
b1 = bignum('68');
b2 = bignum('111');
assert.equal(b1.jacobi(b2), 1);
};
if (process.argv[1] === __filename) {
assert.eql = assert.deepEqual;
Object.keys(exports).forEach(function (ex) {
exports[ex]();
});
if ("function" === typeof gc) {
gc();
}
}

196
node_modules/bignum/test/buf.js generated vendored Normal file
View File

@ -0,0 +1,196 @@
var assert = require('assert');
var bignum = require('../');
var put = require('put');
exports.buf_be = function () {
var buf1 = new Buffer([1,2,3,4]);
var num = bignum.fromBuffer(buf1, { size : 4 }).toNumber();
assert.eql(
num,
1*Math.pow(256, 3)
+ 2 * Math.pow(256, 2)
+ 3 * 256
+ 4
);
var buf2 = put().word32be(num).buffer();
assert.eql(buf1, buf2,
'[ ' + [].slice.call(buf1) + ' ] != [ ' + [].slice.call(buf2) + ' ]'
);
};
exports.buf_le = function () {
var buf1 = new Buffer([1,2,3,4]);
var num = bignum
.fromBuffer(buf1, { size : 4, endian : 'little' })
.toNumber()
;
var buf2 = put().word32le(num).buffer();
assert.eql(buf1, buf2,
'[ ' + [].join.call(buf1, ',')
+ ' ] != [ '
+ [].join.call(buf2, ',') + ' ]'
);
};
exports.buf_be_le = function () {
var buf_be = new Buffer([1,2,3,4,5,6,7,8]);
var buf_le = new Buffer([4,3,2,1,8,7,6,5]);
var num_be = bignum
.fromBuffer(buf_be, { size : 4, endian : 'big' })
.toString()
;
var num_le = bignum
.fromBuffer(buf_le, { size : 4, endian : 'little' })
.toString()
;
assert.eql(num_be, num_le);
};
exports.buf_high_bits = function () {
var buf_be = new Buffer([
201,202,203,204,
205,206,207,208
]);
var buf_le = new Buffer([
204,203,202,201,
208,207,206,205
]);
var num_be = bignum
.fromBuffer(buf_be, { size : 4, endian : 'big' })
.toString()
;
var num_le = bignum
.fromBuffer(buf_le, { size : 4, endian : 'little' })
.toString()
;
assert.eql(num_be, num_le);
};
exports.buf_to_from = function () {
var nums = [
0, 1, 10, 15, 3, 16,
7238, 1337, 31337, 505050,
'172389721984375328763297498273498732984324',
'32848432742',
'12988282841231897498217398217398127983721983719283721',
'718293798217398217312387213972198321'
];
nums.forEach(function (num) {
var b = bignum(num);
var u = b.toBuffer();
assert.ok(u);
assert.eql(
bignum.fromBuffer(u).toString(),
b.toString()
);
});
assert.throws(function () {
bignum(-1).toBuffer(); // can't pack negative numbers yet
});
};
exports.toBuf = function () {
var buf = new Buffer([ 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f ]);
var b = bignum(
0x0a * 256*256*256*256*256
+ 0x0b * 256*256*256*256
+ 0x0c * 256*256*256
+ 0x0d * 256*256
+ 0x0e * 256
+ 0x0f
);
assert.eql(b.toString(16), '0a0b0c0d0e0f');
assert.eql(
[].slice.call(b.toBuffer({ endian : 'big', size : 2 })),
[ 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f ]
);
assert.eql(
[].slice.call(b.toBuffer({ endian : 'little', size : 2 })),
[ 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e ]
);
assert.eql(
bignum.fromBuffer(buf).toString(16),
b.toString(16)
);
assert.eql(
[].slice.call(bignum(43135012110).toBuffer({
endian : 'little', size : 4
})),
[ 0x0a, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0c, 0x0b ]
);
assert.eql(
[].slice.call(bignum(43135012110).toBuffer({
endian : 'big', size : 4
})),
[ 0x00, 0x00, 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e ]
);
};
exports.zeroPad = function () {
var b = bignum(0x123456);
assert.eql(
[].slice.call(b.toBuffer({ endian : 'big', size:4 })),
[ 0x00, 0x12, 0x34, 0x56 ]
);
assert.eql(
[].slice.call(b.toBuffer({ endian : 'little', size:4 })),
[ 0x56, 0x34, 0x12, 0x00 ]
);
};
exports.toMpint = function () {
// test values taken directly out of
// http://tools.ietf.org/html/rfc4251#page-10
var refs = {
'0' : new Buffer([ 0x00, 0x00, 0x00, 0x00 ]),
'9a378f9b2e332a7' : new Buffer([
0x00, 0x00, 0x00, 0x08,
0x09, 0xa3, 0x78, 0xf9,
0xb2, 0xe3, 0x32, 0xa7,
]),
'80' : new Buffer([ 0x00, 0x00, 0x00, 0x02, 0x00, 0x80 ]),
'-1234' : new Buffer([ 0x00, 0x00, 0x00, 0x02, 0xed, 0xcc ]),
'-deadbeef' : new Buffer([
0x00, 0x00, 0x00, 0x05, 0xff, 0x21, 0x52, 0x41, 0x11
]),
};
Object.keys(refs).forEach(function (key) {
var buf0 = bignum(key, 16).toBuffer('mpint');
var buf1 = refs[key];
assert.eql(
buf0, buf1,
buf0.inspect() + ' != ' + buf1.inspect()
+ ' for bignum(' + key + ')'
);
});
};
if (process.argv[1] === __filename) {
assert.eql = assert.deepEqual;
Object.keys(exports).forEach(function (ex) {
exports[ex]();
});
if ("function" === typeof gc) {
gc();
}
}

51
node_modules/bignum/test/seed.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
var assert = require('assert');
var exec = require('child_process').exec;
exports.rand = function () {
var to = setTimeout(function () {
assert.fail('never executed');
}, 5000);
var cmd = 'node -e \'console.log(require('
+ JSON.stringify(__dirname + '/../')
+ ').rand(1000).toString())\''
;
exec(cmd, function (err1, r1) {
exec(cmd, function (err2, r2) {
clearTimeout(to);
assert.ok(!err1);
assert.ok(!err2);
assert.ok(
r1.match(/^\d+\n/),
JSON.stringify(r1) + ' is not an integer'
);
assert.ok(
r2.match(/^\d+\n/),
JSON.stringify(r2) + ' is not an integer'
);
var n1 = parseInt(r1.split('\n')[0], 10);
var n2 = parseInt(r2.split('\n')[0], 10);
assert.ok(n1 >= 0, 'n1 >= 0');
assert.ok(n2 >= 0, 'n2 >= 0');
assert.ok(n1 < 1000, 'n1 < 1000');
assert.ok(n2 < 1000, 'n2 < 1000');
assert.ok(n1 != n2, 'n1 != n2');
})
});
}
if (process.argv[1] === __filename) {
assert.eql = assert.deepEqual;
Object.keys(exports).forEach(function (ex) {
exports[ex]();
});
if ("function" === typeof gc) {
gc();
}
}

4
node_modules/binpack/.npmignore generated vendored Normal file
View File

@ -0,0 +1,4 @@
build/
binpack.node
node_modules
.lock-wscript

14
node_modules/binpack/COPYING generated vendored Normal file
View File

@ -0,0 +1,14 @@
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

8
node_modules/binpack/binding.gyp generated vendored Normal file
View File

@ -0,0 +1,8 @@
{
"targets": [
{
"target_name": "binpack",
"sources": [ "src/binpack.cpp" ]
}
]
}

332
node_modules/binpack/build/Makefile generated vendored Normal file
View File

@ -0,0 +1,332 @@
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= flock $(builddir)/linker.lock $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,binpack.target.mk)))),)
include binpack.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/matt/site/node_modules/binpack/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/matt/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/matt/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/matt/site/node_modules/binpack" binding.gyp
Makefile: $(srcdir)/../../../.node-gyp/0.10.24/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif

View File

@ -0,0 +1 @@
cmd_Release/binpack.node := rm -rf "Release/binpack.node" && cp -af "Release/obj.target/binpack.node" "Release/binpack.node"

View File

@ -0,0 +1 @@
cmd_Release/obj.target/binpack.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m64 -Wl,-soname=binpack.node -o Release/obj.target/binpack.node -Wl,--start-group Release/obj.target/binpack/src/binpack.o -Wl,--end-group

View File

@ -0,0 +1,23 @@
cmd_Release/obj.target/binpack/src/binpack.o := g++ '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/matt/.node-gyp/0.10.24/src -I/home/matt/.node-gyp/0.10.24/deps/uv/include -I/home/matt/.node-gyp/0.10.24/deps/v8/include -fPIC -Wall -Wextra -Wno-unused-parameter -pthread -m64 -O2 -fno-strict-aliasing -fno-tree-vrp -fno-omit-frame-pointer -fno-rtti -fno-exceptions -MMD -MF ./Release/.deps/Release/obj.target/binpack/src/binpack.o.d.raw -c -o Release/obj.target/binpack/src/binpack.o ../src/binpack.cpp
Release/obj.target/binpack/src/binpack.o: ../src/binpack.cpp \
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8.h \
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8stdint.h \
/home/matt/.node-gyp/0.10.24/src/node.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h \
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h \
/home/matt/.node-gyp/0.10.24/src/node_object_wrap.h \
/home/matt/.node-gyp/0.10.24/src/node.h \
/home/matt/.node-gyp/0.10.24/src/node_buffer.h
../src/binpack.cpp:
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8.h:
/home/matt/.node-gyp/0.10.24/deps/v8/include/v8stdint.h:
/home/matt/.node-gyp/0.10.24/src/node.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h:
/home/matt/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h:
/home/matt/.node-gyp/0.10.24/src/node_object_wrap.h:
/home/matt/.node-gyp/0.10.24/src/node.h:
/home/matt/.node-gyp/0.10.24/src/node_buffer.h:

BIN
node_modules/binpack/build/Release/binpack.node generated vendored Executable file

Binary file not shown.

0
node_modules/binpack/build/Release/linker.lock generated vendored Normal file
View File

BIN
node_modules/binpack/build/Release/obj.target/binpack.node generated vendored Executable file

Binary file not shown.

Binary file not shown.

6
node_modules/binpack/build/binding.Makefile generated vendored Normal file
View File

@ -0,0 +1,6 @@
# This file is generated by gyp; do not edit.
export builddir_name ?= build/./.
.PHONY: all
all:
$(MAKE) binpack

130
node_modules/binpack/build/binpack.target.mk generated vendored Normal file
View File

@ -0,0 +1,130 @@
# This file is generated by gyp; do not edit.
TOOLSET := target
TARGET := binpack
DEFS_Debug := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION' \
'-DDEBUG' \
'-D_DEBUG'
# Flags passed to all source files.
CFLAGS_Debug := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-g \
-O0
# Flags passed to only C files.
CFLAGS_C_Debug :=
# Flags passed to only C++ files.
CFLAGS_CC_Debug := \
-fno-rtti \
-fno-exceptions
INCS_Debug := \
-I/home/matt/.node-gyp/0.10.24/src \
-I/home/matt/.node-gyp/0.10.24/deps/uv/include \
-I/home/matt/.node-gyp/0.10.24/deps/v8/include
DEFS_Release := \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION'
# Flags passed to all source files.
CFLAGS_Release := \
-fPIC \
-Wall \
-Wextra \
-Wno-unused-parameter \
-pthread \
-m64 \
-O2 \
-fno-strict-aliasing \
-fno-tree-vrp \
-fno-omit-frame-pointer
# Flags passed to only C files.
CFLAGS_C_Release :=
# Flags passed to only C++ files.
CFLAGS_CC_Release := \
-fno-rtti \
-fno-exceptions
INCS_Release := \
-I/home/matt/.node-gyp/0.10.24/src \
-I/home/matt/.node-gyp/0.10.24/deps/uv/include \
-I/home/matt/.node-gyp/0.10.24/deps/v8/include
OBJS := \
$(obj).target/$(TARGET)/src/binpack.o
# Add to the list of files we specially track dependencies for.
all_deps += $(OBJS)
# CFLAGS et al overrides must be target-local.
# See "Target-specific Variable Values" in the GNU Make manual.
$(OBJS): TOOLSET := $(TOOLSET)
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# End of this set of suffix rules
### Rules for final target.
LDFLAGS_Debug := \
-pthread \
-rdynamic \
-m64
LDFLAGS_Release := \
-pthread \
-rdynamic \
-m64
LIBS :=
$(obj).target/binpack.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
$(obj).target/binpack.node: LIBS := $(LIBS)
$(obj).target/binpack.node: TOOLSET := $(TOOLSET)
$(obj).target/binpack.node: $(OBJS) FORCE_DO_CMD
$(call do_cmd,solink_module)
all_deps += $(obj).target/binpack.node
# Add target alias
.PHONY: binpack
binpack: $(builddir)/binpack.node
# Copy this to the executable output path.
$(builddir)/binpack.node: TOOLSET := $(TOOLSET)
$(builddir)/binpack.node: $(obj).target/binpack.node FORCE_DO_CMD
$(call do_cmd,copy)
all_deps += $(builddir)/binpack.node
# Short alias for building this executable.
.PHONY: binpack.node
binpack.node: $(obj).target/binpack.node $(builddir)/binpack.node
# Add executable to "all" target.
.PHONY: all
all: $(builddir)/binpack.node

115
node_modules/binpack/build/config.gypi generated vendored Normal file
View File

@ -0,0 +1,115 @@
# Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"clang": 0,
"gcc_version": 48,
"host_arch": "x64",
"node_install_npm": "true",
"node_prefix": "/usr",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_openssl": "false",
"node_shared_v8": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_unsafe_optimizations": 0,
"node_use_dtrace": "false",
"node_use_etw": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"node_use_systemtap": "false",
"python": "/usr/bin/python",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_no_strict_aliasing": 1,
"v8_use_snapshot": "false",
"nodedir": "/home/matt/.node-gyp/0.10.24",
"copy_dev_lib": "true",
"standalone_static_library": 1,
"cache_lock_stale": "60000",
"sign_git_tag": "",
"always_auth": "",
"user_agent": "node/v0.10.24 linux x64",
"bin_links": "true",
"key": "",
"description": "true",
"fetch_retries": "2",
"heading": "npm",
"user": "",
"force": "",
"cache_min": "10",
"init_license": "ISC",
"editor": "vi",
"rollback": "true",
"cache_max": "null",
"userconfig": "/home/matt/.npmrc",
"engine_strict": "",
"init_author_name": "",
"init_author_url": "",
"tmp": "/home/matt/tmp",
"depth": "null",
"save_dev": "",
"usage": "",
"https_proxy": "",
"onload_script": "",
"rebuild_bundle": "true",
"save_bundle": "",
"shell": "/bin/bash",
"prefix": "/usr",
"registry": "https://registry.npmjs.org/",
"browser": "",
"cache_lock_wait": "10000",
"save_optional": "",
"searchopts": "",
"versions": "",
"cache": "/home/matt/.npm",
"ignore_scripts": "",
"searchsort": "name",
"version": "",
"local_address": "",
"viewer": "man",
"color": "true",
"fetch_retry_mintimeout": "10000",
"umask": "18",
"fetch_retry_maxtimeout": "60000",
"message": "%s",
"cert": "",
"global": "",
"link": "",
"save": "",
"unicode": "true",
"long": "",
"production": "",
"unsafe_perm": "true",
"node_version": "v0.10.24",
"tag": "latest",
"git_tag_version": "true",
"shrinkwrap": "true",
"fetch_retry_factor": "10",
"npat": "",
"proprietary_attribs": "true",
"strict_ssl": "true",
"username": "",
"dev": "",
"globalconfig": "/usr/etc/npmrc",
"init_module": "/home/matt/.npm-init.js",
"parseable": "",
"globalignorefile": "/usr/etc/npmignore",
"cache_lock_retries": "10",
"group": "1000",
"init_author_email": "",
"searchexclude": "",
"git": "git",
"optional": "true",
"email": "",
"json": ""
}
}

6
node_modules/binpack/changes.md generated vendored Normal file
View File

@ -0,0 +1,6 @@
# Changelog
## 0.0.3
Switched "repositories" to "repository" in package.json.
## 0.0.2
Updated documentation

1
node_modules/binpack/index.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('bindings')('binpack.node')

97
node_modules/binpack/node_modules/bindings/README.md generated vendored Normal file
View File

@ -0,0 +1,97 @@
node-bindings
=============
### Helper module for loading your native module's .node file
This is a helper module for authors of Node.js native addon modules.
It is basically the "swiss army knife" of `require()`ing your native module's
`.node` file.
Throughout the course of Node's native addon history, addons have ended up being
compiled in a variety of different places, depending on which build tool and which
version of node was used. To make matters worse, now the _gyp_ build tool can
produce either a _Release_ or _Debug_ build, each being built into different
locations.
This module checks _all_ the possible locations that a native addon would be built
at, and returns the first one that loads successfully.
Installation
------------
Install with `npm`:
``` bash
$ npm install bindings
```
Or add it to the `"dependencies"` section of your _package.json_ file.
Example
-------
`require()`ing the proper bindings file for the current node version, platform
and architecture is as simple as:
``` js
var bindings = require('bindings')('binding.node')
// Use your bindings defined in your C files
bindings.your_c_function()
```
Nice Error Output
-----------------
When the `.node` file could not be loaded, `node-bindings` throws an Error with
a nice error message telling you exactly what was tried. You can also check the
`err.tries` Array property.
```
Error: Could not load the bindings file. Tried:
→ /Users/nrajlich/ref/build/binding.node
→ /Users/nrajlich/ref/build/Debug/binding.node
→ /Users/nrajlich/ref/build/Release/binding.node
→ /Users/nrajlich/ref/out/Debug/binding.node
→ /Users/nrajlich/ref/Debug/binding.node
→ /Users/nrajlich/ref/out/Release/binding.node
→ /Users/nrajlich/ref/Release/binding.node
→ /Users/nrajlich/ref/build/default/binding.node
→ /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node
at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)
at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
...
```
License
-------
(The MIT License)
Copyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

159
node_modules/binpack/node_modules/bindings/bindings.js generated vendored Normal file
View File

@ -0,0 +1,159 @@
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path')
, join = path.join
, dirname = path.dirname
, exists = fs.existsSync || path.existsSync
, defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → '
, compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
, platform: process.platform
, arch: process.arch
, version: process.versions.node
, bindings: 'bindings.node'
, try: [
// node-gyp's linked version in the "build" dir
[ 'module_root', 'build', 'bindings' ]
// node-waf and gyp_addon (a.k.a node-gyp)
, [ 'module_root', 'build', 'Debug', 'bindings' ]
, [ 'module_root', 'build', 'Release', 'bindings' ]
// Debug files, for development (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Debug', 'bindings' ]
, [ 'module_root', 'Debug', 'bindings' ]
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Release', 'bindings' ]
, [ 'module_root', 'Release', 'bindings' ]
// Legacy from node-waf, node <= 0.4.x
, [ 'module_root', 'build', 'default', 'bindings' ]
// Production "Release" buildtype binary (meh...)
, [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
]
}
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings (opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts }
} else if (!opts) {
opts = {}
}
opts.__proto__ = defaults
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName())
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node'
}
var tries = []
, i = 0
, l = opts.try.length
, n
, b
, err
for (; i<l; i++) {
n = join.apply(null, opts.try[i].map(function (p) {
return opts[p] || p
}))
tries.push(n)
try {
b = opts.path ? require.resolve(n) : require(n)
if (!opts.path) {
b.path = n
}
return b
} catch (e) {
if (!/not find/i.test(e.message)) {
throw e
}
}
}
err = new Error('Could not locate the bindings file. Tried:\n'
+ tries.map(function (a) { return opts.arrow + a }).join('\n'))
err.tries = tries
throw err
}
module.exports = exports = bindings
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
*/
exports.getFileName = function getFileName () {
var origPST = Error.prepareStackTrace
, origSTL = Error.stackTraceLimit
, dummy = {}
, fileName
Error.stackTraceLimit = 10
Error.prepareStackTrace = function (e, st) {
for (var i=0, l=st.length; i<l; i++) {
fileName = st[i].getFileName()
if (fileName !== __filename) {
return
}
}
}
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy)
dummy.stack
// cleanup
Error.prepareStackTrace = origPST
Error.stackTraceLimit = origSTL
return fileName
}
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}

View File

@ -0,0 +1,32 @@
{
"name": "bindings",
"description": "Helper module for loading your native module's .node file",
"keywords": [
"native",
"addon",
"bindings",
"gyp",
"waf",
"c",
"c++"
],
"version": "1.1.1",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://tootallnate.net"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-bindings.git"
},
"main": "./bindings.js",
"readme": "node-bindings\n=============\n### Helper module for loading your native module's .node file\n\nThis is a helper module for authors of Node.js native addon modules.\nIt is basically the \"swiss army knife\" of `require()`ing your native module's\n`.node` file.\n\nThroughout the course of Node's native addon history, addons have ended up being\ncompiled in a variety of different places, depending on which build tool and which\nversion of node was used. To make matters worse, now the _gyp_ build tool can\nproduce either a _Release_ or _Debug_ build, each being built into different\nlocations.\n\nThis module checks _all_ the possible locations that a native addon would be built\nat, and returns the first one that loads successfully.\n\n\nInstallation\n------------\n\nInstall with `npm`:\n\n``` bash\n$ npm install bindings\n```\n\nOr add it to the `\"dependencies\"` section of your _package.json_ file.\n\n\nExample\n-------\n\n`require()`ing the proper bindings file for the current node version, platform\nand architecture is as simple as:\n\n``` js\nvar bindings = require('bindings')('binding.node')\n\n// Use your bindings defined in your C files\nbindings.your_c_function()\n```\n\n\nNice Error Output\n-----------------\n\nWhen the `.node` file could not be loaded, `node-bindings` throws an Error with\na nice error message telling you exactly what was tried. You can also check the\n`err.tries` Array property.\n\n```\nError: Could not load the bindings file. Tried:\n → /Users/nrajlich/ref/build/binding.node\n → /Users/nrajlich/ref/build/Debug/binding.node\n → /Users/nrajlich/ref/build/Release/binding.node\n → /Users/nrajlich/ref/out/Debug/binding.node\n → /Users/nrajlich/ref/Debug/binding.node\n → /Users/nrajlich/ref/out/Release/binding.node\n → /Users/nrajlich/ref/Release/binding.node\n → /Users/nrajlich/ref/build/default/binding.node\n → /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node\n at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)\n at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)\n at Module._compile (module.js:449:26)\n at Object.Module._extensions..js (module.js:467:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n ...\n```\n\n\nLicense\n-------\n\n(The MIT License)\n\nCopyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"readmeFilename": "README.md",
"bugs": {
"url": "https://github.com/TooTallNate/node-bindings/issues"
},
"homepage": "https://github.com/TooTallNate/node-bindings",
"_id": "bindings@1.1.1",
"_from": "bindings@*"
}

46
node_modules/binpack/package.json generated vendored Normal file
View File

@ -0,0 +1,46 @@
{
"name": "binpack",
"version": "0.0.14",
"main": "binpack",
"author": {
"name": "Russell McClellan",
"email": "russell.mcclellan@gmail.com",
"url": "http://www.ghostfact.com"
},
"description": "Minimalist numeric binary packing utilities for node.js",
"keywords": [
"binary",
"pack",
"unpack"
],
"repository": {
"type": "git",
"url": "http://github.com/russellmcc/node-binpack.git"
},
"dependencies": {
"bindings": "*"
},
"devDependencies": {
"vows": "*",
"coffee-script": "*"
},
"directories": {
"src": "src"
},
"engines": {
"node": ">=0.6.0"
},
"scripts": {
"test": "vows tests/*",
"install": "node-gyp rebuild"
},
"gypfile": true,
"readme": "# binpack\n\n_Minimalist numeric binary packing utilities for node.js_\n\n## What's all this?\n\nThis is an intentionally simple binary packing/unpacking package for node.js for programmers who prefer to write most of their parsing code in javascript. This exposes some common binary formats for numbers.\n\nsee the included COPYING file for licensing.\n\nthe core of the module is the set of `pack`/`unpack` pair functions. The meaning should be clear from the name - for example, `packInt32` packs a given javascript number into a 32-bit int inside a 4-byte node.js Buffer, while `unpackFloat32` unpacks a 4-byte node.js Buffer containing a native floating point number into a javascript number.\n\nThe following types are available for both pack and unpack:\n\n Float32 \n Float64 \n Int8\n Int16 \n Int32\n Int64\n UInt8 \n UInt16\n UInt32\n UInt64\n \nEach `pack*` function takes a javascript number and outputs a node.js Buffer.\n\nEach `unpack*` function takes a node.js Buffer and outputs a javascript number.\n\nBoth types of functions take an optional second argument. If this argument is `\"big\"`, the output is put in big endian format. If the argument is `\"little\"`, the output is put in little endian format. If the argument is anything else or non-existent, we default to your machine's native encoding.\n\n## How is this different than the `binary` module on npm?\n\nIt contains floating point values, and it has packing functions",
"readmeFilename": "readme.md",
"bugs": {
"url": "https://github.com/russellmcc/node-binpack/issues"
},
"homepage": "https://github.com/russellmcc/node-binpack",
"_id": "binpack@0.0.14",
"_from": "binpack@"
}

34
node_modules/binpack/readme.md generated vendored Normal file
View File

@ -0,0 +1,34 @@
# binpack
_Minimalist numeric binary packing utilities for node.js_
## What's all this?
This is an intentionally simple binary packing/unpacking package for node.js for programmers who prefer to write most of their parsing code in javascript. This exposes some common binary formats for numbers.
see the included COPYING file for licensing.
the core of the module is the set of `pack`/`unpack` pair functions. The meaning should be clear from the name - for example, `packInt32` packs a given javascript number into a 32-bit int inside a 4-byte node.js Buffer, while `unpackFloat32` unpacks a 4-byte node.js Buffer containing a native floating point number into a javascript number.
The following types are available for both pack and unpack:
Float32
Float64
Int8
Int16
Int32
Int64
UInt8
UInt16
UInt32
UInt64
Each `pack*` function takes a javascript number and outputs a node.js Buffer.
Each `unpack*` function takes a node.js Buffer and outputs a javascript number.
Both types of functions take an optional second argument. If this argument is `"big"`, the output is put in big endian format. If the argument is `"little"`, the output is put in little endian format. If the argument is anything else or non-existent, we default to your machine's native encoding.
## How is this different than the `binary` module on npm?
It contains floating point values, and it has packing functions

142
node_modules/binpack/src/binpack.cpp generated vendored Normal file
View File

@ -0,0 +1,142 @@
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <cstring>
using namespace node;
using namespace v8;
namespace
{
Handle<Value> except(const char* msg)
{
return ThrowException(Exception::Error(String::New(msg)));
}
enum ByteOrder
{
kNative,
kFlip
};
template <typename t>
t SwapBytes(const t& in)
{
t out;
const char* in_p = reinterpret_cast<const char*>(&in);
char* out_p = reinterpret_cast<char*>(&out) + sizeof(t) - 1;
for(; out_p >= reinterpret_cast<char*>(&out); --out_p, ++in_p)
{
*out_p = *in_p;
}
return out;
}
bool IsPlatformLittleEndian()
{
int32_t one = 1;
char* one_p = reinterpret_cast<char*>(&one);
if(*one_p == 1)
return true;
return false;
}
ByteOrder GetByteOrder(const Arguments& args)
{
// default to native.
if(!(args.Length() > 1))
return kNative;
Local<Value> arg = args[1];
if(arg->IsString())
{
char utf8[12];
arg->ToString()->WriteUtf8(utf8, 10);
if(!std::strncmp(utf8, "big", 10))
return IsPlatformLittleEndian() ? kFlip : kNative;
if(!std::strncmp(utf8, "little", 10))
return IsPlatformLittleEndian() ? kNative : kFlip;
}
return kNative;
}
template<typename t>
Handle<Value> unpackBuffer(const Arguments& args)
{
HandleScope scope;
if(args.Length() < 1)
return except("You must provide at least one argument.");
if(!Buffer::HasInstance(args[0]->ToObject()))
return except("The first argument must be a buffer.");
if(Buffer::Length(args[0]->ToObject()) != sizeof(t))
return except("Buffer is the incorrect length.");
ByteOrder order = GetByteOrder(args);
t nativeType = *reinterpret_cast<t*>(Buffer::Data(args[0]->ToObject()));
if(order == kFlip)
nativeType = SwapBytes(nativeType);
Local<Number> num = Number::New(nativeType);
return scope.Close(num);
}
template<typename t>
Handle<Value> packBuffer(const Arguments& args)
{
HandleScope scope;
if(args.Length() < 1)
return except("You must provide at least one argument.");
if(!args[0]->IsNumber ())
return except("The first argument must be a number.");
ByteOrder order = GetByteOrder(args);
Local<Number> num = args[0]->ToNumber();
t nativeType = num->Value();
if(order == kFlip)
nativeType = SwapBytes(nativeType);
Buffer* buff = Buffer::New(reinterpret_cast<char*>(&nativeType), sizeof(nativeType));
return scope.Close(buff->handle_);
}
}// private namespace
extern "C"
{
static void init(Handle<Object> target)
{
NODE_SET_METHOD(target, "unpackFloat32", unpackBuffer<float>);
NODE_SET_METHOD(target, "unpackFloat64", unpackBuffer<double>);
NODE_SET_METHOD(target, "unpackInt8", unpackBuffer<int8_t>);
NODE_SET_METHOD(target, "unpackInt16", unpackBuffer<int16_t>);
NODE_SET_METHOD(target, "unpackInt32", unpackBuffer<int32_t>);
NODE_SET_METHOD(target, "unpackInt64", unpackBuffer<int64_t>);
NODE_SET_METHOD(target, "unpackUInt8", unpackBuffer<uint8_t>);
NODE_SET_METHOD(target, "unpackUInt16", unpackBuffer<uint16_t>);
NODE_SET_METHOD(target, "unpackUInt32", unpackBuffer<uint32_t>);
NODE_SET_METHOD(target, "unpackUInt64", unpackBuffer<uint64_t>);
NODE_SET_METHOD(target, "packFloat32", packBuffer<float>);
NODE_SET_METHOD(target, "packFloat64", packBuffer<double>);
NODE_SET_METHOD(target, "packInt8", packBuffer<int8_t>);
NODE_SET_METHOD(target, "packInt16", packBuffer<int16_t>);
NODE_SET_METHOD(target, "packInt32", packBuffer<int32_t>);
NODE_SET_METHOD(target, "packInt64", packBuffer<int64_t>);
NODE_SET_METHOD(target, "packUInt8", packBuffer<uint8_t>);
NODE_SET_METHOD(target, "packUInt16", packBuffer<uint16_t>);
NODE_SET_METHOD(target, "packUInt32", packBuffer<uint32_t>);
NODE_SET_METHOD(target, "packUInt64", packBuffer<uint64_t>);
}
NODE_MODULE(binpack, init);
}

64
node_modules/binpack/tests/test-binpack.coffee generated vendored Normal file
View File

@ -0,0 +1,64 @@
vows = require "vows"
assert = require "assert"
binpack = require "../index"
# do a round trip
okayForOptions = (num, options) ->
return false if options.size? and Math.abs(num) > options.size?
return false if num < 0 and options.unsigned
true
roundTrip = (type, options) ->
works : (num) ->
return null if not okayForOptions(num, options)
assert.strictEqual (binpack["unpack" + type] binpack["pack" + type] num), num
"fails plus 1.1" : (num) ->
return null if not okayForOptions(num, options)
assert.notStrictEqual (binpack["unpack" + type] binpack["pack" + type] num + 1.1), num
"works little endian" : (num) ->
return null if options.onebyte
return null if not okayForOptions(num, options)
assert.strictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "little"), "little"), num
"works big endian" : (num) ->
return null if options.onebyte
return null if not okayForOptions(num, options)
assert.strictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "big"), "big"), num
"fails mismatched" : (num) ->
return null if not okayForOptions(num, options)
return null if num is 0
return null if options.onebyte
assert.notStrictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "little"), "big"), num
types =
"Float32" : {}
"Float64" : {}
"Int8" : {onebyte : true, size : 128}
"Int16" : {size : 32768}
"Int32" : {}
"Int64" : {}
"UInt8" : {unsigned : true, onebyte : true, size:255}
"UInt16" : {unsigned : true, size : 65535}
"UInt32" : {unsigned : true}
"UInt64" : {unsigned : true}
# round trip testing makes up the core of the test.
roundTripTests = (num) ->
tests = {topic : num}
for type, options of types
tests[type + "round trip test"] = roundTrip type, options
tests
vows.describe("binpack").addBatch(
# choose a bunch of random numbers
'roundTrips for 0' : roundTripTests 0
'roundTrips for 12' : roundTripTests 12
'roundTrips for -18' : roundTripTests -18
'roundTrips for 129' : roundTripTests 129
'roundTrips for -400' : roundTripTests -400
'roundTrips for 60000' : roundTripTests 60000
'roundTrips for 1234567' : roundTripTests 1234567
).export module

17
node_modules/binpack/wscript generated vendored Normal file
View File

@ -0,0 +1,17 @@
import Options
from os import unlink, symlink
from os.path import exists
def set_options(opt):
opt.tool_options("compiler_cxx")
def configure(conf):
conf.check_tool("compiler_cxx")
conf.check_tool("node_addon")
conf.env.set_variant("Release")
conf.env.append_value('CXXFLAGS', ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"])
def build(bld):
obj = bld.new_task_gen("cxx", "shlib", "node_addon")
obj.target = "binpack"
obj.source = "src/binpack.cpp"

177
old_blockTemplate.js Normal file
View File

@ -0,0 +1,177 @@
function BlockTemplate(jobId, data){
this.jobId = jobId;
//CBlock
this.nVersion = 1;
this.hashPrevBlock = 0;
this.hashMerkleRoot = 0;
this.nTime = 0;
this.nBits = 0;
this.nNonce = 0;
this.vtx = [];
this.sha256 = null;
this.scrypt = null;
//---
this.jobId = JobStore.nextId();
this.submits = [];
var txHashes = [null].concat(data.transactions.map(function(tx){
return util.uint256BufferFromHash(tx.hash);
}));
this.merkleTree = new merkle.Tree(txHashes);
this.coinbase = new coinbase.CoinbaseTransaction(
data.coinbasevalue,
data.coinbaseaux.flags,
data.height
);
this.vtx = [this.coinbase.tx];
data.transactions.each(function(tx){
var t = new coinbase.CTransaction();
t.deserialize(new Buffer(tx.data, 'hex'));
this.vtx.push(t);
});
this.height = data.height;
this.nVersion = data.version;
this.nBits = parseInt(data.bits, 16);
this.hashMerkleRoot = 0;
this.nNonce = 0;
this.curTime = data.curtime;
this.timeDelt = this.curTime - Math.floor(Date.now() / 1000);
this.target = util.uint256_from_compact(this.nBits);
this.prevHashBin = util.reverseBuffer(new Buffer(data.previousblockhash, 'hex'));
this.broadCastArgs = this.buildBroadcastArgs();
}
BlockTemplate.prototype = {
registerSubmit: function(extraNonce1, extraNonce2, nTime, nonce){
var t = [extraNonce1, extraNonce2, nTime, nonce];
this.submits.forEach(function(s){
if (s.join(',') == t.join(','))
return false;
});
this.submits.push(t);
return true;
},
buildBroadcastArgs: function(){
return [
this.jobId,
this.prevHashBin.toString('hex'),
this.coinbase.serialized[0].toString('hex'),
this.coinbase.serialized[1].toString('hex'),
this.merkleTree.steps.map(function(s){
return s.toString('hex');
}),
binpack.packInt32(this.nVersion, 'big').toString('hex'),
binpack.packUInt32(this.nBits, 'big').toString('hex'),
binpack.packUInt32(this.curTime, 'big').toString('hex'),
true //cleanJobs
];
},
serializeCoinbase: function(extraNonce1, extraNonce2){
var parts = this.coinbase.serialized;
return Buffer.concat([
parts[0],
extraNonce1,
extraNonce2,
parts[1]
]);
},
checkNTime: function(nTime){
if (nTime < this.curTime)
return false;
if (nTime > ((Date.now() / 1000) + 7200))
return false;
return true;
},
serializeHeader: function(merkleRootInt, nTimeBin, nonceBin){
return Buffer.concat([
binpack.packInt32(this.version, 'big'),
this.prevHashBin,
util.ser_uint256_be(merkleRootInt),
nTimeBin,
binpack.packUInt32(this.nBits, 'big'),
nonceBin
]);
},
finalize: function(merkleRootInt, extraNonce1Bin, extraNonce2Bin, nTime, nonce){
this.hashMerkleRoot = merkleRootInt;
this.nTime = nTime;
this.nNonce = nonce;
this.vtx[0].setExtraNonce(Buffer.concat([extraNonce1Bin, extraNonce2Bin]));
this.sha256 = null;
},
/* CBlock */
deserialize: function(f){
util.makeBufferReadable(f);
this.nVersion = f.read(4).readInt32LE(0);
this.hashPrevBlock = util.hexFromReversedBuffer(f.read(32));
this.hashMerkleRoot = util.hexFromReversedBuffer(f.read(32));
this.nTime = f.read(4).readUInt32LE(0);
this.nBits = f.read(4).readUInt32LE(0);
this.nNonce = f.read(4).readUInt32LE(0);
this.vtx = util.deser_vector(f, coinbase.CTransaction);
},
serialize: function(){
return Buffer.concat([
binpack.packInt32(this.nVersion, 'little'),
util.uint256BufferFromHash(this.hashPrevBlock),
util.uint256BufferFromHash(this.hashMerkleRoot),
binpack.packUInt32(this.nTime, 'little'),
binpack.packUInt32(this.nBits, 'little'),
binpack.packUInt32(this.nNonce, 'little'),
util.ser_vector(this.vtx)
]);
},
calcSha256: function(){
if (!this.sha256){
var r = Buffer.concat([
binpack.packInt32(this.nVersion, 'little'),
util.uint256BufferFromHash(this.hashPrevBlock),
util.uint256BufferFromHash(this.hashMerkleRoot),
binpack.packUInt32(this.nTime, 'little'),
binpack.packUInt32(this.nBits, 'little'),
binpack.packUInt32(this.nNonce, 'little')
]);
this.sha256 = util.doublesha(r);
}
return this.sha256;
},
calc_scrypt: function(){
},
is_valid: function(){
this.calc_sha256();
var target = bignum.fromBuffer(new Buffer(this.nBits, 'hex'));
if (bignum.fromBuffer(this.sha256).gt(target))
return false;
var hashes = [];
}
/* --- */
};

46
old_shareSubmit.js Normal file
View File

@ -0,0 +1,46 @@
var binpack = require('/usr/lib/node_modules/binpack');
var bignum = require('/usr/lib/node_modules/bignum');
var merkle = require('./merkleTree.js');
var coinbase = require('./coinbase.js');
var util = require('./util.js');
exports.submit = function(job_id, worker_name, extranonce1_bin, extranonce2, ntime, nonce, difficulty){
var job = JobStore.find(job_id);
var extraNonce2Size = coinbase.extranonce_size - ExtraNonceCounter.size();
if (extranonce2.length != extraNonce2Size * 2)
return {error: 'rejected'} //Incorrect size of extranonce2
if (!job)
return {error: 'unknown-work'}
if (ntime.length != 8)
return {error: 'rejected'}
if (!job.check_ntime(parseInt(ntime, 16)))
return {error: 'time-invalid'};
if (nonce.length != 8)
return {error: 'rejected'};
if (!job.register_submit(extranonce1_bin, extranonce2, ntime ,nonce))
return {error: 'duplicate'};
var extranonce2_bin = new Buffer(extranonce2, 'hex');
var ntime_bin = new Buffer(ntime, 'hex');
var nonce_bin = new Buffer(nonce, 'hex');
var coinbase_bin = job.serialize_coinbase(extranonce1_bin, extranonce2_bin);
var coinbase_hash = util.doublesha(coinbase_bin);
var merkle_root_bin = job.template.merkleTree.withFirst(coinbase_hash);
var merkle_root_int = util.uint
};

104
pool.js Normal file
View File

@ -0,0 +1,104 @@
var net = require('net');
var fs = require('fs');
var bignum = require('/usr/lib/node_modules/bignum');
var daemon = require('./daemon.js');
var stratum = require('./stratum.js');
var jobManager = require('./jobManager.js');
var util = require('./util.js');
var coinbase = require('./coinbase.js');
function Coin(options){
this.options = options;
}
Coin.prototype = {};
var coins = [
new Coin({
name: 'Dogecoin',
symbol: 'doge',
algorithm: 'scrypt',
address: 'D5uXR7F6bTCJKRZBqj1D4gyHF9MHAd5oNs',
daemon: {
bin: 'dogecoind',
port: 8332,
user: 'test',
password: 'test',
blocknotify: '"blockNotify.js doge %s"',
startIfOffline: true
}
})
];
coins.forEach(function(coin){
coin.jobManager = new jobManager({
algorithm: coin.options.algorithm,
address: coin.options.address
});
coin.jobManager.on('newBlock', function(blockTemplate){
coin.stratumServer.broadcastMiningJobs(blockTemplate.getJobParams());
});
coin.daemon = new daemon.interface(coin.options.daemon);
coin.daemon.on('online', function(){
coin.daemon.cmd(
'getblocktemplate',
[{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ]}],
function(error, response){
coin.jobManager.newTemplate(response.result);
console.log(coin.jobManager.currentJob.getJobParams());
}
);
}).on('startFailed', function(){
console.log('Failed to start daemon for ' + coin.name);
});
coin.stratumServer = new stratum.Server({
port: 3333
});
coin.stratumServer.on('client', function(client){
client.on('subscription', function(params, result){
var extraNonce = coin.jobManager.extraNonceCounter.next();
var extraNonce2Size = coinbase.extranonce_size - coin.jobManager.extraNonceCounter.size();
result(extraNonce, extraNonce2Size);
client.sendDifficulty(1);
client.sendMiningJob(coin.jobManager.currentJob.getJobParams());
}).on('authorize', function(params, result){
result(true);
}).on('submit', function(params, result){
result(true);
});
});
});
var blockNotifyServer = net.createServer(function(c) {
console.log('server connected');
var data = '';
c.on('data', function(d){
console.log('got blocknotify data');
data += d;
if (data.slice(-1) === '\n'){
c.end();
}
});
c.on('end', function() {
console.log(data);
console.log('server disconnected');
});
});
//blockNotifyServer.listen(8124, function() {});

3
required-modules.txt Normal file
View File

@ -0,0 +1,3 @@
binpack https://github.com/russellmcc/node-binpack
bignum https://github.com/justmoon/node-bignum
base58-native https://github.com/gasteve/node-base58

193
stratum.js Normal file
View File

@ -0,0 +1,193 @@
var net = require('net');
var events = require('events');
var binpack = require('/usr/lib/node_modules/binpack');
var util = require('./util.js');
var SubscriptionCounter = function(){
var count = 0;
var padding = 'deadbeefdeadbeef';
return {
next: function(){
count++;
if (Number.MAX_VALUE == count) count = 0;
return padding + binpack.packUInt64(count, 'big').toString('hex');
}
};
};
var StratumClient = function(options){
//private members
var _this = this;
(function init(){
setupSocket();
})();
function handleMessage(message){
switch(message.method){
case 'mining.subscribe':
handleSubscribe(message);
break;
case 'mining.authorize':
handleAuthorize(message);
break;
case 'mining.submit':
handleSubmit(message);
break;
default:
console.dir('unknown stratum client message: ' + message);
break;
}
}
function handleSubscribe(message){
_this.emit('subscription',
{},
function(extraNonce1, extraNonce2Size){
_this.extraNonce = extraNonce1;
sendJson({
id: message.id,
result: [
["mining.notify", options.subscriptionId],
extraNonce1,
extraNonce2Size
],
error: null
});
}
);
}
function handleAuthorize(message){
_this.emit('authorize',
{
name: message.params[0][0],
password: message.params[0][1]
},
function(authorized){
sendJson({
id: message.id,
result: authorized,
error: null
});
}
);
}
function handleSubmit(message){
_this.emit('submit',
{
name: message.params[0],
jobId: message.params[1],
extraNonce2: message.params[2],
nTime: message.params[3],
nonce: message.params[4]
},
function(accepted){
sendJson({
id: message.id,
result: accepted,
error: null
});
}
);
}
function sendJson(){
var response = '';
for (var i = 0; i < arguments.length; i++){
response += JSON.stringify(arguments[i]) + '\n';
}
console.log('response: ' + response);
options.socket.write(response);
}
function setupSocket(){
var socket = options.socket;
var dataBuffer = '';
socket.setEncoding('utf8');
socket.on('data', function(d){
console.log('request: ' + d);
dataBuffer += d;
if (dataBuffer.slice(-1) === '\n'){
var messages = dataBuffer.split('\n');
messages.forEach(function(message){
var messageJson;
try{
messageJson = JSON.parse(message);
}
catch(e){
console.log('could not parse stratum client socket message: ' + message);
}
if (messageJson)
handleMessage(messageJson);
});
dataBuffer = '';
}
});
socket.on('end', function() {
_this.emit('socketDisconnect')
console.log('stratum client disconnected');
});
socket.on('error', function(){
_this.emit('socketError');
console.log('stratum client socket error');
});
}
//public members
this.sendDifficulty = function(difficulty){
sendJson({
id: null,
method: "mining.set_difficulty",
params: [difficulty]//[512],
});
};
this.sendMiningJob = function(jobParams){
sendJson({
id: null,
method: "mining.notify",
params: jobParams
});
};
};
StratumClient.prototype.__proto__ = events.EventEmitter.prototype;
var StratumServer = exports.Server = function StratumServer(options){
//private members
var _this = this;
var _socketServer;
var _stratumClients = {};
var _subscriptionCounter = SubscriptionCounter();
(function init(){
_socketServer = socketServer = net.createServer(function(c){
var subscriptionId = _subscriptionCounter.next();
var client = new StratumClient({subscriptionId: subscriptionId, socket: c});
_stratumClients[subscriptionId] = client;
_this.emit('client', client);
});
_socketServer.listen(options.port, function(){});
})();
//public members
this.broadcastMiningJobs = function(jobParams){
for (var clientId in _stratumClients){
_stratumClients[clientId].sendMiningJob(jobParams)
}
};
};
StratumServer.prototype.__proto__ = events.EventEmitter.prototype;

3
templateRegistry.js Normal file
View File

@ -0,0 +1,3 @@

289
util.js Normal file
View File

@ -0,0 +1,289 @@
var crypto = require('crypto');
var binpack = require('/usr/lib/node_modules/binpack');
var base58 = require('/usr/lib/node_modules/base58-native');
var bignum = require('/usr/lib/node_modules/bignum');
exports.bignumFromBits = function(bitsString){
var bitsBuff = new Buffer(bitsString, 'hex');
var numBytes = bitsBuff.readUInt8(0);
var bigBits = bignum.fromBuffer(bitsBuff.slice(1));
var target = bigBits.mul(
bignum(2).pow(
bignum(8).mul(
numBytes - 3
)
)
);
return target;
};
exports.bignumFromTarget = function(targetString){
return bignum.fromBuffer(new Buffer(targetString, 'hex'));
};
exports.doublesha = function(buffer){
var hash1 = crypto.createHash('sha256');
hash1.update(buffer);
hash1 = hash1.digest();
var hash2 = crypto.createHash('sha256');
hash2.update(hash1);
hash2 = hash2.digest();
return hash2;
};
exports.makeBufferReadable = function(buffer){
var position = 0;
buffer.read = function(length){
var section = buffer.slice(position, length ? (position + length) : buffer.length);
position += length;
return MakeBufferReadable(section);
}
return buffer;
};
exports.reverseBuffer = function(buff){
var reversed = new Buffer(buff.length);
for (var i = 0; i < buff.length; i++){
reversed[buff.length - (i + 1)] = buff[i];
}
return reversed;
};
exports.reverseHex = function(hex){
return exports.reverseBuffer(new Buffer(hex, 'hex')).toString('hex');
};
exports.uint256BufferFromHash = function(hex){
var fromHex = new Buffer(hex, 'hex');
if (buffer.length != 32){
var empty = new Buffer(32);
empty.fill(0);
fromHex.copy(empty);
fromHex = empty;
}
return exports.reverseBuffer(fromHex);
};
exports.hexFromReversedBuffer = function(buffer){
return exports.reverseBuffer(buffer).toString('hex');
};
exports.randomId = function(){
var text = "";
var possible = "abcdef0123456789";
for (var i = 0; i < 32; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
exports.uint256_from_compact = function(c){
var nbytes = (c >> 24) & 0xFF;
v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
return v;
};
exports.uint256_from_str = function(s){
var r = 0;
var t = binpack.unpack
};
exports.ser_uint256_be = function(u){
var rs = new Buffer(0);
exports.range(8).forEach(function(i){
rs = Buffer.concat([
rs,
binpack.packUInt32(u & 0xFFFFFFFF, 'big')
]);
u >>= 32;
});
return rs;
};
//use reversedbufferfromhex
/*
exports.ser_uint256 = function(u){
var rs = new Buffer(0);
exports.range(8).forEach(function(i){
rs = Buffer.concat([
rs,
binpack.packUInt32(u & 0xFFFFFFFF, 'little')
]);
u >>= 32;
});
return rs;
};
*/
//use hexfromrevsersedbuffer
/*
exports.deser_uint256 = function(f){
var r = 0;
exports.range(8).forEach(function(i){
var t = f.read(4).readUInt32LE(4);
r += t << (i * 32);
});
return r;
};
*/
exports.serializeNumber = function(n){
if (n < 0xfd){
var buff = new Buffer(2);
buff[0] = 0x1;
buff.writeUInt8(n, 1);
return buff;
}
else if (n <= 0xffff){
var buff = new Buffer(4);
buff[0] = 0x3;
buff.writeUInt16BE(n, 1);
return buff;
}
else if (n <= 0xffffffff){
var buff = new Buffer(6);
buff[0] = 0x5;
buff.writeUInt32BE(n, 1);
return buff;
}
else{
return Buffer.concat([new Buffer([0x9]), binpack.packUInt64(n, 'little')]);
}
};
exports.ser_string = function(s){
if (s.length < 253)
return Buffer.concat([
new Buffer([s.length]),
new Buffer(s)
]);
else if (s.length < 0x10000)
return Buffer.concat([
new Buffer([253]),
binpack.packUInt16(s.length, 'little'),
new Buffer(s)
]);
else if (s.length < 0x100000000)
return Buffer.concat([
new Buffer([254]),
binpack.packUInt32(s.length, 'little'),
new Buffer(s)
]);
else
return Buffer.concat([
new Buffer([255]),
binpack.packUInt64(s.length),
new Buffer(s)
]);
};
exports.deser_string = function(f){
var nit = f.read(1).readUInt8(0);
if (nit == 253)
nit = f.read(2).readUInt16LE(0);
else if (nit == 254)
nit = f.read(4).readUInt32LE(1);
else if (nit == 255)
nit = f.read(8).readUInt64LE(1);
return f.read(nit);
};
exports.ser_vector = function(l){
var r;
if (l.length < 253)
r = new Buffer([l.length]);
else if (l.length < 0x10000)
r = Buffer.concat([new Buffer([253]), binpack.packUInt16(l.length, 'little')]);
else if (l.length < 0x100000000)
r = Buffer.concat([new Buffer([254]), binpack.packUInt32(l.length, 'little')]);
else
r = Buffer.concat([new Buffer([255]), binpack.packUInt64(l.length, 'little')]);
l.forEach(function(i){
r = Buffer.concat([r, i.serialize()]);
});
return r;
};
exports.deser_vector = function(f, c){
var nit = f.read(1).readUInt8(0);
if (nit == 253)
nit = f.read(2).readUInt16LE(0);
else if (nit == 254)
nit = f.read(4).readUInt32LE(0);
else if (nit == 255)
nit = f.read(8).readUInt64LE(0);
var r = [];
exports.range(nit).forEach(function(i){
var t = new c();
t.deserialize(f);
r.push(t);
});
return r;
};
exports.range = function(start, stop, step){
if (typeof stop == 'undefined'){
stop = start;
start = 0;
}
if (typeof step == 'undefined'){
step = 1;
}
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)){
return [];
}
var result = [];
for (var i = start; step > 0 ? i < stop : i > stop; i += step){
result.push(i);
}
return result;
};
exports.address_to_pubkeyhash = function(addr){
addr = base58.decode(addr);
if (addr.length != 25){
console.log('invalid address length for ' + addr);
throw 'invalid address length';
}
if (!addr)
return null;
var ver = addr[0];
var cksumA = addr.slice(-4);
var cksumB = exports.doublesha(addr.slice(0, -4)).slice(0, 4);
if (cksumA.toString('hex') != cksumB.toString('hex'))
throw 'checksum did not match';
return [ver, addr.slice(1,-4)];
};
exports.script_to_address = function(addr){
var d = exports.address_to_pubkeyhash(addr)
if (!d)
throw "invalid address";
var ver = d[0];
var pubkeyhash = d[1];
return Buffer.concat([new Buffer([0x76, 0xa9, 0x14]), pubkeyhash, new Buffer([0x88, 0xac])]);
};