comments. refactor how module is exposed.

This commit is contained in:
Christopher Jeffrey 2016-05-14 13:22:43 -07:00
parent 86fbd64598
commit 493f0092e4
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
23 changed files with 293 additions and 101 deletions

View File

@ -27,14 +27,14 @@ $ npm install bcoin
## Documentation
Read the docs here: http://bcoin.ninja/docs/
Read the docs here: http://bcoin.io/docs/
## Example Usage
### High-level usage for Node object
``` js
var bcoin = require('bcoin')('main');
var bcoin = require('bcoin').set('main');
var node = bcoin.fullnode({
prune: false,
@ -136,7 +136,7 @@ $ node bin/bcoin-cli mempool
### Creating a blockchain and mempool
``` js
var bcoin = require('bcoin')('regtest');
var bcoin = require('bcoin').set('regtest');
var chain = new bcoin.chain({ db: 'memory' });
var mempool = new bcoin.mempool({ chain: chain, db: 'memory' });
var miner = new bcoin.miner({ chain: chain, mempool: mempool });
@ -166,7 +166,7 @@ miner.createBlock(function(err, attempt) {
### Connecting to the P2P network
``` js
var bcoin = require('bcoin')('testnet');
var bcoin = require('bcoin').set('testnet');
var chain = new bcoin.chain({ db: 'leveldb' });
var mempool = new bcoin.mempool({ chain: chain, db: 'memory' });
@ -197,7 +197,7 @@ pool.on('tx', function(tx) {
### Doing an SPV sync
``` js
var bcoin = require('bcoin')('testnet');
var bcoin = require('bcoin').set('testnet');
var chain = new bcoin.chain({
db: 'leveldb',

View File

@ -2,7 +2,7 @@
var argv = parseArg(process.argv);
var bcoin = require('../')(argv.network);
var bcoin = require('../').set(argv.network);
var network = bcoin.protocol.network;
var utils = bcoin.utils;
var assert = utils.assert;

View File

@ -1,6 +1,6 @@
#!/usr/bin/env node
var bcoin = require('../')({ debug: true, debugFile: true });
var bcoin = require('../').set({ debug: true, debugFile: true });
var utils = bcoin.utils;
var assert = utils.assert;

View File

@ -1,6 +1,6 @@
#!/usr/bin/env node
var bcoin = require('../')({ debug: true, debugFile: true });
var bcoin = require('../').set({ debug: true, debugFile: true });
var utils = bcoin.utils;
var assert = utils.assert;

View File

@ -1,6 +1,7 @@
/**
* Javascript bitcoin library.
* Javascript bitcoin library. Exposes the global environment.
* @module bcoin
* @see {Environment}
* @license
* Copyright (c) 2014-2015, Fedor Indutny (MIT License).
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
@ -11,22 +12,12 @@ var env = require('./bcoin/env');
var utils = require('./bcoin/utils');
var global = utils.global;
if (utils.isBrowser)
global.bcoin = exports;
/**
* Create a new Environment. Note that this will
* be cached by network. Calling `bcoin('main')`
* twice will return the same environment.
* @param {Object} options - See {@link Environment}.
* @returns {Environment}
/*
* Expose bcoin globally in the
* browser. Necessary for workers.
*/
function BCoin(options) {
env.setDefaults(options);
return BCoin;
}
if (utils.isBrowser)
global.bcoin = env;
utils.merge(BCoin, env);
module.exports = BCoin;
module.exports = env;

View File

@ -20,10 +20,15 @@ var Script = bcoin.script;
* @exports Address
* @constructor
* @param {Object} options
* @param {String?} options.hash
* @param {String?} options.type
* @param {String?} options.version
* @param {String?} options.network
* @param {Buffer|Hash} options.hash - Address hash.
* @param {AddressType} options.type - Address type
* `{witness,}{pubkeyhash,scripthash}`.
* @param {Number} [options.version=-1] - Witness program version.
* @param {(Network|NetworkType)?} options.network - Network name.
* @property {Buffer} hash
* @property {AddressType} type
* @property {Number} version
* @property {NetworkType} network
*/
function Address(options) {
@ -39,12 +44,25 @@ function Address(options) {
this.hash = new Buffer(this.hash, 'hex');
}
/**
* Get the address hash.
* @param {String?} enc - Can be `"hex"` or `null`.
* @returns {Hash|Buffer}
*/
Address.prototype.getHash = function getHash(enc) {
if (enc === 'hex')
return this.hash.toString(enc);
return this.hash;
};
/**
* Compile the address object to a base58 address.
* @param {{NetworkType|Network)?} network
* @returns {Base58Address}
* @throws Error on bad hash/prefix.
*/
Address.prototype.toBase58 = function toBase58(network) {
if (!network)
network = this.network;
@ -147,10 +165,25 @@ Address.parseBase58 = function parseBase58(address) {
};
};
Address.fromBase58 = function fromBase58(addr) {
return new Address(Address.parseBase58(addr));
/**
* Create an address object from a base58 address.
* @param {Base58Address} address
* @returns {Address}
* @throws Parse error.
*/
Address.fromBase58 = function fromBase58(address) {
return new Address(Address.parseBase58(address));
};
/**
* Parse an output script and extract address
* properties. Converts pubkey and multisig
* scripts to pubkeyhash and scripthash addresses.
* @param {Script} script
* @returns {ParsedAddress|null}
*/
Address.parseScript = function parseScript(script) {
var program;
@ -186,6 +219,15 @@ Address.parseScript = function parseScript(script) {
}
};
/**
* Parse input data (witness or input script) and
* attempt extract address properties by "guessing"
* the script type. Only works for pubkeyhash and
* scripthash.
* @param {Array} code
* @returns {ParsedAddress|null}
*/
Address.parseInput = function parseInput(code, witness) {
var hash;
@ -212,14 +254,34 @@ Address.parseInput = function parseInput(code, witness) {
}
};
/**
* Attempt to extract address
* properties from a witness.
* @param {Witness} witness
* @returns {ParsedAddress|null}
*/
Address.parseWitness = function parseWitness(witness) {
return Address.parseInput(witness.items, true);
};
/**
* Attempt to extract address
* properties from an input script.
* @param {Witness} witness
* @returns {ParsedAddress|null}
*/
Address.parseInputScript = function parseInputScript(script) {
return Address.parseInput(script.code, false);
};
/**
* Create an Address from a witness.
* @param {Witness}
* @returns {ParsedAddress|null}
*/
Address.fromWitness = function fromWitness(witness) {
var data = Address.parseWitness(witness);
@ -229,6 +291,12 @@ Address.fromWitness = function fromWitness(witness) {
return new Address(data);
};
/**
* Create an Address from an input script.
* @param {Script}
* @returns {ParsedAddress|null}
*/
Address.fromInputScript = function fromInputScript(script) {
var data = Address.parseInputScript(script);
@ -238,6 +306,12 @@ Address.fromInputScript = function fromInputScript(script) {
return new Address(data);
};
/**
* Create an Address from an output script.
* @param {Script}
* @returns {ParsedAddress|null}
*/
Address.fromScript = function fromScript(script) {
var data = Address.parseScript(script);
@ -247,7 +321,18 @@ Address.fromScript = function fromScript(script) {
return new Address(data);
};
/**
* Create a naked address from hash/type/version.
* @param {Buffer|Hash} hash
* @param {AddressType} type
* @param {Number} [version=-1]
* @returns {ParsedAddress}
*/
Address.parseHash = function parseHash(hash, type, version) {
if (!Buffer.isBuffer(hash))
hash = new Buffer(hash, 'hex');
return {
hash: hash,
type: type || 'pubkeyhash',
@ -255,6 +340,14 @@ Address.parseHash = function parseHash(hash, type, version) {
};
};
/**
* Create an Address from hash/type/version.
* @param {Buffer|Hash} hash
* @param {AddressType} type
* @param {Number} [version=-1]
* @returns {Address}
*/
Address.fromHash = function fromHash(hash, type, version) {
return new Address(Address.parseHash(hash, type, version));
};
@ -264,7 +357,7 @@ Address.fromHash = function fromHash(hash, type, version) {
* @param {Hash|Buffer} hash
* @param {AddressType?} type
* @param {Number?} version - Witness program version.
* @returns {Base58Address}
* @returns {ParsedAddress}
*/
Address.parseData = function parseData(data, type, version) {
@ -272,13 +365,27 @@ Address.parseData = function parseData(data, type, version) {
data = utils.sha256(data);
else
data = utils.ripesha(data);
return Address.parseHash(data, type, version);
};
/**
* Create an Address from data/type/version.
* @param {Buffer} data - Data to be hashed.
* @param {AddressType} type
* @param {Number} [version=-1]
* @returns {Address}
*/
Address.fromData = function fromData(data, type, version) {
return new Address(Address.parseData(data, type, version));
};
/**
* Convert the address to an output script.
* @returns {Script}
*/
Address.toScript = function toScript() {
if (this.type === 'pubkeyhash')
return Script.createPubkeyhash(this.hash);
@ -291,7 +398,7 @@ Address.toScript = function toScript() {
/**
* Validate an address, optionally test against a type.
* @param {String} address - Can be of any type in reality.
* @param {Base58Address} address
* @param {AddressType}
* @returns {Boolean}
*/
@ -315,6 +422,13 @@ Address.validate = function validate(address, type) {
return true;
};
/**
* Get the hex hash of a base58
* address or address object.
* @param {Base58Address|Address} data
* @returns {Hash|null}
*/
Address.getHash = function getHash(data) {
var hash;
@ -331,17 +445,27 @@ Address.getHash = function getHash(data) {
return hash.toString('hex');
};
// Address.prototype.toString = function toString() {
// return this.toBase58();
// };
/**
* Convert the Address to a string.
* @returns {Base58String}
*/
Address.prototype.toString = function toString() {
assert(false, 'Cannot toString an address.');
return this.toBase58();
};
/**
* Inspect the Address.
* @returns {Object}
*/
Address.prototype.inspect = function inspect() {
return {
hash: this.getHash('hex'),
type: this.type,
version: this.version,
address: this.toBase58()
};
return '<Address:'
+ ' t=' + this.type
+ ' v=' + this.version
+ ' b58=' + this.toBase58()
+ '>';
};
module.exports = Address;

View File

@ -16,18 +16,20 @@ try {
}
/**
* A BCoin "environment" which is tied to the
* network type among other options. It exposes all
* constructors for primitives, the blockchain,
* mempool, wallet, etc. BCoin is _not_ usable
* without an environment.
* A BCoin "environment" which is used for
* bootstrapping the initial `bcoin` module.
* It exposes all constructors for primitives,
* the blockchain, mempool, wallet, etc. It
* also sets the default network if there is
* one. It exposes a global {@link TimeData}
* object for adjusted time, as well as a
* global worker pool.
*
* @exports Environment
* @constructor
*
* @param {Object|String} options - Options object or network type.
* @param {String?} options.network - One of `main`, `testnet`,
* `regtest`, `segnet3`, `segnet4`.
* @param {(Object|NetworkType)?} options - Options object or network type.
* @param {(Network|NetworkType)?} options.network
* @param {String?} options.prefix - Prefix for filesystem (default=~/.bcoin).
* @param {String?} options.db - Database backend (default=leveldb).
* @param {Boolean?} options.debug - Whether to display debug output.
@ -39,7 +41,7 @@ try {
* the worker pool (default=6).
*
* @property {Boolean} isBrowser
* @property {String} networkType
* @property {NetworkType} networkType
*
* @property {Function} bn - Big number constructor
* (see {@link https://github.com/indutny/bn.js} for docs).
@ -109,9 +111,6 @@ try {
*/
function Environment(options) {
// if (!(this instanceof Environment))
// return new Environment(options);
if (!options)
options = {};
@ -125,6 +124,7 @@ function Environment(options) {
this.isBrowser = utils.isBrowser;
this.env = Environment;
this.bn = require('bn.js');
this.utils = require('./utils');
this.locker = require('./locker');
@ -195,10 +195,10 @@ function Environment(options) {
this.time = new this.timedata();
this.setDefaults(options);
this.set(options);
}
Environment.prototype.setDefaults = function setDefaults(options) {
Environment.prototype.set = function set(options) {
if (typeof options === 'string')
options = { network: options };
@ -262,6 +262,8 @@ Environment.prototype.setDefaults = function setDefaults(options) {
network: this.network.get(this.network.primary)
});
}
return this;
};
/**
@ -331,5 +333,12 @@ Environment.prototype.now = function now() {
return this.time.now();
};
/*
* Expose by converting `exports` to an
* Environment. This will later also be
* injected into the BCoin object.
*/
utils.merge(exports, Environment.prototype);
Environment.call(exports);

View File

@ -10,21 +10,13 @@ var assert = utils.assert;
var network = require('./protocol/network');
/**
* Represents a key ring which amounts to an address. Used for {@link Wallet}.
* @exports Address
* Represents a network.
* @exports Network
* @constructor
* @param {Object} options
* @param {String?} options.label
* @param {Boolean?} options.derived
* @param {HDPrivateKey|HDPublicKey} options.key
* @param {String?} options.path
* @param {Boolean?} options.change
* @param {Number?} options.index
* @param {String?} options.type - `"pubkeyhash"` or `"multisig"`.
* @param {Buffer[]} options.keys - Shared multisig keys.
* @param {Number?} options.m - Multisig `m` value.
* @param {Number?} options.n - Multisig `n` value.
* @param {Boolean?} options.witness - Whether witness programs are enabled.
* @param {Object|String} options - See {@link module:network}.
* @property {Number} height
* @property {Number} feeRate
* @property {Number} minRelay
*/
function Network(options) {
@ -56,12 +48,16 @@ function Network(options) {
Network.primary = this.type;
}
/**
* Default network.
* @type {String}
*/
Network.primary = null;
/**
* Test an object to see if it is an Address.
* @param {Object} obj
* @returns {Boolean}
* Update the height of the network.
* @param {Number} height
*/
Network.prototype.updateHeight = function updateHeight(height) {
@ -69,18 +65,29 @@ Network.prototype.updateHeight = function updateHeight(height) {
};
/**
* Return address ID (pubkeyhash address of pubkey).
* @returns {Base58Address}
* Update the estimated fee rate of the network.
* @param {Number} rate
*/
Network.prototype.updateRate = function updateRate(rate) {
this.feeRate = rate;
};
/**
* Update the minimum relay rate (reject rate) of the network.
* @param {Number} rate
*/
Network.prototype.updateMinRelay = function updateMinRelay(rate) {
this.minRelay = rate;
};
/**
* Calculate the minimum relay rate. If the network is
* inactive (height=-1), return the default minimum relay.
* @return {Number} Rate
*/
Network.prototype.getMinRelay = function getMinRelay() {
if (this.height === -1)
return this.minRate;
@ -88,6 +95,12 @@ Network.prototype.getMinRelay = function getMinRelay() {
return Math.min(this.minRelay, this.maxRate);
};
/**
* Calculate the normal relay rate. If the network is
* inactive (height=-1), return the default rate.
* @return {Number} Rate
*/
Network.prototype.getRate = function getRate() {
if (this.height === -1)
return this.maxRate;
@ -96,9 +109,11 @@ Network.prototype.getRate = function getRate() {
};
/**
* Test an object to see if it is an Address.
* @param {Object} obj
* @returns {Boolean}
* Set the default network. This network will be used
* if nothing is passed as the `network` option for
* certain objects.
* @param {String} type - Network type.
* @returns {Network}
*/
Network.set = function set(type) {
@ -107,6 +122,12 @@ Network.set = function set(type) {
return Network(network[type]);
};
/**
* Get a network with a string or a Network object.
* @param {String|Network} options - Network type.
* @returns {Network}
*/
Network.get = function get(options) {
if (!options) {
assert(Network.primary, 'No default network.');
@ -122,6 +143,20 @@ Network.get = function get(options) {
assert(false, 'Unknown network.');
};
/**
* Convert the network to a string.
* @returns {String}
*/
Network.prototype.toString = function toString() {
return this.type;
};
/**
* Inspect the network.
* @returns {String}
*/
Network.prototype.inspect = function inspect() {
return '<Network: ' + this.type + '>';
};

View File

@ -72,7 +72,7 @@ BufferReader.prototype.end = function end() {
*/
BufferReader.prototype.endData = function endData() {
var start, end, size, data;
var ret, start, end, size, data;
assert(this.stack.length > 0);
@ -90,7 +90,10 @@ BufferReader.prototype.endData = function endData() {
if (this.zeroCopy)
return data.slice(start, end);
return utils.slice(data, start, end);
ret = new Buffer(size);
data.copy(ret, 0, start, end);
return ret;
};
/**
@ -393,10 +396,12 @@ BufferReader.prototype.readBytes = function readBytes(size) {
assert(size >= 0);
assert(this.offset + size <= this.data.length);
if (this.zeroCopy)
if (this.zeroCopy) {
ret = this.data.slice(this.offset, this.offset + size);
else
ret = utils.slice(this.data, this.offset, this.offset + size);
} else {
ret = new Buffer(size);
this.data.copy(ret, 0, this.offset, this.offset + size);
}
this.offset += size;

View File

@ -58,12 +58,19 @@ function Witness(items, mutable) {
/**
* Inspect a Witness object.
* @method
* @returns {String} Human-readable script.
*/
Witness.prototype.toString =
Witness.prototype.inspect = function inspect() {
return '<Witness: ' + this.toString() + '>';
};
/**
* Convert a Witness object to a String.
* @returns {String} Human-readable script.
*/
Witness.prototype.toString = function toString() {
return Witness.format(this.items);
};
@ -353,12 +360,19 @@ function Stack(items) {
/**
* Inspect the stack.
* @method
* @returns {String} Human-readable stack.
*/
Stack.prototype.toString =
Stack.prototype.inspect = function inspect() {
return '<Stack: ' + this.toString() + '>';
};
/**
* Convert the stack to a string.
* @returns {String} Human-readable stack.
*/
Stack.prototype.toString = function toString() {
return Witness.format(this.items);
};
@ -890,12 +904,19 @@ Script.prototype.clone = function clone(mutable) {
/**
* Inspect the script.
* @method
* @returns {String} Human-readable script code.
*/
Script.prototype.toString =
Script.prototype.inspect = function inspect() {
return '<Script: ' + this.toString() + '>';
};
/**
* Convert the script to a bitcoind test string.
* @returns {String} Human-readable script code.
*/
Script.prototype.toString = function toString() {
return Script.format(this.code);
};

View File

@ -367,6 +367,13 @@
* @global
*/
/**
* One of `main`, `testnet`, `regtest`, `segnet3`, `segnet4`.
* @typedef {String} NetworkType
* @see {module:network.types}
* @global
*/
/*
* Callbacks & Events
*/

View File

@ -1,4 +1,4 @@
var bcoin = require('bcoin')();
var bcoin = require('bcoin');
var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network;
var utils = bcoin.utils;

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
describe('Block', function() {

View File

@ -1,4 +1,4 @@
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
describe('Bloom', function() {

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('regtest');
var bcoin = require('../').set('regtest');
var constants = bcoin.protocol.constants;
var utils = bcoin.utils;
var assert = require('assert');

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var utils = bcoin.utils;
var assert = require('assert');

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var constants = bcoin.protocol.constants;
var utils = bcoin.utils;
var assert = require('assert');

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var utils = bcoin.utils;
var assert = require('assert');
var mnemonic1 = require('./data/mnemonic1').english;

View File

@ -1,4 +1,4 @@
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
var constants = bcoin.protocol.constants;
var network = bcoin.network.get();

View File

@ -1,4 +1,4 @@
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
var Script = bcoin.script;
var Stack = bcoin.stack;

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
var utils = bcoin.utils;
var constants = bcoin.protocol.constants;

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var assert = require('assert');
var utils = bcoin.utils;

View File

@ -1,5 +1,5 @@
var bn = require('bn.js');
var bcoin = require('../')('main');
var bcoin = require('../').set('main');
var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network;
var utils = bcoin.utils;