http: refactor deps and tests.

This commit is contained in:
Christopher Jeffrey 2016-10-01 22:04:50 -07:00
parent 24b92a2b58
commit f96ee525f5
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
3 changed files with 163 additions and 167 deletions

View File

@ -6,14 +6,30 @@
'use strict'; 'use strict';
var bcoin = require('../env');
var utils = require('../utils/utils'); var utils = require('../utils/utils');
var spawn = require('../utils/spawn'); var spawn = require('../utils/spawn');
var co = spawn.co; var co = spawn.co;
var crypto = require('../crypto/crypto'); var crypto = require('../crypto/crypto');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.constants; var constants = require('../protocol/constants');
var ec = require('../crypto/ec');
var time = require('../net/timedata');
var NetworkAddress = require('../primitives/netaddress'); var NetworkAddress = require('../primitives/netaddress');
var Script = require('../script/script');
var Address = require('../primitives/address');
var Block = require('../primitives/block');
var Coin = require('../primitives/coin');
var Headers = require('../primitives/headers');
var Input = require('../primitives/input');
var KeyRing = require('../primitives/keyring');
var Locker = require('../utils/locker');
var MerkleBlock = require('../primitives/merkleblock');
var MTX = require('../primitives/mtx');
var Network = require('../protocol/network');
var Outpoint = require('../primitives/outpoint');
var Output = require('../primitives/output');
var BufferReader = require('../utils/reader');
var TX = require('../primitives/tx');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var fs; var fs;
@ -40,7 +56,7 @@ function RPC(node) {
this.walletdb = node.walletdb; this.walletdb = node.walletdb;
this.logger = node.logger; this.logger = node.logger;
this.locker = new bcoin.locker(); this.locker = new Locker();
this.feeRate = null; this.feeRate = null;
this.mining = false; this.mining = false;
@ -308,11 +324,11 @@ RPC.prototype.getinfo = co(function* getinfo(args) {
walletversion: 0, walletversion: 0,
balance: +utils.btc(balance.total), balance: +utils.btc(balance.total),
blocks: this.chain.height, blocks: this.chain.height,
timeoffset: bcoin.time.offset, timeoffset: time.offset,
connections: this.pool.peers.all.length, connections: this.pool.peers.all.length,
proxy: '', proxy: '',
difficulty: this._getDifficulty(), difficulty: this._getDifficulty(),
testnet: this.network.type !== bcoin.network.main, testnet: this.network.type !== Network.main,
keypoololdest: 0, keypoololdest: 0,
keypoolsize: 0, keypoolsize: 0,
unlocked_until: this.wallet.master.until, unlocked_until: this.wallet.master.until,
@ -360,7 +376,7 @@ RPC.prototype.getnetworkinfo = function getnetworkinfo(args) {
subversion: constants.USER_AGENT, subversion: constants.USER_AGENT,
protocolversion: constants.VERSION, protocolversion: constants.VERSION,
localservices: this.pool.services, localservices: this.pool.services,
timeoffset: bcoin.time.offset, timeoffset: Time.offset,
connections: this.pool.peers.all.length, connections: this.pool.peers.all.length,
networks: [], networks: [],
relayfee: +utils.btc(this.network.getMinRelay()), relayfee: +utils.btc(this.network.getMinRelay()),
@ -809,7 +825,7 @@ RPC.prototype._scriptToJSON = function scriptToJSON(script, hex) {
out.hex = script.toJSON(); out.hex = script.toJSON();
type = script.getType(); type = script.getType();
out.type = bcoin.script.typesByVal[type]; out.type = Script.typesByVal[type];
out.reqSigs = script.isMultisig() ? script.getSmall(0) : 1; out.reqSigs = script.isMultisig() ? script.getSmall(0) : 1;
@ -1249,7 +1265,7 @@ RPC.prototype.gettxoutproof = co(function* gettxoutproof(args) {
throw new RPCError('Block does not contain all txids.'); throw new RPCError('Block does not contain all txids.');
} }
block = bcoin.merkleblock.fromHashes(block, txids); block = MerkleBlock.fromHashes(block, txids);
return block.toRaw().toString('hex'); return block.toRaw().toString('hex');
}); });
@ -1261,7 +1277,7 @@ RPC.prototype.verifytxoutproof = co(function* verifytxoutproof(args) {
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
throw new RPCError('verifytxoutproof "proof"'); throw new RPCError('verifytxoutproof "proof"');
block = bcoin.merkleblock.fromRaw(toString(args[0]), 'hex'); block = MerkleBlock.fromRaw(toString(args[0]), 'hex');
if (!block.verify()) if (!block.verify())
return res; return res;
@ -1328,7 +1344,7 @@ RPC.prototype._submitwork = co(function* _submitwork(data) {
reverseEndian(data); reverseEndian(data);
header = bcoin.headers.fromAbbr(data); header = Headers.fromAbbr(data);
block = attempt.block; block = attempt.block;
if (header.prevBlock !== block.prevBlock if (header.prevBlock !== block.prevBlock
@ -1445,7 +1461,7 @@ RPC.prototype.submitblock = co(function* submitblock(args) {
throw new RPCError('submitblock "hexdata" ( "jsonparametersobject" )'); throw new RPCError('submitblock "hexdata" ( "jsonparametersobject" )');
} }
block = bcoin.block.fromRaw(toString(args[0]), 'hex'); block = Block.fromRaw(toString(args[0]), 'hex');
return yield this._submitblock(block); return yield this._submitblock(block);
}); });
@ -1490,7 +1506,7 @@ RPC.prototype.getblocktemplate = co(function* getblocktemplate(args) {
if (!utils.isHex(opt.data)) if (!utils.isHex(opt.data))
throw new RPCError('Invalid parameter.'); throw new RPCError('Invalid parameter.');
block = bcoin.block.fromRaw(opt.data, 'hex'); block = Block.fromRaw(opt.data, 'hex');
return yield this._submitblock(block); return yield this._submitblock(block);
} }
@ -1626,7 +1642,7 @@ RPC.prototype._tmpl = co(function* _tmpl(version, coinbase, rules) {
target: utils.revHex(attempt.target.toString('hex')), target: utils.revHex(attempt.target.toString('hex')),
submitold: false, submitold: false,
mintime: block.ts, mintime: block.ts,
maxtime: bcoin.now() + 2 * 60 * 60, maxtime: time.now() + 2 * 60 * 60,
mutable: mutable, mutable: mutable,
noncerange: '00000000ffffffff', noncerange: '00000000ffffffff',
sigoplimit: attempt.witness sigoplimit: attempt.witness
@ -1794,7 +1810,7 @@ RPC.prototype.getmininginfo = co(function* getmininginfo(args) {
genproclimit: this.proclimit, genproclimit: this.proclimit,
networkhashps: hashps, networkhashps: hashps,
pooledtx: this._totalTX(), pooledtx: this._totalTX(),
testnet: this.network !== bcoin.network.main, testnet: this.network !== Network.main,
chain: 'main', chain: 'main',
generate: this.mining generate: this.mining
}; };
@ -1958,7 +1974,7 @@ RPC.prototype.generatetoaddress = co(function* generatetoaddress(args) {
numblocks = toNumber(args[0], 1); numblocks = toNumber(args[0], 1);
address = this.miner.address; address = this.miner.address;
this.miner.address = bcoin.address.fromBase58(toString(args[1])); this.miner.address = Address.fromBase58(toString(args[1]));
hashes = yield this._generate(numblocks); hashes = yield this._generate(numblocks);
@ -1990,7 +2006,7 @@ RPC.prototype.createrawtransaction = function createrawtransaction(args) {
if (!inputs || !sendTo) if (!inputs || !sendTo)
return Promise.reject(new RPCError('Invalid parameter')); return Promise.reject(new RPCError('Invalid parameter'));
tx = bcoin.tx(); tx = new TX();
if (args.length > 2 && args[2] != null) { if (args.length > 2 && args[2] != null) {
locktime = toNumber(args[2]); locktime = toNumber(args[2]);
@ -2024,7 +2040,7 @@ RPC.prototype.createrawtransaction = function createrawtransaction(args) {
return Promise.reject(new RPCError('Invalid parameter')); return Promise.reject(new RPCError('Invalid parameter'));
} }
input = new bcoin.input({ input = new Input({
prevout: { prevout: {
hash: utils.revHex(hash), hash: utils.revHex(hash),
index: index index: index
@ -2044,15 +2060,15 @@ RPC.prototype.createrawtransaction = function createrawtransaction(args) {
if (key === 'data') { if (key === 'data') {
value = new Buffer(value, 'hex'); value = new Buffer(value, 'hex');
output = new bcoin.output({ output = new Output({
value: 0, value: 0,
script: bcoin.script.fromNulldata(value) script: Script.fromNulldata(value)
}); });
tx.outputs.push(output); tx.outputs.push(output);
continue; continue;
} }
address = bcoin.address.fromBase58(key); address = Address.fromBase58(key);
b58 = address.toBase58(this.network); b58 = address.toBase58(this.network);
if (addrs[b58]) if (addrs[b58])
@ -2060,7 +2076,7 @@ RPC.prototype.createrawtransaction = function createrawtransaction(args) {
addrs[b58] = true; addrs[b58] = true;
output = new bcoin.output({ output = new Output({
value: toSatoshi(value), value: toSatoshi(value),
address: address address: address
}); });
@ -2077,7 +2093,7 @@ RPC.prototype.decoderawtransaction = function decoderawtransaction(args) {
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
return Promise.reject(new RPCError('decoderawtransaction "hexstring"')); return Promise.reject(new RPCError('decoderawtransaction "hexstring"'));
tx = bcoin.tx.fromRaw(toString(args[0]), 'hex'); tx = TX.fromRaw(toString(args[0]), 'hex');
return Promise.resolve(this._txToJSON(tx)); return Promise.resolve(this._txToJSON(tx));
}; };
@ -2089,13 +2105,13 @@ RPC.prototype.decodescript = function decodescript(args) {
return Promise.reject(new RPCError('decodescript "hex"')); return Promise.reject(new RPCError('decodescript "hex"'));
data = toString(args[0]); data = toString(args[0]);
script = new bcoin.script(); script = new Script();
if (data.length > 0) if (data.length > 0)
script.fromRaw(new Buffer(data, 'hex')); script.fromRaw(new Buffer(data, 'hex'));
hash = crypto.hash160(script.toRaw()); hash = crypto.hash160(script.toRaw());
address = bcoin.address.fromHash(hash, bcoin.script.types.SCRIPTHASH); address = Address.fromHash(hash, Script.types.SCRIPTHASH);
script = this._scriptToJSON(script); script = this._scriptToJSON(script);
script.p2sh = address.toBase58(this.network); script.p2sh = address.toBase58(this.network);
@ -2144,7 +2160,7 @@ RPC.prototype.sendrawtransaction = function sendrawtransaction(args) {
if (!utils.isHex(args[0])) if (!utils.isHex(args[0]))
return Promise.reject(new RPCError('Invalid parameter')); return Promise.reject(new RPCError('Invalid parameter'));
tx = bcoin.tx.fromRaw(args[0], 'hex'); tx = TX.fromRaw(args[0], 'hex');
this.node.sendTX(tx); this.node.sendTX(tx);
@ -2166,11 +2182,11 @@ RPC.prototype.signrawtransaction = co(function* signrawtransaction(args) {
throw new RPCError('Invalid parameter'); throw new RPCError('Invalid parameter');
raw = new Buffer(args[0], 'hex'); raw = new Buffer(args[0], 'hex');
p = new bcoin.reader(raw); p = new BufferReader(raw);
txs = []; txs = [];
while (p.left()) while (p.left())
txs.push(bcoin.mtx.fromRaw(p)); txs.push(MTX.fromRaw(p));
merged = txs[0]; merged = txs[0];
@ -2204,7 +2220,7 @@ RPC.prototype._signrawtransaction = co(function* signrawtransaction(merged, txs,
if (!utils.isBase58(secret)) if (!utils.isBase58(secret))
throw new RPCError('Invalid parameter'); throw new RPCError('Invalid parameter');
key = bcoin.keyring.fromSecret(secret); key = KeyRing.fromSecret(secret);
keyMap[key.getPublicKey('hex')] = key; keyMap[key.getPublicKey('hex')] = key;
keys.push(key); keys.push(key);
} }
@ -2232,8 +2248,8 @@ RPC.prototype._signrawtransaction = co(function* signrawtransaction(merged, txs,
throw new RPCError('Invalid parameter'); throw new RPCError('Invalid parameter');
} }
script = bcoin.script.fromRaw(script, 'hex'); script = Script.fromRaw(script, 'hex');
coins.push(new bcoin.coin({ coins.push(new Coin({
hash: utils.revHex(hash), hash: utils.revHex(hash),
index: index, index: index,
script: script, script: script,
@ -2246,7 +2262,7 @@ RPC.prototype._signrawtransaction = co(function* signrawtransaction(merged, txs,
continue; continue;
if (script.isScripthash() || script.isWitnessScripthash()) { if (script.isScripthash() || script.isWitnessScripthash()) {
redeem = bcoin.script.fromRaw(prev.redeemScript, 'hex'); redeem = Script.fromRaw(prev.redeemScript, 'hex');
for (j = 0; j < redeem.length; j++) { for (j = 0; j < redeem.length; j++) {
op = redeem.get(j); op = redeem.get(j);
@ -2302,7 +2318,7 @@ RPC.prototype.fundrawtransaction = co(function* fundrawtransaction(args) {
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
throw new RPCError('fundrawtransaction "hexstring" ( options )'); throw new RPCError('fundrawtransaction "hexstring" ( options )');
tx = bcoin.mtx.fromRaw(toString(args[0]), 'hex'); tx = MTX.fromRaw(toString(args[0]), 'hex');
if (tx.outputs.length === 0) if (tx.outputs.length === 0)
throw new RPCError('TX must have at least one output.'); throw new RPCError('TX must have at least one output.');
@ -2312,7 +2328,7 @@ RPC.prototype.fundrawtransaction = co(function* fundrawtransaction(args) {
changeAddress = toString(options.changeAddress); changeAddress = toString(options.changeAddress);
if (changeAddress) if (changeAddress)
changeAddress = bcoin.address.fromBase58(changeAddress); changeAddress = Address.fromBase58(changeAddress);
feeRate = options.feeRate; feeRate = options.feeRate;
@ -2359,7 +2375,7 @@ RPC.prototype._createRedeem = co(function* _createRedeem(args) {
continue; continue;
} }
hash = bcoin.address.getHash(key, 'hex'); hash = Address.getHash(key, 'hex');
if (!hash) if (!hash)
throw new RPCError('Invalid key.'); throw new RPCError('Invalid key.');
@ -2373,7 +2389,7 @@ RPC.prototype._createRedeem = co(function* _createRedeem(args) {
} }
try { try {
script = bcoin.script.fromMultisig(m, n, keys); script = Script.fromMultisig(m, n, keys);
} catch (e) { } catch (e) {
throw new RPCError('Invalid parameters.'); throw new RPCError('Invalid parameters.');
} }
@ -2407,16 +2423,16 @@ RPC.prototype._scriptForWitness = function scriptForWitness(script) {
if (script.isPubkey()) { if (script.isPubkey()) {
hash = crypto.hash160(script.get(0)); hash = crypto.hash160(script.get(0));
return bcoin.script.fromProgram(0, hash); return Script.fromProgram(0, hash);
} }
if (script.isPubkeyhash()) { if (script.isPubkeyhash()) {
hash = script.get(2); hash = script.get(2);
return bcoin.script.fromProgram(0, hash); return Script.fromProgram(0, hash);
} }
hash = script.sha256(); hash = script.sha256();
return bcoin.script.fromProgram(0, hash); return Script.fromProgram(0, hash);
}; };
RPC.prototype.createwitnessaddress = function createwitnessaddress(args) { RPC.prototype.createwitnessaddress = function createwitnessaddress(args) {
@ -2426,7 +2442,7 @@ RPC.prototype.createwitnessaddress = function createwitnessaddress(args) {
return Promise.reject(new RPCError('createwitnessaddress "script"')); return Promise.reject(new RPCError('createwitnessaddress "script"'));
raw = toString(args[1]); raw = toString(args[1]);
script = bcoin.script.fromRaw(raw, 'hex'); script = Script.fromRaw(raw, 'hex');
program = this._scriptForWitness(script); program = this._scriptForWitness(script);
return Promise.resolve({ return Promise.resolve({
@ -2444,7 +2460,7 @@ RPC.prototype.validateaddress = co(function* validateaddress(args) {
b58 = toString(args[0]); b58 = toString(args[0]);
try { try {
address = bcoin.address.fromBase58(b58); address = Address.fromBase58(b58);
} catch (e) { } catch (e) {
return { return {
isvalid: false isvalid: false
@ -2484,7 +2500,7 @@ RPC.prototype.verifymessage = function verifymessage(args) {
sig = toString(args[1]); sig = toString(args[1]);
msg = toString(args[2]); msg = toString(args[2]);
address = bcoin.address.getHash(address); address = Address.getHash(address);
if (!address) if (!address)
return Promise.reject(new RPCError('Invalid address.')); return Promise.reject(new RPCError('Invalid address.'));
@ -2493,7 +2509,7 @@ RPC.prototype.verifymessage = function verifymessage(args) {
msg = new Buffer(RPC.magic + msg, 'utf8'); msg = new Buffer(RPC.magic + msg, 'utf8');
msg = crypto.hash256(msg); msg = crypto.hash256(msg);
key = bcoin.ec.recover(msg, sig, 0, true); key = ec.recover(msg, sig, 0, true);
if (!key) if (!key)
return Promise.resolve(false); return Promise.resolve(false);
@ -2514,7 +2530,7 @@ RPC.prototype.signmessagewithprivkey = function signmessagewithprivkey(args) {
key = toString(args[0]); key = toString(args[0]);
msg = toString(args[1]); msg = toString(args[1]);
key = bcoin.keyring.fromSecret(key); key = KeyRing.fromSecret(key);
msg = new Buffer(RPC.magic + msg, 'utf8'); msg = new Buffer(RPC.magic + msg, 'utf8');
msg = crypto.hash256(msg); msg = crypto.hash256(msg);
@ -2658,8 +2674,8 @@ RPC.prototype.setmocktime = function setmocktime(args) {
if (time < 0) if (time < 0)
return Promise.reject(new RPCError('Invalid parameter.')); return Promise.reject(new RPCError('Invalid parameter.'));
delta = bcoin.now() - time; delta = time.now() - time;
bcoin.time.offset = -delta; time.offset = -delta;
return Promise.resolve(null); return Promise.resolve(null);
}; };
@ -2719,7 +2735,7 @@ RPC.prototype.dumpprivkey = co(function* dumpprivkey(args) {
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
throw new RPCError('dumpprivkey "bitcoinaddress"'); throw new RPCError('dumpprivkey "bitcoinaddress"');
hash = bcoin.address.getHash(toString(args[0]), 'hex'); hash = Address.getHash(toString(args[0]), 'hex');
if (!hash) if (!hash)
throw new RPCError('Invalid address.'); throw new RPCError('Invalid address.');
@ -2837,7 +2853,7 @@ RPC.prototype.getaccount = co(function* getaccount(args) {
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
throw new RPCError('getaccount "bitcoinaddress"'); throw new RPCError('getaccount "bitcoinaddress"');
hash = bcoin.address.getHash(args[0], 'hex'); hash = Address.getHash(args[0], 'hex');
if (!hash) if (!hash)
throw new RPCError('Invalid address.'); throw new RPCError('Invalid address.');
@ -2991,7 +3007,7 @@ RPC.prototype.getreceivedbyaddress = co(function* getreceivedbyaddress(args) {
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
throw new RPCError('getreceivedbyaddress "bitcoinaddress" ( minconf )'); throw new RPCError('getreceivedbyaddress "bitcoinaddress" ( minconf )');
hash = bcoin.address.getHash(toString(args[0]), 'hex'); hash = Address.getHash(toString(args[0]), 'hex');
if (!hash) if (!hash)
throw new RPCError('Invalid address'); throw new RPCError('Invalid address');
@ -3186,7 +3202,7 @@ RPC.prototype.importprivkey = co(function* importprivkey(args) {
if (rescan && this.chain.db.options.prune) if (rescan && this.chain.db.options.prune)
throw new RPCError('Cannot rescan when pruned.'); throw new RPCError('Cannot rescan when pruned.');
key = bcoin.keyring.fromSecret(secret); key = KeyRing.fromSecret(secret);
yield this.wallet.importKey(0, key, null); yield this.wallet.importKey(0, key, null);
@ -3230,7 +3246,7 @@ RPC.prototype.importwallet = co(function* importwallet(args) {
if (parts.length < 4) if (parts.length < 4)
throw new RPCError('Malformed wallet.'); throw new RPCError('Malformed wallet.');
secret = bcoin.keyring.fromSecret(parts[0]); secret = KeyRing.fromSecret(parts[0]);
time = +parts[1]; time = +parts[1];
label = parts[2]; label = parts[2];
@ -3280,7 +3296,7 @@ RPC.prototype.importpubkey = co(function* importpubkey(args) {
pubkey = new Buffer(pubkey, 'hex'); pubkey = new Buffer(pubkey, 'hex');
key = bcoin.keyring.fromPublic(pubkey, this.network); key = KeyRing.fromPublic(pubkey, this.network);
yield this.wallet.importKey(0, key, null); yield this.wallet.importKey(0, key, null);
@ -3661,7 +3677,7 @@ RPC.prototype.listunspent = co(function* listunspent(args) {
addresses = {}; addresses = {};
for (i = 0; i < addrs.length; i++) { for (i = 0; i < addrs.length; i++) {
address = toString(addrs[i]); address = toString(addrs[i]);
hash = bcoin.address.getHash(address, 'hex'); hash = Address.getHash(address, 'hex');
if (!hash) if (!hash)
throw new RPCError('Invalid address.'); throw new RPCError('Invalid address.');
@ -3745,7 +3761,7 @@ RPC.prototype.lockunspent = function lockunspent(args) {
if (!output || typeof output !== 'object') if (!output || typeof output !== 'object')
return Promise.reject(new RPCError('Invalid paremeter.')); return Promise.reject(new RPCError('Invalid paremeter.'));
outpoint = new bcoin.outpoint(); outpoint = new Outpoint();
outpoint.hash = toHash(output.txid); outpoint.hash = toHash(output.txid);
outpoint.index = toNumber(output.vout); outpoint.index = toNumber(output.vout);
@ -3797,7 +3813,7 @@ RPC.prototype.sendfrom = function sendfrom(args) {
} }
account = toString(args[0]); account = toString(args[0]);
address = bcoin.address.fromBase58(toString(args[1])); address = Address.fromBase58(toString(args[1]));
amount = toSatoshi(args[2]); amount = toSatoshi(args[2]);
if (!account) if (!account)
@ -3843,7 +3859,7 @@ RPC.prototype.sendmany = co(function* sendmany(args) {
for (i = 0; i < keys.length; i++) { for (i = 0; i < keys.length; i++) {
key = keys[i]; key = keys[i];
value = toSatoshi(sendTo[key]); value = toSatoshi(sendTo[key]);
address = bcoin.address.fromBase58(key); address = Address.fromBase58(key);
hash = address.getHash('hex'); hash = address.getHash('hex');
if (uniq[hash]) if (uniq[hash])
@ -3851,7 +3867,7 @@ RPC.prototype.sendmany = co(function* sendmany(args) {
uniq[hash] = true; uniq[hash] = true;
output = new bcoin.output(); output = new Output();
output.value = value; output.value = value;
output.script.fromAddress(address); output.script.fromAddress(address);
outputs.push(output); outputs.push(output);
@ -3879,7 +3895,7 @@ RPC.prototype.sendtoaddress = function sendtoaddress(args) {
+ ' subtractfeefromamount )')); + ' subtractfeefromamount )'));
} }
address = bcoin.address.fromBase58(toString(args[0])); address = Address.fromBase58(toString(args[0]));
amount = toSatoshi(args[1]); amount = toSatoshi(args[1]);
subtractFee = toBool(args[4]); subtractFee = toBool(args[4]);
@ -3913,7 +3929,7 @@ RPC.prototype.signmessage = co(function* signmessage(args) {
address = toString(args[0]); address = toString(args[0]);
msg = toString(args[1]); msg = toString(args[1]);
address = bcoin.address.getHash(address, 'hex'); address = Address.getHash(address, 'hex');
if (!address) if (!address)
throw new RPCError('Invalid address.'); throw new RPCError('Invalid address.');
@ -4005,8 +4021,8 @@ RPC.prototype.importprunedfunds = co(function* importprunedfunds(args) {
if (!utils.isHex(tx) || !utils.isHex(block)) if (!utils.isHex(tx) || !utils.isHex(block))
throw new RPCError('Invalid parameter.'); throw new RPCError('Invalid parameter.');
tx = bcoin.tx.fromRaw(tx, 'hex'); tx = TX.fromRaw(tx, 'hex');
block = bcoin.merkleblock.fromRaw(block, 'hex'); block = MerkleBlock.fromRaw(block, 'hex');
if (args.length === 3) if (args.length === 3)
label = toString(args[2]); label = toString(args[2]);

View File

@ -9,13 +9,15 @@
/* jshint -W069 */ /* jshint -W069 */
var bcoin = require('../env');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var constants = bcoin.constants; var constants = require('../protocol/constants');
var http = require('./'); var http = require('./');
var HTTPBase = http.base; var HTTPBase = http.base;
var utils = require('../utils/utils'); var utils = require('../utils/utils');
var spawn = require('../utils/spawn'); var spawn = require('../utils/spawn');
var Address = require('../primitives/address');
var TX = require('../primitives/tx');
var Script = require('../script/script');
var co = spawn.co; var co = spawn.co;
var con = spawn.con; var con = spawn.con;
var crypto = require('../crypto/crypto'); var crypto = require('../crypto/crypto');
@ -297,10 +299,10 @@ HTTPServer.prototype._init = function _init() {
options.outputs.push({ options.outputs.push({
address: output.address address: output.address
? bcoin.address.fromBase58(output.address) ? Address.fromBase58(output.address)
: null, : null,
script: output.script script: output.script
? bcoin.script.fromRaw(output.script, 'hex') ? Script.fromRaw(output.script, 'hex')
: null, : null,
value: utils.satoshi(output.value) value: utils.satoshi(output.value)
}); });
@ -313,20 +315,20 @@ HTTPServer.prototype._init = function _init() {
for (i = 0; i < params.address.length; i++) { for (i = 0; i < params.address.length; i++) {
address = params.address[i]; address = params.address[i];
assert(typeof address === 'string', 'Address must be a string.'); assert(typeof address === 'string', 'Address must be a string.');
address = bcoin.address.fromBase58(address); address = Address.fromBase58(address);
} }
} else { } else {
assert(typeof params.address === 'string', 'Address must be a string.'); assert(typeof params.address === 'string', 'Address must be a string.');
options.address = bcoin.address.fromBase58(params.address); options.address = Address.fromBase58(params.address);
} }
} }
if (params.tx) { if (params.tx) {
if (typeof params.tx === 'object') { if (typeof params.tx === 'object') {
options.tx = bcoin.tx.fromJSON(params.tx); options.tx = TX.fromJSON(params.tx);
} else { } else {
assert(typeof params.tx === 'string', 'TX must be a hex string.'); assert(typeof params.tx === 'string', 'TX must be a hex string.');
options.tx = bcoin.tx.fromRaw(params.tx, 'hex'); options.tx = TX.fromRaw(params.tx, 'hex');
} }
} }
@ -1146,7 +1148,7 @@ ClientSocket.prototype.addFilter = function addFilter(addresses) {
var i, hash; var i, hash;
for (i = 0; i < addresses.length; i++) { for (i = 0; i < addresses.length; i++) {
hash = bcoin.address.getHash(addresses[i], 'hex'); hash = Address.getHash(addresses[i], 'hex');
if (!hash) if (!hash)
throw new Error('Bad address.'); throw new Error('Bad address.');
@ -1164,7 +1166,7 @@ ClientSocket.prototype.removeFilter = function removeFilter(addresses) {
var i, hash; var i, hash;
for (i = 0; i < addresses.length; i++) { for (i = 0; i < addresses.length; i++) {
hash = bcoin.address.getHash(addresses[i], 'hex'); hash = Address.getHash(addresses[i], 'hex');
if (!hash) if (!hash)
throw new Error('Bad address.'); throw new Error('Bad address.');

View File

@ -8,7 +8,8 @@ var utils = bcoin.utils;
var crypto = require('../lib/crypto/crypto'); var crypto = require('../lib/crypto/crypto');
var assert = require('assert'); var assert = require('assert');
var scriptTypes = constants.scriptTypes; var scriptTypes = constants.scriptTypes;
var c = require('../lib/utils/spawn').cb; var spawn = require('../lib/utils/spawn');
var cob = spawn.cob;
var dummyInput = { var dummyInput = {
prevout: { prevout: {
@ -49,41 +50,32 @@ describe('HTTP', function() {
node.on('error', function() {}); node.on('error', function() {});
it('should open node', function(cb) { it('should open node', cob(function *() {
constants.tx.COINBASE_MATURITY = 0; constants.tx.COINBASE_MATURITY = 0;
c(node.open(), cb); yield node.open();
}); }));
it('should create wallet', function(cb) { it('should create wallet', cob(function *() {
c(wallet.create({ id: 'test' }), function(err, wallet) { var info = yield wallet.create({ id: 'test' });
assert.ifError(err); assert.equal(info.id, 'test');
assert.equal(wallet.id, 'test'); }));
cb();
});
});
it('should get info', function(cb) { it('should get info', cob(function *() {
c(wallet.client.getInfo(), function(err, info) { var info = yield wallet.client.getInfo();
assert.ifError(err); assert.equal(info.network, node.network.type);
assert.equal(info.network, node.network.type); assert.equal(info.version, constants.USER_VERSION);
assert.equal(info.version, constants.USER_VERSION); assert.equal(info.agent, constants.USER_AGENT);
assert.equal(info.agent, constants.USER_AGENT); assert.equal(info.height, 0);
assert.equal(info.height, 0); }));
cb();
});
});
it('should get wallet info', function(cb) { it('should get wallet info', cob(function *() {
c(wallet.getInfo(), function(err, wallet) { var info = yield wallet.getInfo();
assert.ifError(err); assert.equal(info.id, 'test');
assert.equal(wallet.id, 'test'); addr = info.account.receiveAddress;
addr = wallet.account.receiveAddress; assert.equal(typeof addr, 'string');
assert.equal(typeof addr, 'string'); }));
cb();
});
});
it('should fill with funds', function(cb) { it('should fill with funds', cob(function *() {
var balance, receive, details; var balance, receive, details;
// Coinbase // Coinbase
@ -108,35 +100,29 @@ describe('HTTP', function() {
details = d; details = d;
}); });
c(node.walletdb.addTX(t1), function(err) { yield node.walletdb.addTX(t1);
assert.ifError(err); yield spawn.timeout(300);
setTimeout(function() {
assert(receive);
assert.equal(receive.id, 'test');
assert.equal(receive.type, 'pubkeyhash');
assert.equal(receive.branch, 0);
assert(balance);
assert.equal(utils.satoshi(balance.confirmed), 0);
assert.equal(utils.satoshi(balance.unconfirmed), 201840);
assert.equal(utils.satoshi(balance.total), 201840);
assert(details);
assert.equal(details.hash, t1.rhash);
cb();
}, 300);
});
});
it('should get balance', function(cb) { assert(receive);
c(wallet.getBalance(), function(err, balance) { assert.equal(receive.id, 'test');
assert.ifError(err); assert.equal(receive.type, 'pubkeyhash');
assert.equal(utils.satoshi(balance.confirmed), 0); assert.equal(receive.branch, 0);
assert.equal(utils.satoshi(balance.unconfirmed), 201840); assert(balance);
assert.equal(utils.satoshi(balance.total), 201840); assert.equal(utils.satoshi(balance.confirmed), 0);
cb(); assert.equal(utils.satoshi(balance.unconfirmed), 201840);
}); assert.equal(utils.satoshi(balance.total), 201840);
}); assert(details);
assert.equal(details.hash, t1.rhash);
}));
it('should send a tx', function(cb) { it('should get balance', cob(function *() {
var balance = yield wallet.getBalance();
assert.equal(utils.satoshi(balance.confirmed), 0);
assert.equal(utils.satoshi(balance.unconfirmed), 201840);
assert.equal(utils.satoshi(balance.total), 201840);
}));
it('should send a tx', cob(function *() {
var options = { var options = {
rate: 10000, rate: 10000,
outputs: [{ outputs: [{
@ -145,49 +131,41 @@ describe('HTTP', function() {
}] }]
}; };
c(wallet.send(options), function(err, tx) { var tx = yield wallet.send(options);
assert.ifError(err);
assert(tx);
assert.equal(tx.inputs.length, 1);
assert.equal(tx.outputs.length, 2);
assert.equal(utils.satoshi(tx.outputs[0].value) + utils.satoshi(tx.outputs[1].value), 48190);
hash = tx.hash;
cb();
});
});
it('should get a tx', function(cb) { assert(tx);
c(wallet.getTX('default', hash), function(err, tx) { assert.equal(tx.inputs.length, 1);
assert.ifError(err); assert.equal(tx.outputs.length, 2);
assert(tx); assert.equal(utils.satoshi(tx.outputs[0].value) + utils.satoshi(tx.outputs[1].value), 48190);
assert.equal(tx.hash, hash); hash = tx.hash;
cb(); }));
});
});
it('should generate new api key', function(cb) { it('should get a tx', cob(function *() {
var tx = yield wallet.getTX('default', hash);
assert(tx);
assert.equal(tx.hash, hash);
}));
it('should generate new api key', cob(function *() {
var t = wallet.token.toString('hex'); var t = wallet.token.toString('hex');
c(wallet.retoken(null), function(err, token) { var token = yield wallet.retoken(null);
assert.ifError(err); assert(token.length === 64);
assert(token.length === 64); assert.notEqual(token, t);
assert.notEqual(token, t); }));
cb();
});
});
it('should get balance', function(cb) { it('should get balance', cob(function *() {
c(wallet.getBalance(), function(err, balance) { var balance = yield wallet.getBalance();
assert.ifError(err); assert.equal(utils.satoshi(balance.total), 199570);
assert.equal(utils.satoshi(balance.total), 199570); }));
cb();
});
});
it('should cleanup', function(cb) { it('should execute an rpc call', cob(function *() {
var info = yield wallet.client.rpc.call('getblockchaininfo', []);
assert.equal(info.blocks, 0);
}));
it('should cleanup', cob(function *() {
constants.tx.COINBASE_MATURITY = 100; constants.tx.COINBASE_MATURITY = 100;
c(wallet.close(), function(err) { yield wallet.close();
assert.ifError(err); yield node.close();
c(node.close(), cb); }));
});
});
}); });