Merge pull request #760 from eordano/docs/jsdocs

Review JSDocs
This commit is contained in:
Manuel Aráoz 2014-12-16 17:41:09 -03:00
commit 1b9ac8243d
23 changed files with 329 additions and 142 deletions

1
.gitignore vendored
View File

@ -16,3 +16,4 @@ apiref
bower_components bower_components
dist dist
report report
.DS_Store

36
.jsdoc.conf Normal file
View File

@ -0,0 +1,36 @@
{
"tags": {
"allowUnknownTags": true
},
"source": {
"include": ["docs/README.md"],
"exclude": [],
"includePattern": "lib/.+\\.js(doc)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins": ["plugins/markdown"],
"templates": {
"cleverLinks": false,
"monospaceLinks": false
},
"opts": {
"template": "node_modules/ink-docstrap/template",
"encoding": "utf8",
"destination": "./apiref/",
"recurse": true,
"query": "value",
"private": true,
"lenient": true
},
"templates": {
"systemName": "bitcore",
"copyright": "© 2013-2014, BitPay Inc.",
"navType": "vertical",
"theme": "journal",
"linenums": true,
"collapseSymbols": false,
"inverseNav": false,
"outputSourceFiles": true
}
}

BIN
apiref.zip Normal file

Binary file not shown.

View File

@ -3,10 +3,29 @@
* *
* Defines tasks that can be run on gulp. * Defines tasks that can be run on gulp.
* *
* Summary: * Summary: <ul>
* * test - Run tests * <li> `test` - runs all the tests on node and the browser (mocha and karma)
* * watch:test - Waits for filesystem changes and runs tests * <ul>
* * <li> `test:node`
* <li> `test:node:nofail` - internally used for watching (due to bug on gulp-mocha)
* <li> `test:browser`
* </ul>`
* <li> `watch:test` - watch for file changes and run tests
* <ul>
* <li> `watch:test:node`
* <li> `watch:test:browser`
* </ul>`
* <li> `browser` - generate files needed for browser (browserify)
* <ul>
* <li> `browser:uncompressed` - build `browser/bitcore.js`
* <li> `browser:compressed` - build `browser/bitcore.min.js`
* <li> `browser:maketests` - build `browser/tests.js`, needed for testing without karma
* </ul>`
* <li> `errors` - autogenerate the `./lib/errors/index.js` file with error definitions
* <li> `lint` - run `jshint`
* <li> `coverage` - run `istanbul` with mocha to generate a report of test coverage
* <li> `jsdoc` - run `jsdoc` to generate the API reference
* </ul>
*/ */
'use strict'; 'use strict';
@ -41,21 +60,98 @@ var testKarma = shell.task([
'./node_modules/karma/bin/karma start --single-run --browsers Firefox' './node_modules/karma/bin/karma start --single-run --browsers Firefox'
]); ]);
/**
* Testing
*/
gulp.task('test', ['errors'], testMocha); gulp.task('test:node', ['errors'], testMocha);
gulp.task('test-all', ['errors'], function(callback) { gulp.task('test:node:nofail', ['errors'], function() {
runSequence(['test'], ['karma'], callback);
});
gulp.task('test-nofail', ['errors'], function() {
return testMocha().on('error', ignoreError); return testMocha().on('error', ignoreError);
}); });
gulp.task('test:browser', ['browser:uncompressed', 'browser:maketests'], testKarma);
gulp.task('test', function(callback) {
runSequence(['test:node'], ['test:browser'], callback);
});
/**
* File generation
*/
gulp.task('browser:uncompressed', ['errors'], shell.task([
'./node_modules/.bin/browserify index.js --insert-global-vars=true --standalone=bitcore -o browser/bitcore.js'
]));
gulp.task('browser:compressed', ['errors'], function() {
return gulp.src('dist/bitcore.js')
.pipe(closureCompiler({
fileName: 'bitcore.min.js',
compilerPath: 'node_modules/closure-compiler-jar/compiler.jar',
compilerFlags: {
language_in: 'ECMASCRIPT5',
jscomp_off: 'suspiciousCode'
}
}))
.pipe(gulp.dest('dist'));
});
gulp.task('browser:maketests', shell.task([
'find test/ -type f -name "*.js" | xargs ./node_modules/.bin/browserify -t brfs -o browser/tests.js'
]));
gulp.task('browser', ['errors'], function(callback) {
runSequence(['browser:uncompressed'], ['browser:compressed'], ['browser:maketests'], callback);
});
gulp.task('errors', shell.task([
'node ./lib/errors/build.js'
]));
/**
* Code quality and documentation
*/
gulp.task('lint', function() {
return gulp.src(alljs)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('plato', shell.task['plato -d report -r -l .jshintrc -t bitcore lib']);
gulp.task('jsdoc', shell.task['jsdoc -c .jsdoc.conf lib']);
gulp.task('coverage', shell.task(['istanbul cover _mocha -- --recursive']));
/**
* Watch tasks
*/
gulp.task('watch:test', function() { gulp.task('watch:test', function() {
// TODO: Only run tests that are linked to file changes by doing // TODO: Only run tests that are linked to file changes by doing
// something smart like reading through the require statements // something smart like reading through the require statements
return gulp.watch(alljs, ['test-nofail']); return gulp.watch(alljs, ['test']);
});
gulp.task('watch:test:node', function() {
// TODO: Only run tests that are linked to file changes by doing
// something smart like reading through the require statements
return gulp.watch(alljs, ['test:node']);
});
gulp.task('watch:test:browser', function() {
// TODO: Only run tests that are linked to file changes by doing
// something smart like reading through the require statements
return gulp.watch(alljs, ['test:browser']);
});
gulp.task('watch:jsdoc', function() {
// TODO: Only run tests that are linked to file changes by doing
// something smart like reading through the require statements
return gulp.watch(alljs, ['jsdoc']);
}); });
gulp.task('watch:coverage', function() { gulp.task('watch:coverage', function() {
@ -71,64 +167,15 @@ gulp.task('watch:lint', function() {
}); });
gulp.task('watch:browser', function() { gulp.task('watch:browser', function() {
return gulp.watch(alljs, ['browser-all']); return gulp.watch(alljs, ['browser']);
});
gulp.task('coverage', shell.task(['istanbul cover _mocha -- --recursive']));
gulp.task('jsdoc', function() {
return gulp.src(files.concat([jsdocReadme]))
.pipe(jsdoc.parser())
.pipe(jsdoc.generator('./apiref', {
path: 'ink-docstrap',
theme: 'flatly',
}));
});
gulp.task('lint', function() {
return gulp.src(alljs)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('browser', ['errors'], shell.task([
'./node_modules/.bin/browserify index.js --insert-global-vars=true --standalone=bitcore -o browser/bitcore.js'
]));
gulp.task('browser-test', shell.task([
'find test/ -type f -name "*.js" | xargs ./node_modules/.bin/browserify -t brfs -o browser/tests.js'
]));
gulp.task('browser-all', ['errors'], function(callback) {
runSequence(['browser'], ['browser-test'], callback);
});
gulp.task('karma', ['browser-all'], testKarma);
gulp.task('plato', shell.task[
'plato -d report -r -l .jshintrc -t bitcore lib'
]);
gulp.task('errors', shell.task([
'node ./lib/errors/build.js'
]));
gulp.task('minify', ['errors'], function() {
return gulp.src('dist/bitcore.js')
.pipe(closureCompiler({
fileName: 'bitcore.min.js',
compilerPath: 'node_modules/closure-compiler-jar/compiler.jar',
compilerFlags: {
language_in: 'ECMASCRIPT5',
jscomp_off: 'suspiciousCode'
}
}))
.pipe(gulp.dest('dist'));
}); });
/**
* Default task
*/
gulp.task('default', function(callback) { gulp.task('default', function(callback) {
return runSequence(['lint', 'jsdoc'], return runSequence(['lint', 'jsdoc'],
['browser', 'test'], ['browser:uncompressed', 'test'],
['coverage', 'minify'], ['coverage', 'browser:compressed'],
callback); callback);
}); });

View File

@ -20,16 +20,12 @@ bitcore.encoding.Varint = require('./lib/encoding/varint');
// utilities // utilities
bitcore.util = {}; bitcore.util = {};
bitcore.util.bitcoin = require('./lib/util/bitcoin');
bitcore.util.buffer = require('./lib/util/buffer'); bitcore.util.buffer = require('./lib/util/buffer');
bitcore.util.js = require('./lib/util/js'); bitcore.util.js = require('./lib/util/js');
bitcore.util.preconditions = require('./lib/util/preconditions'); bitcore.util.preconditions = require('./lib/util/preconditions');
// transport // transport
bitcore.transport = {}; bitcore.transport = require('./lib/transport');
bitcore.transport.Peer = require('./lib/transport/peer');
bitcore.transport.Messages = require('./lib/transport/messages');
bitcore.transport.Pool = require('./lib/transport/pool');
// errors thrown by the library // errors thrown by the library
bitcore.errors = require('./lib/errors'); bitcore.errors = require('./lib/errors');

View File

@ -8,10 +8,16 @@ var JSUtil = require('./util/js');
/** /**
* Instantiate an address from an address String or Buffer, a public key or script hash Buffer, * Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
* or an instance of PublicKey or Script. * or an instance of {@link PublicKey} or {@link Script}.
*
* This is an immutable class, and if the first parameter provided to this constructor is an
* `Address` instance, the same argument will be returned.
*
* An address has two key properties: `network` and `type`. The type is either
* `Address.PayToPublicKeyHash` (value is the `'pubkeyhash'` string)
* or `Address.PayToScriptHash` (the string `'scripthash'`). The network is an instance of {@link Network}.
* *
* @example * @example
*
* // validate that an input field is valid * // validate that an input field is valid
* var error = Address.getValidationError(input, 'testnet'); * var error = Address.getValidationError(input, 'testnet');
* if (!error) { * if (!error) {
@ -24,9 +30,8 @@ var JSUtil = require('./util/js');
* // get an address from a public key * // get an address from a public key
* var address = Address(publicKey, 'testnet').toString(); * var address = Address(publicKey, 'testnet').toString();
* *
* * @param {*} data - The encoded data in various formats
* @param {String} data - The encoded data in various formats * @param {Network|String|number} [network] - The network: 'livenet' or 'testnet'
* @param {String} [network] - The network: 'livenet' or 'testnet'
* @param {String} [type] - The type of address: 'script' or 'pubkey' * @param {String} [type] - The type of address: 'script' or 'pubkey'
* @returns {Address} A new valid and frozen instance of an Address * @returns {Address} A new valid and frozen instance of an Address
* @constructor * @constructor
@ -90,7 +95,12 @@ function Address(data, network, type) {
return this; return this;
} }
/** @static */
Address.PayToPublicKeyHash = 'pubkeyhash'; Address.PayToPublicKeyHash = 'pubkeyhash';
/**
* @static
* @value 'scripthash'
*/
Address.PayToScriptHash = 'scripthash'; Address.PayToScriptHash = 'scripthash';
/** /**

View File

@ -12,21 +12,22 @@ var Transaction = require('./transaction');
var Varint = require('./encoding/varint'); var Varint = require('./encoding/varint');
/** /**
* @class Block
* Instantiate a Block from a Buffer, JSON object, or Object with * Instantiate a Block from a Buffer, JSON object, or Object with
* the properties of the Block * the properties of the Block
* *
* @param {*} - A Buffer, JSON string, or Object * @param {*} - A Buffer, JSON string, or Object
* @returns {Block} - An instance of Block * @returns {Block}
* @constructor * @constructor
*/ */
var Block = function Block(arg) { function Block(arg) {
if (!(this instanceof Block)) { if (!(this instanceof Block)) {
return new Block(arg); return new Block(arg);
} }
_.extend(this, Block._from(arg)); _.extend(this, Block._from(arg));
this._setupProperties(); this._setupProperties();
return this; return this;
}; }
/** /**
* @param {*} - A Buffer, JSON string or Object * @param {*} - A Buffer, JSON string or Object
@ -42,10 +43,26 @@ Block._from = function _from(arg) {
info = Block._fromJSON(arg); info = Block._fromJSON(arg);
} else if (_.isObject(arg)) { } else if (_.isObject(arg)) {
info = { info = {
/**
* @name Block#magicnum
* @type number
*/
magicnum: arg.magicnum, magicnum: arg.magicnum,
/**
* @name Block#blocksize
* @type number
*/
blocksize: arg.blocksize, blocksize: arg.blocksize,
/**
* @name Block#blockheader
* @type {BlockHeader}
*/
blockheader: arg.blockheader, blockheader: arg.blockheader,
txsvi: arg.txsvi, txsvi: arg.txsvi,
/**
* @name Block#txs
* @type {Transaction[]}
*/
txs: arg.txs txs: arg.txs
}; };
} else { } else {
@ -59,18 +76,35 @@ Block._from = function _from(arg) {
* easier access * easier access
*/ */
Block.prototype._setupProperties = function() { Block.prototype._setupProperties = function() {
/**
* @name Block#version
* @type {number}
*/
Object.defineProperty(this, 'version', { Object.defineProperty(this, 'version', {
configurable: false, configurable: false,
value: this.blockheader.version value: this.blockheader.version
}); });
/**
* @name Block#timestamp
* @type {number}
*/
Object.defineProperty(this, 'timestamp', { Object.defineProperty(this, 'timestamp', {
configurable: false, configurable: false,
value: this.blockheader.timestamp value: this.blockheader.timestamp
}); });
/**
* @name Block#nonce
* @type {number}
*/
Object.defineProperty(this, 'nonce', { Object.defineProperty(this, 'nonce', {
configurable: false, configurable: false,
value: this.blockheader.nonce value: this.blockheader.nonce
}); });
/**
* Amount of bytes of the serialized block
* @name Block#size
* @type {number}
*/
Object.defineProperty(this, 'size', { Object.defineProperty(this, 'size', {
configurable: false, configurable: false,
value: this.blockheader.size value: this.blockheader.size

View File

@ -35,7 +35,7 @@ var traverseRoot = function(errorsDefinition) {
var fullName = 'bitcore.Error'; var fullName = 'bitcore.Error';
var path = 'Error'; var path = 'Error';
var generated = '\'use strict\';\n\nvar inherits = require(\'inherits\');\n\n'; var generated = '\'use strict\';\n\nvar inherits = require(\'inherits\');\n\n';
generated += '/** AUTOGENERATED FILE. DON\'T EDIT, MODIFY "lib/errors/spec.js" INSTEAD */\n\n'; generated += '/* AUTOGENERATED FILE. DON\'T EDIT, MODIFY "lib/errors/spec.js" INSTEAD */\n\n';
generated += 'var bitcore = {};\n\n'; generated += 'var bitcore = {};\n\n';
generated += defineElement(fullName, path, '\'Internal error\''); generated += defineElement(fullName, path, '\'Internal error\'');
generated += childDefinitions(fullName, errorsDefinition); generated += childDefinitions(fullName, errorsDefinition);

View File

@ -398,20 +398,20 @@ HDPrivateKey.prototype.inspect = function() {
/** /**
* Returns a plain object with a representation of this private key. * Returns a plain object with a representation of this private key.
* *
* Fields include: * Fields include:<ul>
* * network: either 'livenet' or 'testnet' * <li> network: either 'livenet' or 'testnet'
* * depth: a number ranging from 0 to 255 * <li> depth: a number ranging from 0 to 255
* * fingerPrint: a number ranging from 0 to 2^32-1, taken from the hash of the * <li> fingerPrint: a number ranging from 0 to 2^32-1, taken from the hash of the
* associated public key * <li> associated public key
* * parentFingerPrint: a number ranging from 0 to 2^32-1, taken from the hash * <li> parentFingerPrint: a number ranging from 0 to 2^32-1, taken from the hash
* of this parent's associated public key or zero. * <li> of this parent's associated public key or zero.
* * childIndex: the index from which this child was derived (or zero) * <li> childIndex: the index from which this child was derived (or zero)
* * chainCode: an hexa string representing a number used in the derivation * <li> chainCode: an hexa string representing a number used in the derivation
* * privateKey: the private key associated, in hexa representation * <li> privateKey: the private key associated, in hexa representation
* * xprivkey: the representation of this extended private key in checksum * <li> xprivkey: the representation of this extended private key in checksum
* base58 format * <li> base58 format
* * checksum: the base58 checksum of xprivkey * <li> checksum: the base58 checksum of xprivkey
* * </ul>
* @return {Object} * @return {Object}
*/ */
HDPrivateKey.prototype.toObject = function toObject() { HDPrivateKey.prototype.toObject = function toObject() {

View File

@ -361,18 +361,19 @@ HDPublicKey.prototype.inspect = function() {
/** /**
* Returns a plain javascript object with information to reconstruct a key. * Returns a plain javascript object with information to reconstruct a key.
* *
* Fields are: * Fields are: <ul>
* * network: 'livenet' or 'testnet' * <li> network: 'livenet' or 'testnet'
* * depth: a number from 0 to 255, the depth to the master extended key * <li> depth: a number from 0 to 255, the depth to the master extended key
* * fingerPrint: a number of 32 bits taken from the hash of the public key * <li> fingerPrint: a number of 32 bits taken from the hash of the public key
* * fingerPrint: a number of 32 bits taken from the hash of this key's * <li> fingerPrint: a number of 32 bits taken from the hash of this key's
* parent's public key * <li> parent's public key
* * childIndex: index with which this key was derived * <li> childIndex: index with which this key was derived
* * chainCode: string in hexa encoding used for derivation * <li> chainCode: string in hexa encoding used for derivation
* * publicKey: string, hexa encoded, in compressed key format * <li> publicKey: string, hexa encoded, in compressed key format
* * checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), * <li> checksum: BufferUtil.integerFromBuffer(this._buffers.checksum),
* * xpubkey: the string with the base58 representation of this extended key * <li> xpubkey: the string with the base58 representation of this extended key
* * checksum: the base58 checksum of xpubkey * <li> checksum: the base58 checksum of xpubkey
* </ul>
*/ */
HDPublicKey.prototype.toObject = function toObject() { HDPublicKey.prototype.toObject = function toObject() {
return { return {
@ -388,6 +389,10 @@ HDPublicKey.prototype.toObject = function toObject() {
}; };
}; };
/**
* Serializes this object into a JSON string
* @return {string}
*/
HDPublicKey.prototype.toJSON = function toJSON() { HDPublicKey.prototype.toJSON = function toJSON() {
return JSON.stringify(this.toObject()); return JSON.stringify(this.toObject());
}; };

View File

@ -262,7 +262,7 @@ PublicKey.fromDER = PublicKey.fromBuffer = function(buf, strict) {
* Instantiate a PublicKey from a Point * Instantiate a PublicKey from a Point
* *
* @param {Point} point - A Point instance * @param {Point} point - A Point instance
* @param {boolean=true} compressed - whether to store this public key as compressed format * @param {boolean=} compressed - whether to store this public key as compressed format
* @returns {PublicKey} A new valid instance of PublicKey * @returns {PublicKey} A new valid instance of PublicKey
*/ */
PublicKey.fromPoint = function(point, compressed) { PublicKey.fromPoint = function(point, compressed) {

View File

@ -551,7 +551,7 @@ Script.buildMultisigOut = function(pubkeys, m, opts) {
* @param {number} threshold amount of required signatures to spend the output * @param {number} threshold amount of required signatures to spend the output
* @param {Array} signatures signatures to append to the script * @param {Array} signatures signatures to append to the script
* @param {Object=} opts * @param {Object=} opts
* @param {boolean=false} opts.noSorting don't sort the given public keys before creating the script * @param {boolean=} opts.noSorting don't sort the given public keys before creating the script (false by default)
* @param {Script=} opts.cachedMultisig don't recalculate the redeemScript * @param {Script=} opts.cachedMultisig don't recalculate the redeemScript
* *
* @returns Script * @returns Script
@ -632,7 +632,7 @@ Script.buildScriptHashOut = function(script) {
* *
* @param {Buffer|string|PublicKey} publicKey * @param {Buffer|string|PublicKey} publicKey
* @param {Buffer} signature - the signature in DER cannonical encoding * @param {Buffer} signature - the signature in DER cannonical encoding
* @param {number=1} sigtype - the type of the signature (defaults to SIGHASH_ALL) * @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL)
*/ */
Script.buildPublicKeyHashIn = function(publicKey, signature, sigtype) { Script.buildPublicKeyHashIn = function(publicKey, signature, sigtype) {
var script = new Script() var script = new Script()

View File

@ -12,6 +12,9 @@ var Signature = require('../../crypto/signature');
var Sighash = require('../sighash'); var Sighash = require('../sighash');
var BufferUtil = require('../../util/buffer'); var BufferUtil = require('../../util/buffer');
/**
* @constructor
*/
function MultiSigScriptHashInput(input, pubkeys, threshold) { function MultiSigScriptHashInput(input, pubkeys, threshold) {
Input.apply(this, arguments); Input.apply(this, arguments);
var self = this; var self = this;

View File

@ -14,6 +14,7 @@ var Signature = require('../../crypto/signature');
/** /**
* Represents a special kind of input of PayToPublicKeyHash kind. * Represents a special kind of input of PayToPublicKeyHash kind.
* @constructor
*/ */
function PublicKeyHashInput() { function PublicKeyHashInput() {
Input.apply(this, arguments); Input.apply(this, arguments);
@ -25,7 +26,7 @@ inherits(PublicKeyHashInput, Input);
* @param {Transaction} transaction - the transaction to be signed * @param {Transaction} transaction - the transaction to be signed
* @param {PrivateKey} privateKey - the private key with which to sign the transaction * @param {PrivateKey} privateKey - the private key with which to sign the transaction
* @param {number} index - the index of the input in the transaction input vector * @param {number} index - the index of the input in the transaction input vector
* @param {number=Singature.SIGHASH_ALL} sigtype - the type of signature * @param {number=} sigtype - the type of signature, defaults to Signature.SIGHASH_ALL
* @param {Buffer=} hashData - the precalculated hash of the public key associated with the privateKey provided * @param {Buffer=} hashData - the precalculated hash of the public key associated with the privateKey provided
* @return {Array} of objects that can be * @return {Array} of objects that can be
*/ */
@ -54,7 +55,7 @@ PublicKeyHashInput.prototype.getSignatures = function(transaction, privateKey, i
* @param {Object} signature * @param {Object} signature
* @param {PublicKey} signature.publicKey * @param {PublicKey} signature.publicKey
* @param {Signature} signature.signature * @param {Signature} signature.signature
* @param {number=Signature.SIGHASH_ALL} signature.sigtype * @param {number=} signature.sigtype
* @return {PublicKeyHashInput} this, for chaining * @return {PublicKeyHashInput} this, for chaining
*/ */
PublicKeyHashInput.prototype.addSignature = function(transaction, signature) { PublicKeyHashInput.prototype.addSignature = function(transaction, signature) {

View File

@ -19,6 +19,7 @@ var BITS_64_ON = 'ffffffffffffffff';
* Returns a buffer of length 32 bytes with the hash that needs to be signed * Returns a buffer of length 32 bytes with the hash that needs to be signed
* for OP_CHECKSIG. * for OP_CHECKSIG.
* *
* @name Signing.sighash
* @param {Transaction} transaction the transaction to sign * @param {Transaction} transaction the transaction to sign
* @param {number} sighashType the type of the hash * @param {number} sighashType the type of the hash
* @param {number} inputNumber the input index for the signature * @param {number} inputNumber the input index for the signature
@ -90,21 +91,46 @@ var sighash = function sighash(transaction, sighashType, inputNumber, subscript)
return ret; return ret;
}; };
var sign = function sign(transaction, keypair, nhashtype, nin, subscript) { /**
var hashbuf = sighash(transaction, nhashtype, nin, subscript); * Create a signature
var sig = ECDSA.sign(hashbuf, keypair, 'little').set({ *
nhashtype: nhashtype * @name Signing.sign
* @param {Transaction} transaction
* @param {PrivateKey} privateKey
* @param {number} sighash
* @param {number} inputIndex
* @param {Script} subscript
* @return {Signature}
*/
function sign(transaction, privateKey, sighashType, inputIndex, subscript) {
var hashbuf = sighash(transaction, sighashType, inputIndex, subscript);
var sig = ECDSA.sign(hashbuf, privateKey, 'little').set({
nhashtype: sighashType
}); });
return sig; return sig;
}; }
var verify = function verify(transaction, sig, pubkey, nin, subscript) { /**
* Verify a signature
*
* @name Signing.verify
* @param {Transaction} transaction
* @param {Signature} signature
* @param {PublicKey} publicKey
* @param {number} inputIndex
* @param {Script} subscript
* @return {boolean}
*/
function verify(transaction, signature, publicKey, inputIndex, subscript) {
$.checkArgument(transaction); $.checkArgument(transaction);
$.checkArgument(sig && sig.nhashtype); $.checkArgument(signature && signature.nhashtype);
var hashbuf = sighash(transaction, sig.nhashtype, nin, subscript); var hashbuf = sighash(transaction, signature.nhashtype, inputIndex, subscript);
return ECDSA.verify(hashbuf, sig, pubkey, 'little'); return ECDSA.verify(hashbuf, signature, publicKey, 'little');
}; }
/**
* @namespace Signing
*/
module.exports = { module.exports = {
sighash: sighash, sighash: sighash,
sign: sign, sign: sign,

View File

@ -31,6 +31,7 @@ var DEFAULT_SEQNUMBER = 0xFFFFFFFF;
* ownership of tokens * ownership of tokens
* *
* @param {*} serialized * @param {*} serialized
* @constructor
*/ */
function Transaction(serialized) { function Transaction(serialized) {
if (!(this instanceof Transaction)) { if (!(this instanceof Transaction)) {

8
lib/transport/index.js Normal file
View File

@ -0,0 +1,8 @@
/**
* @namespace Transport
*/
module.exports = {
Peer: require('./peer'),
Messages: require('./messages'),
Pool: require('./pool')
};

View File

@ -1,4 +1,7 @@
'use strict'; 'use strict';
/**
* @namespace Transport.Message
*/
/* jshint curly: false */ /* jshint curly: false */
var Buffers = require('buffers'); var Buffers = require('buffers');
@ -19,6 +22,7 @@ var PROTOCOL_VERSION = 70000;
/** /**
* Static helper for consuming a data buffer until the next message. * Static helper for consuming a data buffer until the next message.
* *
* @name Transport.Message#parseMessage
* @param{Network} network - the network object * @param{Network} network - the network object
* @param{Buffer} dataBuffer - the buffer to read from * @param{Buffer} dataBuffer - the buffer to read from
* @returns{Message|undefined} A message or undefined if there is nothing to read. * @returns{Message|undefined} A message or undefined if there is nothing to read.
@ -55,7 +59,8 @@ var parseMessage = function(network, dataBuffer) {
module.exports.parseMessage = parseMessage; module.exports.parseMessage = parseMessage;
/** /**
* Internal function that discards data until founds the next message. * @desc Internal function that discards data until founds the next message.
* @name Transport.Message#discardUntilNextMessage
*/ */
function discardUntilNextMessage(network, dataBuffer) { function discardUntilNextMessage(network, dataBuffer) {
var magicNumber = network.networkMagic; var magicNumber = network.networkMagic;
@ -82,11 +87,20 @@ function discardUntilNextMessage(network, dataBuffer) {
/** /**
* Abstract Message that knows how to parse and serialize itself. * Abstract Message that knows how to parse and serialize itself.
* Concret subclases should implement {fromBuffer} and {getPayload} methods. * Concret subclases should implement {fromBuffer} and {getPayload} methods.
* @name Transport.Message
*/ */
function Message() {} function Message() {}
/**
* @value
* @name Transport.Message.COMMANDS
*/
Message.COMMANDS = {}; Message.COMMANDS = {};
/**
* Look up a message type by command name and instantiate the correct Message
* @name Transport.Message#buildMessage
*/
Message.buildMessage = function(command, payload) { Message.buildMessage = function(command, payload) {
try { try {
var CommandClass = Message.COMMANDS[command]; var CommandClass = Message.COMMANDS[command];
@ -146,6 +160,7 @@ Message.prototype.serialize = function(network) {
/** /**
* Version Message * Version Message
* *
* @name Transport.Message.Version
* @param{string} subversion - version of the client * @param{string} subversion - version of the client
* @param{Buffer} nonce - a random 8 bytes buffer * @param{Buffer} nonce - a random 8 bytes buffer
*/ */
@ -191,6 +206,7 @@ module.exports.Version = Message.COMMANDS.version = Version;
/** /**
* Inv Message * Inv Message
* *
* @name Transport.Message.Inventory
* @param{Array} inventory - reported elements * @param{Array} inventory - reported elements
*/ */
function Inventory(inventory) { function Inventory(inventory) {
@ -229,6 +245,7 @@ module.exports.Inventory = Message.COMMANDS.inv = Inventory;
/** /**
* Getdata Message * Getdata Message
* *
* @name Transport.Message.GetData
* @param{Array} inventory - requested elements * @param{Array} inventory - requested elements
*/ */
function GetData(inventory) { function GetData(inventory) {
@ -242,6 +259,7 @@ module.exports.GetData = GetData;
/** /**
* Ping Message * Ping Message
* *
* @name Transport.Message.Ping
* @param{Buffer} nonce - a random 8 bytes buffer * @param{Buffer} nonce - a random 8 bytes buffer
*/ */
function Ping(nonce) { function Ping(nonce) {
@ -264,6 +282,7 @@ module.exports.Ping = Message.COMMANDS.ping = Ping;
/** /**
* Pong Message * Pong Message
* *
* @name Transport.Message.Pong
* @param{Buffer} nonce - a random 8 bytes buffer * @param{Buffer} nonce - a random 8 bytes buffer
*/ */
function Pong(nonce) { function Pong(nonce) {
@ -277,6 +296,7 @@ module.exports.Pong = Message.COMMANDS.pong = Pong;
/** /**
* Addr Message * Addr Message
* *
* @name Transport.Message.Addressess
* @param{Array} addresses - array of know addresses * @param{Array} addresses - array of know addresses
*/ */
function Addresses(addresses) { function Addresses(addresses) {
@ -342,6 +362,7 @@ module.exports.Addresses = Message.COMMANDS.addr = Addresses;
/** /**
* GetAddr Message * GetAddr Message
* *
* @name Transport.Message.GetAddresses
*/ */
function GetAddresses() { function GetAddresses() {
this.command = 'getaddr'; this.command = 'getaddr';
@ -353,6 +374,7 @@ module.exports.GetAddresses = Message.COMMANDS.getaddr = GetAddresses;
/** /**
* Verack Message * Verack Message
* *
* @name Transport.Message.VerAck
*/ */
function VerAck() { function VerAck() {
this.command = 'verack'; this.command = 'verack';
@ -364,6 +386,7 @@ module.exports.VerAck = Message.COMMANDS.verack = VerAck;
/** /**
* Reject Message * Reject Message
* *
* @name Transport.Message.Reject
*/ */
function Reject() { function Reject() {
this.command = 'reject'; this.command = 'reject';
@ -377,6 +400,7 @@ module.exports.Reject = Message.COMMANDS.reject = Reject;
/** /**
* Alert Message * Alert Message
* *
* @name Transport.Message.Alert
*/ */
function Alert(payload, signature) { function Alert(payload, signature) {
this.command = 'alert'; this.command = 'alert';
@ -408,6 +432,7 @@ module.exports.Alert = Message.COMMANDS.alert = Alert;
/** /**
* Headers Message * Headers Message
* *
* @name Transport.Message.Headers
* @param{Array} blockheaders - array of block headers * @param{Array} blockheaders - array of block headers
*/ */
function Headers(blockheaders) { function Headers(blockheaders) {
@ -446,6 +471,7 @@ module.exports.Headers = Message.COMMANDS.headers = Headers;
/** /**
* Block Message * Block Message
* *
* @name Transport.Message.Block
* @param{Block} block * @param{Block} block
*/ */
function Block(block) { function Block(block) {
@ -468,6 +494,7 @@ module.exports.Block = Message.COMMANDS.block = Block;
/** /**
* Tx Message * Tx Message
* *
* @name Transport.Message.Transaction
* @param{Transaction} transaction * @param{Transaction} transaction
*/ */
function Transaction(transaction) { function Transaction(transaction) {
@ -490,6 +517,7 @@ module.exports.Transaction = Message.COMMANDS.tx = Transaction;
/** /**
* Getblocks Message * Getblocks Message
* *
* @name Transport.Message.GetBlocks
* @param{Array} starts - array of buffers with the starting block hashes * @param{Array} starts - array of buffers with the starting block hashes
* @param{Buffer} [stop] - hash of the last block * @param{Buffer} [stop] - hash of the last block
*/ */
@ -540,6 +568,7 @@ module.exports.GetBlocks = Message.COMMANDS.getblocks = GetBlocks;
/** /**
* Getheaders Message * Getheaders Message
* *
* @name Transport.Message.GetHeaders
* @param{Array} starts - array of buffers with the starting block hashes * @param{Array} starts - array of buffers with the starting block hashes
* @param{Buffer} [stop] - hash of the last block * @param{Buffer} [stop] - hash of the last block
*/ */

View File

@ -22,8 +22,8 @@ var JSUtil = require('./util/js');
* @param {Number} amount - The amount to be represented * @param {Number} amount - The amount to be represented
* @param {String} code - The unit of the amount * @param {String} code - The unit of the amount
* @returns {Unit} A new instance of an Unit * @returns {Unit} A new instance of an Unit
* @constructor
*/ */
function Unit(amount, code) { function Unit(amount, code) {
if (!(this instanceof Unit)) { if (!(this instanceof Unit)) {
return new Unit(amount, code); return new Unit(amount, code);

View File

@ -29,6 +29,7 @@ var JSUtil = require('./util/js');
* @throws {TypeError} Invalid amount * @throws {TypeError} Invalid amount
* @throws {Error} Unknown required argument * @throws {Error} Unknown required argument
* @returns {URI} A new valid and frozen instance of URI * @returns {URI} A new valid and frozen instance of URI
* @constructor
*/ */
var URI = function(data, knownParams) { var URI = function(data, knownParams) {
this.extras = {}; this.extras = {};

View File

@ -1,18 +0,0 @@
/**
* @file util/bitcoin.js
* Contains utilities to handle magnitudes inside of bitcoin
*/
'use strict';
var SATOSHIS_PER_BTC = 1e8;
module.exports = {
/**
* @param number satoshis - amount of satoshis to convert
* @return string an exact representation of such amount, in form of a string
* (avoids duplicate representations in ieee756 of the same number)
*/
satoshisToBitcoin: function(satoshis) {
return satoshis / SATOSHIS_PER_BTC;
}
};

View File

@ -5,6 +5,7 @@ var _ = require('lodash');
/** /**
* Determines whether a string contains only hexadecimal values * Determines whether a string contains only hexadecimal values
* *
* @name JSUtil.isHexa
* @param {string} value * @param {string} value
* @return {boolean} true if the string is the hexa representation of a number * @return {boolean} true if the string is the hexa representation of a number
*/ */
@ -15,6 +16,9 @@ var isHexa = function isHexa(value) {
return /^[0-9a-fA-F]+$/.test(value); return /^[0-9a-fA-F]+$/.test(value);
}; };
/**
* @namespace JSUtil
*/
module.exports = { module.exports = {
/** /**
* Test if an argument is a valid JSON object. If it is, returns a truthy * Test if an argument is a valid JSON object. If it is, returns a truthy

View File

@ -6,7 +6,7 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"lint": "gulp lint", "lint": "gulp lint",
"test": "gulp test-all", "test": "gulp test",
"coverage": "gulp coverage", "coverage": "gulp coverage",
"build": "gulp", "build": "gulp",
"postinstall": "node ./lib/errors/build.js" "postinstall": "node ./lib/errors/build.js"
@ -79,8 +79,11 @@
"elliptic": "=0.15.14", "elliptic": "=0.15.14",
"hash.js": "=0.3.2", "hash.js": "=0.3.2",
"inherits": "=2.0.1", "inherits": "=2.0.1",
"ink-docstrap": "^0.4.12",
"jsdoc": "^3.3.0-alpha11",
"jsrsasign": "=0.0.3", "jsrsasign": "=0.0.3",
"lodash": "=2.4.1", "lodash": "=2.4.1",
"plato": "^1.3.0",
"protobufjs": "=3.0.0", "protobufjs": "=3.0.0",
"sha512": "=0.0.1", "sha512": "=0.0.1",
"socks5-client": "^0.3.6" "socks5-client": "^0.3.6"