Skip to content
/ bcoin Public
forked from bcoin-org/bcoin

Javascript bitcoin library for node.js and browsers

License

Notifications You must be signed in to change notification settings

jjz/bcoin

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BCoin

BCoin is a bitcoin node which can act as an SPV node or a (semi-)fullnode.

Install

$ npm install bcoin

Example Usage

Doing a full blockchain sync

var bcoin = require('bcoin');
var utils = bcoin.utils;

var pool = new bcoin.pool({
  // Number of peers to connect to
  size: 8,
  // Output debug messages
  debug: true,
  // We want a traditional full node sync
  type: 'full',
  // Use testnet
  network: 'testnet'
});

// Peer errors: they happen all the time.
pool.on('error', function(err) {
  utils.print('Error: %s', err.message);
});

// When a new block is added to the chain:
pool.on('block', function(block, peer) {
  // Give a progress report every 500 blocks
  if (pool.chain.height() % 500 === 0)
    utils.print('block=%s, height=%s', block.rhash, pool.chain.height());
});

// Start the get blocks sync
pool.startSync();

Doing a fast SPV sync

var bcoin = require('bcoin');
var utils = bcoin.utils;
var fs = require('fs');

var pool = new bcoin.pool({
  // Number of peers to connect to
  size: 32,
  // Output debug messages
  debug: true,
  // We want an SPV sync using getheaders
  type: 'spv',
  // Use testnet
  network: 'testnet'
});

// Peer errors: they happen all the time.
pool.on('error', function(err) {
  utils.print('Error: %s', err.message);
});

// Instantiate an HD wallet with a serialized xprivkey
var wallet = new bcoin.wallet({
  hd: {
    xkey: process.env.XPRIVKEY || process.argv[2]
  }
});
utils.print('Opened wallet with address: %s', wallet.getAddress());

// Save our wallet for later
process.on('SIGINT', function() {
  fs.writeFileSync(
    process.env.HOME + '/my-wallet.json',
    JSON.stringify(wallet.toJSON()));
  process.exit(0);
});

// When a new block is added to the chain:
pool.on('block', function(block, peer) {
  // Give a progress report every 500 blocks
  if (pool.chain.height() % 500 === 0)
    utils.print('block=%s, height=%s', block.rhash, pool.chain.height());
});

// Watch for transactions pertaining to our wallet
pool.addWallet(wallet);

// Add watched transactions to our wallet's tx pool
pool.on('watched', function(tx, peer) {
  wallet.addTX(tx);
});

// Look for balance changes
wallet.on('balance', function() {
  utils.print('Wallet balance updated: %s', utils.btc(wallet.getBalance()));
});

// Start the getheaders sync
pool.startSync();

Creating and sending a transaction

var bcoin = require('bcoin');
var utils = bcoin.utils;

// Create a pool in order to broadcast our transaction
var pool = bcoin.pool({
  size: 8,
  type: 'spv',
  network: 'testnet'
});

// Retrieve our fully synced wallet
var wallet = bcoin.wallet.fromJSON(require('./my-wallet.json'));
utils.print('Opened wallet with address: %s', wallet.getAddress());

// Create another wallet to send to
var receiver = bcoin.wallet();
utils.print('Created receiver wallet with address: %s', receiver.getAddress());

// Save our new wallet, lest we lose the funds
fs.writeFileSync(process.env.HOME + '/my-new-wallet.json',
  JSON.stringify(receiver.toJSON()));

// Create a transaction
var tx = bcoin.tx();

// Add an output, send some money to our new wallet
tx.addOutput({
  address: receiver.getAddress(),
  // Every satoshi value in bcoin is
  // a big number, so we can convert
  // a BTC string to satoshis (big
  // number) by using utils.satoshi().
  // NOTE: BTC strings _must_ have
  // a decimal point.
  value: utils.satoshi('0.001')
});

// Fill the transaction inputs with the
// necessary unspents (hopefully we have them!).
tx.fill(
  wallet.getUnspent(),    // Our unspents to choose from
  wallet.getAddress(), // Our change address (warning: address re-use)
  null                 // We could put a hard fee here, but lets let bcoin figure it out
);

// Sign the transaction and place
// all signatures in necessary inputs
wallet.sign(tx);

// Make sure our transaction is valid.
if (!tx.verify())
  throw new Error('Our transaction did not verify!');

// Add our new TX to our wallets now
// that we know it is valid.
wallet.addTX(tx);
receiver.addTX(tx);

// Inspect our transaction before we send it.
utils.print('Sending transaction: %s', tx.rhash);
utils.print(tx);

// Tell our peers that we want to
// send a transaction across the network
pool.broadcast(tx)
  .on('ack', function(peer) {
    utils.print('Peer %s requested our transaction!', peer.host);
  })
  .on('reject', function(peer, details) {
    utils.print('Peer %s did not like our transaction (reason: %s).', peer.host, details.reason);
  });

// Watch for the transaction on the network
pool.watch(tx.hash());

// Wait to see our transaction on the network
pool.on('tx', function(ntx) {
  if (ntx.hash('hex') !== tx.hash('hex'))
    return;

  if (ntx.block)
    utils.print('Our tx was included in block %s (%d confirmations)', ntx.rblock, ntx.getConfirmations());
  else
    utils.print('Our tx is being propogated throughout the network!');

  // Add the network transaction to
  // our wallets to update the
  // confirmation status
  wallet.addTX(ntx);
  receiver.addTX(ntx);
});

Multisig Transactions

Let's fabricate a 2-of-3 escrow and dispute mediation situation.

var bcoin = require('bcoin');
var utils = bcoin.utils;

var pool = bcoin.pool({
  size: 8,
  network: 'testnet'
});

var buyer = bcoin.wallet({
  type: 'scripthash',
  subtype: 'multisig',
  m: 2,
  n: 3
});

var seller = bcoin.wallet({
  type: 'scripthash',
  subtype: 'multisig',
  m: 2,
  n: 3
});

var mediator = bcoin.wallet({
  type: 'scripthash',
  subtype: 'multisig',
  m: 2,
  n: 3
});

buyer.addKey(seller.getPublicKey());
buyer.addKey(mediator.getPublicKey());

seller.addKey(buyer.getPublicKey());
seller.addKey(mediator.getPublicKey());

mediator.addKey(buyer.getPublicKey());
mediator.addKey(seller.getPublicKey());

// We should all have the same p2sh address
utils.assert(buyer.getScriptAddress() === seller.getScriptAddress());
utils.assert(buyer.getScriptAddress() === mediator.getScriptAddress());

utils.print('Created 2-of-3 wallet with address: %s', buyer.getScriptAddress());

// Create a fake coinbase for buyer to use as his funds
var coinbase = bcoin.tx().addOutput(buyer.getKeyAddress(), utils.satoshi('50.0'));
buyer.addTX(coinbase);

// Now let's create a tx as the buyer.
// He wants to buy something from seller.
var btx = bcoin.tx();

// Send 25 BTC to the shared wallet
// to buy something from seller.
btx.addOutput({
  address: buyer.getScriptAddress(),
  value: utils.satoshi('25.0')
});

// Fill the unspents and sign
if (!buyer.fill(btx))
  throw new Error('Not enough funds');
buyer.sign(btx);

// Buyer sends his funds to the 2-of-3 wallet
pool.broadcast(btx);

// Seller can now try to redeem the funds
seller.addTX(btx);

// Seller creates a new transaction
var stx = bcoin.tx();

// Seller wants to send the BTC to himself
stx.addOutput({
  address: seller.getKeyAddress(),
  value: utils.satoshi('25.0')
    // Subtract the fee
    .sub(utils.satoshi('0.0001'))
    // Subtract the mediator's cut
    .sub(utils.satoshi('1.0'))
});

// Give the mediator a little something,
// since he's such a cool guy.
stx.addOutput({
  address: mediator.getKeyAddress(),
  value: utils.satoshi('1.0')
});

// Add the buyer's utxo as the input
stx.addInput(btx, 0);

// Add _one_ signature to the tx
seller.sign(stx);

// The tx should not verify at this point
utils.assert(!stx.verify());

// Buyer/Scammer: Hey Mediator, I never got my thing.
// Mediator: That sucks. Let me talk to Seller.
// Seller: I gave Buyer the item.
// Here's the proof: [insert proof here],
// and here's my transaction: [stx.toRaw() here]
// Mediator: Cool, looks good. I'll sign it!
mediator.sign(stx);

// The tx should now verify.
utils.assert(stx.verify())

// Mediator broadcasts Seller's now
// fully-signed transaction. Seller
// gets money.
pool.broadcast(stx);

Scripts

Bcoin has its own deserialized version of scripts to make them human-readable and human-writable. For example, a standard pay-to-pubkey script would look like:

tx.addOutput({
  value: new bn(100000),
  script: [
    'dup',
    'hash160',
    hash, // Byte Array
    'equalverify',
    'checksig'
  ]
});

Opcodes are in the form of their symbolic names, in lowercase, with the OP_ prefixes removed. Pushdata ops are represented with Arrays.

The above script could be redeemed with:

tx2.addInput({
  prevout: { tx: tx, hash: tx.hash('hex'), index: 0 },
  sequence: 0xffffffff,
  script: [
    signature, // Byte Array
    publicKey  // Byte Array
  ]
});

Executing a script by itself is also possible:

var stack = [];
bcoin.script.execute([[1], 'dup'], stack);
console.log(stack);

Output:
[[1], [1]]

Pushdata OPs

Note that with bcoins deserialized script format, you do not get to decide pushdata on ops. Bcoin will always serialize to minimaldata format scripts in terms of OP_PUSHDATA0-OP_PUSHDATA4.

OP_0 is represented with an empty array (which is appropriate because this is what gets pushed onto the stack). While OP_1-16 are actually represented with numbers. OP_1NEGATE is just '1negate'.

So a script making use of all pushdata ops would look like:

script: [
  [],                                // OP_0 / OP_FALSE
  1,                                 // OP_1 / OP_TRUE
  2, 3, 4, 5, 6, 7, 8, 9, 10,        // OP_2-10
  11, 12, 13, 14, 15, 16,            // OP_11-16
  '1negate',                         // OP_1NEGATE
  new Array(0x4b),                   // PUSHDATA0 (direct push)
  new Array(0xff),                   // PUSHDATA1
  new Array(0xffff),                 // PUSHDATA2
  new Array(0xffffffff)              // PUSHDATA4
];
Custom Scripts

Bcoin will allow you to use custom P2SH scripts, but it's up to you to redeem/sign it property.

var wallet = bcoin.wallet({
  redeem: [
    1,
    '1add',
    'equal'
  ]
});
console.log(wallet.getScriptAddress());
var tx1 = bcoin.tx().addOutput(wallet.getScriptAddress(), new bn(100000));

Which would be redeemed with:

tx2.addInput({
  prevout: { tx: tx1, hash: tx1.hash('hex'), index: 0 },
  script: [
    2,
    // Redeem script:
    wallet.getScript()
  ]
});

Big Numbers

Bitcoin deals with really big numbers on a regular basis. Javascript Numbers lose precision after 53 bits. It is absolutely necessary to use big numbers when dealing with satoshi values.

var bcoin = require('bcoin');
var bn = bcoin.bn;

...

// Add an output with 100,000 satoshis as a value.
tx.addOutput(wallet.getKeyAddress(), new bn(100000));

To make this easier to deal with, bcoin has two helper functions: utils.btc() and utils.satoshi().

// Convert a BTC string to Satoshis
var value = utils.satoshi('1.123');
console.log(value);
// Convert back to a BTC string
console.log(utils.btc(value));

Output:

<BN: 6b18fe0>
1.123

Note that BTC strings are identified by having a decimal point. They must have a decimal point in order to be converted to satoshis by utils.satoshi().

This will work:

var value = utils.satoshi('1.0');

This will not work:

var value = utils.satoshi('1');

Endianness

Everything in the bitcoin protocol is little-endian, including block hashes and txids. Bcoin doesn't try to change this at all. If you're outputing a tx hash, you will get the little-endian version.

You will not be able to find this hash on a blockchain explorer:

console.log(tx.hash('hex'));

The byte order must be reversed:

console.log(utils.revHex(tx.hash('hex')));

To make this easier, both tx and block objects have a quick rhash property:

// Output BE hashes as hex string - you will
// be able to find these on a blockchain explorer.
console.log(tx.rhash);
console.log(block.rhash);

Arrays vs. Buffers

Every piece of binary data in bcoin that is user-facing in bcoin is an Array of bytes. For example, block.hash() with no encoding passed in will return a byte array. Bcoin does use Buffers behind the scenes to speed up parsing of blocks and transactions coming in through the network, but every piece of data a programmer using bcoin will deal with is going to be a byte array.

Saving transactions to a wallet

Most of the time, you won't need all transactions in the blockchain if you're only building a wallet. When a transaction comes in pertaining to your wallet, it's best to called wallet.addTX(tx) and save the wallet afterwards.

pool.on('watched', function(tx) {
  wallet.addTX(tx);
});

pool.on('full', function() {
  fs.writeFileSync(
    process.env.HOME + '/wallet.json',
    JSON.stringify(wallet.toJSON()));
});

Saving the blockchain

At the moment, bcoin does not save any full blocks or make any assumptions about how the programmer wants to do it. It only saves the blockchain (block headers and chainwork). The programmer simply needs to hook into block events and save the blocks.

pool.on('block', function(block) {
  // A simple key-value store:
  db.save(block.hash('hex'), utils.toHex(block.render()), function(err) {
    if (err)
      return console.error(err.message);
    console.log('Block %s saved.', block.rhash);
    // Could also save transactions individually here for quick lookups
  });
});

Handling Blockchain Forks

Bcoin handles blockchain forks like an SPV client. If it sees an alternate tip, it will reset to the last non-forked block and kill the current peer while emitting a fork event (see Pool events). It will repeat this process until the network eventually chooses the best chain.

Bcoin essentially backs off and waits to see which fork wins. This means bcoin plays no part in protecting the network by helping choose the best chain according to the chainwork.

Note that this may still cause an issue with transactions that are already saved and considered confirmed. It's best to hook into the fork event and remove all confirmed transactions you may have saved in your database.

pool.on('fork', function(tip1, tip2) {
  // Keep deleting everything until
  // the fork is resolved:
  db.get(tip1, function(err, block) {
    block.txs.forEach(function(tx) {
      db.remove(tx.hash('hex'));
    });
  });
  db.get(tip2, function(err, block) {
    block.txs.forEach(function(tx) {
      db.remove(tx.hash('hex'));
    });
  });
  db.remove(tip1);
  db.remove(tip2);
});

Transaction Building

Transaction building happens in 4 stages:

  1. Outputs: Adding of the outputs (where we want to send the coins).
  2. Filling: Filling of the unspent outputs as the inputs, calculation of fee, and potential addition of a change address.
  3. Scripting: Compilation of the of the input scripts (minus the signatures). This will fill n empty signature slots (OP_0).
    • Potential recalculation of the fee: Now that the redeem script is available to the primitive TX object, it can likely calculate a lower fee. Add value to the change address if the fee is lower than we thought.
  4. Signing: Signing of the inputs. If this is a multisig transaction, we have to wait for other signers to sign it before it is finalized.
    • Finalization: Once the final signer signs the transaction, empty signature slots will be removed as they are no longer necessary.

Once these steps are completed, the transaction should verify and is able to be broadcast to the pool.

API Documentation

Objects

Block (from Object)

A deserialized bitcoin block object.

Usage: bcoin.block([options], [subtype])

Subtype can be block, merkleblock, or header.

Options:
  • version - Block version.
  • prevBlock - Previous block hash (hex string).
  • merkleRoot - Merkle root (hex string).
  • ts - Timestamp (unix time in seconds).
  • bits - Bits (target in compact form).
  • nonce - Nonce.
  • totalTX - Total TX (spv-only, and subtype=header only).
  • hashes - Hashes from partial merkle tree (spv-only).
  • flags - Flags from partial merkle tree (spv-only).
  • txs - Array of transactions (subtype=block only).
  • network - Whether this block came in through the network.
  • relayedBy - IP/host of relayer.
Properties:
  • Inherits all from Object.
  • All options.
  • tx - Type of the node (e.g. box).
  • valid - Cached preliminary verification return value.
  • chain - Chain object (default is the global chain).
  • rhash - Big-endian hash as a hex string (the byte order people are used to seeing). Useful for user output and debugging.
  • height - Block height in chain. -1 if not in chain.
  • nextBlock - Next block hash as a hex string.
  • reward - Full reward with fees included (satoshis/big number).
  • fee - Total TX fees (satoshis/big number).
  • coinbase - Coinbase transaction.
  • entry - Corresponding Entry object in blockchain.
  • orphan - True if block's previous block is not in blockchain.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • hash([enc]) - Hash the block headers, returns an array or a hex string (little-endian) if enc='hex'.
  • abbr() - Return a byte array of serialized headers.
  • render() - Return byte array of serialized block.
  • verify() - Do preliminary validation of block. Checks proof-of-work, timestamp limit, merkle root, max block size, etc.
  • verifyContext() - Do contextual block validation. Checks target, median time, outdated blocks, upgraded blocks, coinbase height, final TXes, verifies tx scripts. NOTE: The previous block must be in the blockchain or the validation will fail.
  • isGenesis() - Returns true if block is the genesis block of the network. before the reference node.
  • getSize() - Return block size in bytes.
  • getHeight() - Returns height in the blockchain. Returns -1 if block is not present in the chain. node.
  • getNextBlock() - Returns hex string of the hash of the next block.
  • getBaseReward() - Return base reward in satoshis (big number).
  • getReward() - Return full reward with TX fees included in satoshis (big number).
  • getFee() - Return total TX fees in satoshis (big number).
  • getEntry() - Return corresponding Entry object in the blockchain.
  • isOrphan() - Returns true if the previous block is not in the blockchain.
  • getCoinbase() - Returns coinbase transaction.
  • toJSON() - Return serialized block in bcoin json format.
Static:
  • reward(height) - Calculate block reward based on a height.
  • fromJSON(json) - Return Block object from serialized JSON block format.

Bloom (from Object)

A bloom filter. Used internally by bcoin for SPV/filterload.

Usage: bcoin.bloom(size, n, tweak)

Methods:
  • Inherits all from Object.
  • add(data, [enc]) - Add an array or buffer to the bloom filter.
  • test(val, [enc]) - Test the bloom filter against a piece of data. NOTE: Bloom filters are probabilistic and may return false positives (but never false negatives).
  • reset() - Reset the bits in the bloom filter.

Chain (from EventEmitter)

The blockchain object. Used for block management. Stores ChainBlock entries using ChainDB.

Usage: bcoin.chain([options])

Options:
  • debug - Whether to print debug messages.
Properties:
  • Inherits all from EventEmitter.
  • All options.
  • tip - The current tip of the blockchain as a ChainBlock.
Events:
  • fork - Emitted when a blockchain fork is detected. When a fork is seen, will kill the peer that forked and reset the tip to the last block which did not fork. Bcoin will repeat this process every time it sees an alternate tip. It will essentially back off and wait to see which fork wins the chainwork race.
Methods:
  • Inherits all from Object.
  • resetLastCheckpoint() - Reset blockchain to the nearest checkpoint block.
  • resetHeight(height) - Reset the blockchain to a past height.
  • resetTime(ts) - Reset the blockchain to an approximate time (unix time in seconds). Bcoin will search the blockchain for a timestamp close to ts, and reset the chain to that height. Used in SPV syncs to get transactions for a wallet based on the wallet's last timestamp.
  • add(block, [peer]) - Add a block to the block chain. Performs all block validation, fork recovery, orphan resolution, etc.
  • has(block/hash) - Returns true if chain contains hash as an entry or an orphan.
  • byHeight(height) - Return a ChainBlock entry by height.
  • byHash(block/hash) - Return a ChainBlock entry by hash.
  • byTime(ts) - Return a ChainBlock entry by ts. Bcoin will do a binary search for a block mined within an hour of ts (unix time in seconds).
  • hasBlock(hash) - Returns true if chain contains non-orphaned block.
  • hasOrphan(hash) - Return true if chain contains orphaned block.
  • getBlock(hash/height) - Return ChainBlock entry by height or hash.
  • getOrphan(hash) - Return orphaned Block object by hash.
  • isFull() - Returns true if last block in chained was mined within 40 minutes of present time.
  • hashRange(startTime, endTime) - Return an array of block hashes between a range of time.
  • getLocator(hash/height) - Return array of block locator hashes starting from hash or height.
  • getOrphanRoot(block/hash) - Find the orphan root based on hash if there is one.
  • getHeight(block/hash) - Return block height based on hash or block.
  • getNextBlock(block/hash) - Return next block hash based on hash or block.
  • getSize() - Number of blocks in the chain (different from height).
  • height() - Return height of chain tip (-1 if genesis block is not present).
  • currentTarget() - Return the current target in compact form.
  • target(last, [block]) - Return the target (compact form) necessary for block based on last (its previous block).
  • toJSON() - Return serialized JSON form of chain.
  • fromJSON(json) - Add serialized blocks to chain.
Static:
  • None.

ChainDB (from Object)

The blockchain database. Stores ChainBlock entries in a serialized binary format. The same format as block headers (80 bytes), except an extra uint256 is included at the end for chainwork, making each entry 112 bytes.

The ChainDB uses synchronous reads and asynchronous writes by default.

ChainDB caches the past majorityWindow blocks (1001 on main), or powDiffInterval (2016 on main) blocks if network.powAllowMinDifficulty is enabled. This is to speed up target calculation and isSuperMajority checks.

Usage: bcoin.chaindb(chain, options)

Options:
  • file - Database file (~/bcoin-[network]-blockchain.db by default).
Properties:
  • Inherits all from Object.
  • All options.
  • size - Size in bytes of the DB file.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • count() - Number of total records (different from chain height).
  • get(height) - Get ChainBlock entry synchronously.
  • getAsync(height, callback) - Get ChainBlock entry asynchronously (used for initial blockchain load).
  • save(entry, [callback]) - Save ChainBlock entry asynchronously.
  • saveSync(entry) - Save ChainBlock entry synchronously.
  • has(height) - Returns true if ChainDB has a block at this height.
  • getSize() - Get size in bytes of DB file.
Static:
  • Inherits all from Object.
  • None.

ChainBlock (from Object)

An "entry" for the blockchain. Counterpart to the block object with some different properties and methods. ChainBlocks are part of the blockchain's entire linked list.

Options:
  • version - Block version.
  • prevBlock - Previous block hash (hex string).
  • merkleRoot - Merkle root (hex string).
  • ts - Timestamp (unix time in seconds).
  • bits - Bits (target in compact form).
  • nonce - Nonce.
  • chainwork - Amount of chainwork (big number). NOTE: Will be calculated based on proof and previous block's chainwork if not present.
Properties:
  • Inherits all from Object.
  • All options.
  • prev - Previous ChainBlock entry.
  • next - Next ChainBlock entry.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • getProof() - Calculate and return proof based on bits/target (big number).
  • getChainwork() - Calculate and return chainwork based on proof and previous block's chainwork.
  • getMedianTime() - Get the median time for the block.
  • isOutdated(version) - Check if block version is outdated (calls isSuperMajority).
  • isUpgraded(version) - Check if block version upgrades the blockchain (calls isSuperMajority).
  • isSuperMajority(version, required) - Calculate if the last majorityWindow blocks are of version.
  • toJSON() - Return serialized ChainBlock in JSON format.
  • toRaw() - Return serialized ChainBlock in binary ChainDB format.
Static:
  • Inherits all from Object.
  • fromJSON(json) - Return ChainBlock from serialized JSON format.
  • fromRaw(data) - Return ChainBlock from ChainDB binary format.

HDSeed (from Object)

Generate an HDSeed (potentially from a passed-in mnemonic) for HD key generation.

Usage: bcoin.hd.seed([options])

Options:
  • bits - Bits of entropy (default: 128).
  • entropy - Entropy bytes (will be generated from /dev/urandom if entropy is not present).
  • mnemonic - English word mnemonic. Will be generated randomly using entropy if not present.
  • passphrase - Passphrase for pbkdf2 seed.
Properties:
  • Inherits all from Object.
  • All options.
  • seed - pbkdf2 seed.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • createSeed(passphrase) - Create pbkdf2 seed from options.
Static:
  • Inherits all from Function.
  • create(options) - Create and generate seed.

HDPrivateKey/HDPublicKey (from Object)

Generate an HDSeed (potentially from a passed-in mnemonic) for HD key generation.

Usage: bcoin.hd.priv([options]) or bcoin.hd.pub([options])

Options:
  • All options from HDSeed for seed generation.
  • seed - HDSeed for generation (will be generated randomly if no options are present).
  • xkey - Serialized xprivkey base58 string.

Deserialized option data:

  • depth
  • parentFingerPrint
  • childIndex
  • chainCode
  • privateKey
  • publicKey
  • checksum
Properties:
  • Inherits all from Object.
  • All options.
  • data - Normalized and deserialized data.
  • hdpub - Corresponding HDPublicKey object (present on HDPrivateKeys only).
  • xpubkey - Serialized xpubkey base58 string.
  • xprivkey - Serialized xprivkey base58 string.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • derive(index/path, [hardened]) - Returns a child key from index or path.
Static:
  • Inherits all from Function.
  • None.

Input (from Object)

TX Input object.

Usage: bcoin.input([options])

Options:
  • out.tx - Reference to the previous output's transaction (optional).
  • out.hash - Previous output's txid as a hex string.
  • out.index - Previous output's index.
  • script - Array of opcodes.
  • sequence - Input's nSequence, 0xffffffff by default.
Properties:
  • Inherits all from Object.
  • All options.
Getters

TX inputs are primitive by themselves, containing most of their relevant data in the script or previous output. The Input object contains several getters which parse the script and grab the previous output data and cache it as _data.

  • type - Standard transaction type of previous output (pubkey, pubkeyhash, multisig, scripthash, or nulldata). nulldata will never be the type of an input as nulldata outputs can never be redeemed.
  • subtype - Only present on scripthash transactions. The "real" transaction type of the previous output. See list above.
  • signature - The first signature in the input script.
  • key - The first public key in the input script.
  • hash - The scripthash or the first public key hash in the input script (if only public keys / redeem scripts are present, they will be hashed).
  • address - Scripthash address, first public key address, or a generated ID if no addresses are found (useful for making a blockchain explorer).
  • signatures - Array containing all signatures in the input.
  • keys - Array containing all keys in the input/previous-output.
  • hashes - Array containing all public key hashes in input/previous-output (all keys will be hashed if there are no hashes present).
  • addresses - All hashes/keys as addresses.
  • redeem - The redeem script in its deserialized form.
  • scripthash - The hash of the redeem script.
  • scriptaddress - The p2sh address.
  • m - m value (required signatures).
  • n - n value (number of keys).
  • lockTime - The OP_CHECKLOCKTIMEVERIFY locktime if present (NOTE: This will only grab the first value and not deal with OP_IF statements, etc).
  • flags - Coinbase flags if present.
  • text - Coinbase flags converted to UTF-8, if present.
  • output - Previous Output object.
  • value - Value (satoshis/big number) of the previous output.
  • tx - Reference to the previous output's parent transaction.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • getID() - Generate an ID string for the input. Used internally if no address is found.
Static:
  • Inherits all from Function.
  • getData(input) - Parse input / previous output and grab all data used for getters.

Output (from Object)

TX Output object.

Usage: bcoin.output([options])

Options:
  • script - Output script.
  • value - Value of output in satoshis (big number).
Properties:
  • Inherits all from Object.
  • All options.
Getters

TX outputs are primitive by themselves, containing most of their relevant data in the script. The Output object contains several getters which parse the script and cache it as _data.

  • type - Standard transaction type of output (pubkey, pubkeyhash, multisig, scripthash, or nulldata).
  • subtype - Only present on scripthash transactions. The "real" transaction type of the output.
  • signature - Null.
  • key - The first public key in the script.
  • hash - The scripthash or the first public key hash in the output script (if only public keys / redeem scripts are present, they will be hashed).
  • address - Scripthash address, first public key address, or a generated ID if no addresses are found (useful for making a blockchain explorer).
  • signatures - Empty array.
  • keys - Array containing all keys in the output script.
  • hashes - Array containing all public key hashes in output (all keys will be hashed if there are no hashes present).
  • addresses - All hashes/keys as addresses.
  • redeem - Null.
  • scripthash - The hash of the redeem script.
  • scriptaddress - The p2sh address.
  • m - m value (required signatures).
  • n - n value (number of keys).
  • lockTime - The OP_CHECKLOCKTIMEVERIFY locktime if present (NOTE: This will only grab the first value and not deal with OP_IF statements, etc).
  • flags - nulldata data.
  • text - nulldata data converted to UTF-8.
Events:
  • None.
Methods:
  • Inherits all from Object.
  • getID() - Generate an ID string for the output. Used internally if no address is found.
Static:
  • Inherits all from Function.
  • getData(output) - Parse output script and grab all data used for getters.

Miner (from EventEmitter)

A CPU bitcoin miner built on top of bcoin.

Usage: bcoin.miner([options])

Options:
  • address - Where to send the coinbase reward.
  • msg - Optional message to put in the coinbase script (default: mined by bcoin).
Properties:
  • Inherits all from EventEmitter.
  • All options.
  • hashes - Number of hashes since the start of mining the current block (big number).
  • rate - Hash rate.
Events:
  • block - Block object received when a new block is mined. NOTE: Miner will automatically attempt to broadcast the blocks, but it might be wise to save them yourself as a failsafe.
  • status - A progress report sent every 100000 hashes, containing hashrate, hashes, target, height, and best (current tip hash).
Methods:
  • Inherits all from Object.
  • start() - Start mining. Will block the thread until the nonce overflows (after which it times out for 10ms before incrementing the extraNonce in order to receive more transactions and potentially a new tip).
  • stop() - Stop mining.
  • add(block/tx) - Add a new tip or a new transaction to the block.
  • addBlock(block) - Inform the miner that someone beat us to the punch. Start over with a new block.
  • addTX(tx) - Add a transaction to the block being mined.
Static:
  • Inherits all from Function.

Peer (from EventEmitter)

Peer object. Used internally by the Pool object.

Usage: bcoin.peer(pool, createConnection, options)

  • pool: Pool object.
  • createConnection(peer, pool, options): Callback which must return a node-like socket.
Options:
  • backoff - Time to delay socket creation in milliseconds.
Properties:
  • Inherits all from EventEmitter.
  • All options.
  • socket - Socket object.
  • parser - Parser object for peer.
  • framer - Framer object for peer.
  • version - Reference to the version packet received from peer.
  • destroyed - Whether the peer has been destroyed.
  • ack - Whether a verack has been received.
  • connected - Whether the socket has established a connection.
  • ts - Time in unix seconds of connection time.
  • host - Hostname/IP string.
  • port - Port.
  • bloom - Reference to the bloom filter (SPV-only).
Events:
  • socket - Received on socket creation if backoff option was specified.
  • connect - Received on socket connection.
  • ack - Received on verack packet.
  • close - Received on peer destruction.
  • error - Received on error.
  • [packetname] - Received on packet (see Packet List).
Methods:
  • Inherits all from EventEmitter.
  • broadcast(items) - Broadcast array of items, whether they be blocks or TXes. Will send an inv packet to all peers and wait for getdata requests.
  • updateWatch() - Resend filterload packet. Useful after adding data to the bloom filter (SPV-mode only).
  • getData(items) - Request blocks or TXes.
  • loadMempool() - Send mempool. Requests inv packet full of mempool transactions from peer.
  • loadHeaders(hashes, stop) - Send getheaders.
  • loadBlocks(hashes, stop) - Send getblocks.
Static:
  • Inherits all from Function.

Pool (from EventEmitter)

A pool of peers. The heart and soul of bcoin's network activity.

Usage: bcoin.pool(options)

Pool will connect to one loader peer and options.size number of block peers. The loader peer is for getblocks or getheaders (as well as getdata, but only on a traditional getblocks sync). The block peers are used for getdata (on a non-traditional sync) as well as for broadcasting blocks/txes and receiving broadcasted blocks/txes.

The pool object will handle DoS attempts, label peers as misbehaving and ban them if necessary. If the pool does not receive an verack packet from a peer after a specified amount of time, the peer will be killed and a new one will be found. If the pool does not receive a block or inv packet in a specified amount of time, the loader peer will be killed and a new one will be found.

The pool object currently does not listen on a socket. It cannot accept connections (it can only connect to peers). It also doesn't maintain a mempool. In this way, the bcoin pool object is a "selfish" node. It does not help propogate data throughout the network.

Options:
  • debug - If true, output debug messages.
  • network - Which builtin network to use. Can be main, testnet, or regtest.
  • fullNode - If true, download blockchain using the traditional getblocks method with no filterload functionality. If false, do an SPV sync using getheaders and filterload.
  • type - Can be spv or full (same as fullNode=false, and fullNode=true respectively).
  • headers - Force use of getheaders for blockchain download depending on boolean value.
  • multiplePeers - Force downloading of blocks from multiple peers depending on value (NOTE: only works with a getheaders sync).
  • relay - Relay value in version packet. See BIP-37 for details.
  • createSocket(port, host) - Callback to create a socket. Must return a node-like socket.
  • seeds - List of initial seeds (array of strings in the format of {ipv4/host}:{port} or [{ipv6}]:port). Port will be set to the default network port if not present.
  • discoverPeers - If false, pay no attention to addr packets. Only connect to default seeds or seeds passed in with seeds.
  • size - Size of pool i.e. the number of peers to maintain connections with.
  • loadTimeout - The amount of time (ms) before killing the loader peer if an inv or block packet has not been received (default: 30000).
  • loadInterval - The amount of time (ms) before attempting stall recovery on the loader peer (which sends another getblocks/getheaders) (default: 5000).
  • requestTimeout - timeout before retrying a request (default: 10000).
  • invTimeout - Amount of time before removing objects from the broadcasted inv list (default: 60000).
  • wallets - Array of wallets to "watch" for on the pool (SPV-only).
Properties:
  • Inherits all from EventEmitter.
  • All options.
  • chain - Reference to the Chain object for the pool.
  • syncing - Whether the pool is syncing the blockchain.
  • synced - Whether the pool has completed the initial blockchain sync.
  • peers.block - Array of block peers.
  • peers.pending - Block peers in the process of establing a connection.
  • peers.load - Loader peer.
  • peers.all - Array of all peers.
  • block.bestHeight - Highest height received from version packet (NOTE: Not trustworthy).
  • block.bestHash - The last known best hash from the loader peer (the last hashContinue in a getblocks sync, or the last header hash in a getheaders sync).
  • inv.list - List of currently broadcasted items.
Events:
  • load() - Received once chain is done loading.
  • block(block, peer) - Received when a new block is received from peer and to the chain. (NOTE: this will never emit orphans).
  • pool block(block, peer) - Received when any new and valid block is received from a peer.
  • tx(tx, peer) - Received on transaction.
  • watched(tx, peer) - Received when a watched transaction is received (SPV-only).
  • fork(tip1Hash, tip2Hash) - Received on fork notifying the user to potentially ignore transactions in the forked blocks.
  • full() - Received when the blockchain is full.
  • headers(payload) - getheaders payload.
  • blocks(items) - inv payload containing only block hashes.
  • chain-progress(fillPercent, peer) - Received on a new block.
  • error(err, [peer]) - Received on error (usually a peer error).
  • reject(payload, peer) - Received when a peer rejects a broadcasted block/TX.
  • addr(payload, peer) - Received when an addr packet is received.
  • txs(txs, peer) - Received on inv packet, containing only TX hashes.
  • version(payload, peer) - Received on peer version packet.
  • peer(peer) - Received when a new peer is added.
Methods:
  • Inherits all from EventEmitter.
  • startSync() - Start downloading the blockchain.
  • stopSync() - Pause the blockchain sync.
  • isFull() - Whether the blockchain is full. Calls chain.isFull().
  • loadMempool() - Request mempool transactions from all peers.
  • watch(id) - Add a piece of data to "watch" for to the bloom filter. Send updated filterload to peers (SPV-only).
  • unwatch(id) - Stop watching for id (SPV-only).
  • isWatched(tx) - Test a transaction to see if the pool's bloom filter was watching for it (SPV-only).
  • addWallet(wallet) - Add a Wallet object to watch for. Add's wallet's pubkey, pubkeyhash, redeem script, and scripthash to the bloom filter. Resets the blockchain to the timestamp of the last TX the wallet contains in its TXPool (SPV-only).
  • removeWallet(wallet) - Remove wallet from watch list (SPV-only).
  • search([id], range) - Search a timestamp range, watch for id (SPV-only). range is a timestamp range: { start: unixSeconds, end: unixSeconds }.
  • getBlock(hash, callback) - Request block from peer.
  • sendBlock(block) - Broadcast a block.
  • getTX(txid, range, callback) - Attempt to search for a particular transaction (SPV-only). range is a timestamp range: { start: unixSeconds, end: unixSeconds }.
  • sendTX(tx) - Broadcast a transaction.
  • broadcast(block/tx) - Broadcast block or TX.
  • destroy() - Destroy pool and peers.
  • getPeer(host) - Get peer by host/ip+port.
  • addSeed(host) - Add a seed to the seed list.
  • removeSeed(host) - Remove a seed from the seed list.
  • setMisbehavior(peer, dos) - Increase peer's banscore by dos.
  • isMisbehaving(peer/host) - Whether peer is known for misbehaving.
Static:
  • Inherits all from Function.

script

A collection of functions for script handling.

Usage:

  • s = bcoin.script.decode(rawScript)
  • rawScript = bcoin.script.encode(s)
Functions:
  • decode(s) - Decode a raw script into bcoin's deserialized format (an array of strings and arrays).
  • encode(s) - Encode a deserialized script to a raw byte array.
  • normalize(s) - Normalize a script by changing 0 into [], -1 into '1negate', etc. Currently unused.
  • verify(input, output, tx, index, flags) - Execute input and previous output script and verify input. index is the index of the input being verified. flags is an object with boolean values. Keys can be of any of bitcoind's script flags in lowercase. i.e. minimaldata, cleanstack, etc.
  • getSubscript(s, lastSep) - Return script from lastSep with codeseparators removed.
  • checksig(msg, sig, key) - Verify a signature against a hash and key.
  • sign(msg, key, type) - Create a bitcoin ecdsa signature from msg and a private key. Appends type to the signature (the sighash type).
  • execute(s, stack, tx, index, flags) - Execute a script. stack must be an array.
  • bool(value) - Cast a byte array to bool. Mimics bitcoind's CastToBool() function. Checks for negative zero.
  • num(value, [useNum], [minimaldata]) - Create a standard little-endian big number from value. Checks for minimaldata if true. Checks for negative zero, etc. Mimics bitcoind's CScriptNum. If useNum is true, attempt to return a javascript Number.
  • array(value) - Convert big number to script little endian byte array.
  • createMultisig(keys, m, n) - Compile a standard multisig script from array of keys and m and n value.
  • createScripthash(s) - Compile a scripthash script from s.
  • getRedeem(s) - Grab an deserialize redeem script from input script.
  • getType(s) - Return standard output script type. unknown if unknown.
  • getSize(s) - Return script size in bytes.
  • isLocktime(s) - Returns true if script is a checklocktimeverify script.
  • getLockTime(s) - Return locktime value pushed onto the stack if checklocktimeverify is used.
  • getInputData(s, [prev]) - Parse input and previous output scripts. Extract as much data as possible. Same format as Input getters.
  • getOutputData(s) - Parse output script. Extract as much data as possible. Same format as Output getters.
  • getUnknownData(s) - Parse script and look for chunks of data with valid key and signature encodings. Return all keys and signatures. Same format as getInputData and getOutputData.
  • isPubkey(s) - Returns true if script is pay-to-pubkey.
  • isPubkeyhash(s) - Returns true if script is pay-to-pubkeyhash.
  • isMultisig(s) - Returns true if script is multisig.
  • isScripthash(s) - Returns true if script is pay-to-scripthash.
  • isNulldata(s) - Returns true if script is nulldata.
  • getInputType(s) - Same as script.getType(), but works on input scripts.
  • isPubkeyInput(s) - Returns true if script is pay-to-pubkey input script.
  • isPubkeyhashInput(s) - Returns true if script is pay-to-pubkeyhash input script.
  • isMultisigInput(s) - Returns true if script is multisig input script.
  • isScripthashInput(s) - Returns true if script is pay-to-scripthash input script.
  • getCoinbaseData(s) - Extract as much data as possible from a coinbase script including height, extraNonce, flags, and text.
  • isHash(data) - Returns true if data is the length of a ripemd hash.
  • isKey(data) - Returns true if data is the length of a public key.
  • isSignature(data) - Returns true if data is the length of a signature.
  • isDummy(data) - Returns true if data is a null dummy (empty array).
  • isData(data) - Returns true if data is potentially a nulldata.
  • isValidKey(data, [flags]) - Returns true if data is of strict key encoding.
  • isKeyEncoding(data) - Returns true if data is correct key encoding.
  • isValidSignature(data, [flags]) - Returns true if data is of signature encoding, with a low DER S value and has a valid hash type.
  • isSignatureEncoding(sig) - Returns true if sig is correct signature encoding (BIP-66).
  • isHashType(sig) - Returns true if sig has a valid hash type.
  • isLowDER(sig) - Returns true if sig has a low S value.
  • format(s) - Format script to make it more human-readable for output and debugging.
  • isPushOnly(s) - Returns true if script contains only push opcodes.
  • getSigops(s, [accurate]) - Count number of sigops in script. Legacy counting by default. Set accurate to true for accurate counting.
  • getScripthashSigops(s) - Count sigops in scripthash input + redeem script.
  • getArgs(s) - Return number of expected "input args" for output script type.

TXPool (from EventEmitter)

A pool of transactions which can be used in conjuction with a wallet object to calculate which transactions have been spent and which are unspent, ultimately calculating a balance. Used internally by Wallet object.

Usage: bcoin.txPool(wallet)

Properties:
  • Inherits all from EventEmitter.
  • None.
Events:
  • error(err) - Emitted on error.
  • load() - Emitted when storage has finished loading.
  • update(lastTs, tx) - Emitted when a spending transaction is added to the pool.
  • tx(tx) - Emitted when tx is added to the pool.
Methods:
  • Inherits all from EventEmitter.
  • add(tx) - Add TX to the pool.
  • getAll() - Return all TXes in the pool owned by wallet.
  • getUnspent() - Return all TXes with unspent outputs, owned by wallet.
  • getPending() - Return all 0-confirmation transactions.
  • getBalance() - Return total balance of TX pool.
  • toJSON() - Return TX pool in serialized JSON format.
  • fromJSON() - Load TX pool from serialized JSON format.
Static:
  • Inherits all from Function.

TX (from Object)

TX object.

Usage: bcoin.tx([options], [block])

Options:
  • version - Transaction version (default: 1).
  • inputs - Array of input objects with tx.addInput() options.
  • outputs - Array of output objects with tx.addOutput() options.
  • lockTime - nLockTime value.
  • ts - Timestamp (set by block if passed in arguments - spv-mode).
  • block - Block hash (Set by block if passed in arguments - spv-mode).
  • network - Should be true if TX came in from the network.
  • relayedBy - IP/hostname of peer who relayed this TX.
  • unspent - List of unspents to use to fill the transaction inputs.
  • hardFee - Custom fee to use in satoshis (big number) (optional).
  • changeAddress - Address to send change to.
  • changeIndex - Index of the change output.
Properties:
  • Inherits all from Object.
  • All options.
  • ps - Pending since time. Time of local transaction creation. Present only if this transaction is not in a block yet.
  • chain - Reference to the chain object.
  • rblock - Big-endian hex string of TX's block hash.
  • rhash - Big-endian hex string hash of transaction.
  • fee - Transaction fee in satoshis (big number).
  • value - Total value on the output side in satoshis (big number).
  • height - Height of block TX was included in (-1 if not included).
  • confirmations - Number of confirmations.
  • priority - Transaction priority based on input age and size (big number).
Events:
  • None.
Methods:
  • Inherits all from Object.

  • clone() - Return an exact duplicate of the transaction.

  • hash([enc], [force]) - Return TX hash/id. Hashes raw data passed in from the network if available to avoid reserialization. Pass in force=true if the transaction was mutated to get the current hash.

  • render([force]) - Serialize transaction. Returns raw byte array. Will return raw data passed in from the network if available. Set force=true to force serialization.

  • getSize() - Return serializzed transaction size in bytes.

  • addInput(options) - Add an input to the transaction. Options can be an Input object (see above), in the form of an Input object (containing properties prevout.tx, prevout.hash, prevout.index, script, and sequence).

    • addInput() can handle many different arguments in the forms of:
      • tx.addInput(tx, index)
      • tx.addInput(txHash, index)
      • tx.addInput(input)
      • tx.addInput({ hash: hash, index: index })
      • tx.addInput({ tx: tx, index: index })
  • scriptInput(index/input, pub, redeem) - Initialize the input scripts based on previous output script type. n signatures will be added. Signatures will be null dummies (empty signature slots) until signInput() is called. pub (the public key) and redeem (raw redeem script) should always be passed in if there is a pubkeyhash or scripthash output being redeemed. Will not overwrite existing input scripts.

  • createSignature(index/input, key, [type]) - Create a signature for the desired input using key as the private key and type as the sighash type. Sighash type can be a number or a string (all, single, or none). Returns a DER signature byte array.

  • signInput(index/input, key, [type]) - Sign the desired input and place the signature in an empty signature slot. Finalize the input script and reduce signature slots to m once the minimum amount of signatures has been reached.

  • scriptSig(index/input, key, pub, redeem, type) - Execute scriptInput and signInput.

  • addOutput(options), addOutput(output), addOutput(address, value) - Add an output to the transaction.

    • options can be in the form of:

              {
                value: [satoshis/big number],
                script: [deserialized script],
                address: [pubkey address or scripthash address],
                keys: [array of keys],
                m: [m value],
                n: [n value],
                flags: [nulldata],
                scripthash: [true or false],
                lockTime: [locktime for checklocktimeverify]
              }
      
  • scriptOutput(index/output, options) - Compile an output script for the output based on the same options addOutput() handles.

  • signatureHash(index/input, s, type) - Return the to-be-signed hash of the transaction for the desired input. Must pass in previous output subscript as s, as well as the sighash type (number or string of all, none, or single).

  • verify([index], [force], [flags]) - Execute and verify the desired input script. If no index is passed in, all inputs will be verified. verify() will not verify TXes already included in blocks, set force=true to force verification. flags can be any of the bitcoind script flags in lowercase, i.e. { cleanstack: false }. They are all enabled by default. Returns true if verification succeeded.

  • isCoinbase() - Returns true if TX is a coinbase.

  • maxSize() - Estimate the size of the transaction in bytes (works before input scripts are compiled and signed). Useful for fee calculation.

  • getInputs(unspent, changeAddress, [fee]) - Determine which unspents to use from unspent (an array of possible unspents, usually returned by wallet.getUnspent()). Calculates the fee and chooses unspents based on the total value required for the transaction. A hard fee can be passed in (satoshis/big number) which will skip the fee calculation. Calculates the necessary change. Returns an object in the form of:

      {
        inputs: [array in inputs to add],
        change: [change in satoshis (big number)],
        cost: [total cost minus fee in satoshis (big number)],
        fee: [fee for transaction in satoshis (big number)],
        total: [total cost including fee in satoshis (big number)],
        kb: [total kb for fee calculation]
      }
    

    inputs will be null if not enough funds were available. NOTE: getInputs() should only be called once all outputs have been added.

  • fill(unspent, [changeAddress], [fee]) - Calls getInputs() and adds the created inputs to the transaction. Adds a change output if necessary. Returns the same result value as getInputs(). NOTE: Should only be called once all outputs have been added.

  • getFee() - Returns the fee for transaction.

  • getFunds(side) - Returns the total funds for a side of the transaction 'input' or 'output'.

  • setLockTime(lockTime) - Sets a locktime for the transaction. Will set the nSequences accordingly.

  • increaseFee(fee) - Increase fee to a hard fee. Opts transaction in for replace-by-fee. NOTE: Transaction must be rescripted and resigned before broadcasting.

  • fillPrevout(wallet/txpool/object) - Fills all the transaction's inputs with the appropriate previous outputs using the available transactions in a wallet, txpool, or an object with txids as its keys and txs as its values.

  • isFull() - Returns true if the TX has all previous output references.

  • isFinal(height, ts) - Mimics the bitcoind IsFinalTx() function. Checks the locktime and input sequences. Returns true or false.

  • getSigops([scripthash], [accurate]) - Count sigops in transaction. Set scripthash=true to count redeem script sigops. Set accurate=true for accurate counting instead of legacy counting.

  • isStandard() - Mimics bitcoind's IsStandardTx() function.

  • isStandardInputs() - Mimics bitcoind's IsStandardInputs() function.

  • getPriority() - Calculate transaction priority based on input age. Returns a big number.

  • isFree() - Determines whether transaction needs a fee or not based on priority and size. Returns true if tx needs no fee.

  • getHeight() - Returns the height of the block TX was included in, similar to GetDepthInMainChain(). Returns -1 if no block is found.

  • getConfirmations() - Returns number of confirmations.

  • getValue() - Returns total value on the output side.

  • toJSON() - Return serialized TX in bcoin JSON format.

  • toRaw() - Returns serialized TX in standard bitcoin binary format.

Static:
  • Inherits all from Function.
  • fromJSON(json) - Return TX from serialized JSON format.
  • fromRaw(data) - Return TX from standard bitcoin binary format.

Wallet (from EventEmitter)

Wallet object.

Usage: bcoin.wallet(options)

Options:
  • compressed - Whether to use compressed public keys (default: true).
  • label - A string identifier for this wallet. Will be saved in JSON format.
  • changeAddress - A change address for this wallet to use (warning: address re-use).
  • key - Can be an instance of elliptic.KeyPair, bcoin.hd.priv, or bcoin.hd.pub.
  • priv - Private key, can be an array of bytes.
  • pub - Public key, can be an array of bytes.
  • type - Output script type. Can be: pubkey, pubkeyhash, multisig, scripthash.
  • subtype - Only applicable for scripthash types. Specify the type of redeem script. Can be pubkey, pubkeyhash, or multisig.
  • keys - An array of public keys (usually byte arrays) to use for a multisig wallet.
  • m - m value of wallet (number of required signatures).
  • n - n value of wallet (number of keys).
  • redeem - A script array containing a custom redeem script for scripthash.
  • hd - Make the wallet HD. Can be an object containing HDPrivateKey options, or a boolean.
Properties:
  • Inherits all from EventEmitter.
  • All options.
Events:
  • getBalance(balance) - Emitted when balance is updated. balance is in satoshis (big number).
  • tx(tx) - Emitted when a TX is added to the wallet's TXPool.
  • load(ts) - Emitted when the TXPool is finished loading. ts is the timestamp of the last transaction in the pool.
  • error(err) - Emitted on error.
Methods:
  • Inherits all from EventEmitter.

  • addKey(key) - Add public key to wallet (multisig).

  • removeKey(key) - Remove public key from wallet (multisig).

  • derive(index) - Derive a new wallet at index (HD-only).

  • getPrivateKey([enc]) - Return private key as a byte array or whatever encoding specified (base58 or hex).

  • getScript() - Get the raw redeem script as a byte array.

  • getScriptHash() - Return the hash of the redeem script as a byte array.

  • getScriptAddress() - Return the address of the scripthash.

  • getPublicKey([enc]) - Return the public key in desired encoding (byte array by default).

  • getKeyHash([enc]) - Return the hash of the public key.

  • getKeyAddress() - Return the address of the public key.

  • getHash([enc]) - Return scripthash if a scripthash wallet, otherwise return the public key hash.

  • getAddress() - Return the scripthash address if a scripthash wallet, otherwise return the address of the public key.

  • ownOutput(tx, [index]) - Check to see if output at index pertains to this wallet. If index is not present, all outputs will be tested.

  • ownInput(tx, [index]) - Check to see if input at index pertains to this wallet. If index is not present, all inputs will be tested.

  • fill(tx, [changeAddress], [fee]) - Fill tx with inputs necessary for total output value. Uses wallet.getUnspent() as the unspent list. Returns true if successfully filled necessary funds.

  • fillPrevout(tx) - "Fill" a transactions' inputs with references to its previous outputs if available.

  • scriptInputs(tx) - Compile necessary scripts for inputs (with OP_0 where the signatures should be). Will not overwrite existing input scripts.

  • signInputs(tx) - Sign all inputs possible in the TX. Finalize input scripts if possible.

  • sign(tx) - Equivalent to calling both scriptInputs(tx) and signInputs(tx) in one go.

  • addTX(tx) - Add a transaction to the wallet's TXPool.

  • getAll() - Returns all transactions from the TXPool.

  • getUnspent() - Returns all TXes with unspent outputs from the TXPool.

  • getPending() - Returns all TXes in the TXPool that have yet to be included in a block.

  • getBalance() - Returns total balance of the TXPool.

  • toAddress() - Return blockchain-explorer-like data in the format of:

                  {
                    address: [address],
                    hash160: [hash],
                    received: [total received (big number)],
                    sent: [total sent (big number)]
                    balance: [total balance (big number)],
                    txs: [array of txs]
                  }
    
  • toJSON([encrypt]) - Return a serialized wallet in JSON format. encrypt must be a callback which accepts and encrypts a string if you want the private keys to be encrypted when serializing.

Static:
  • Inherits all from Function.
  • toSecret(priv, [compressed]) - Convert a private key to a base58 string. Mimics the bitcoind CBitcoinSecret object for converting private keys to and from base58 strings. The same format bitcoind uses for dumpprivkey and importprivkey.
  • fromSecret(priv) - Convert a base58 private key string to a private key. See above for more information.
  • key2hash(key) - Return hash of a public key (byte array).
  • hash2addr(hash, [prefix]) - Return address of hash. prefix can be pubkey, pubkeyhash, multisig, or scripthash. Only scripthash actually has a different base58 prefix.
  • addr2hash(address, [prefix]) - Convert address back to a hash. Do checksum verification (returns empty array if checksum fails). If prefix is null, bcoin will detect the prefix.
  • validateAddress(address, [prefix]) - Return true if address is a valid address for prefix. i.e. bcoin.wallet.validateAddress('3L...', 'scripthash').
  • fromJSON(json, [decrypt]) - Return a wallet from a serialized JSON wallet. decrypt must be a callback which can decrypt the private keys encrypted by the encrypt callback (see toJSON above).

bcoin.utils

  • toArray(msg, [enc]) - Converts msg to an array. msg can be a string where enc can be null (for converting ascii to a byte array) or hex.
  • toBase58(arr) - Convert a byte array to base58.
  • fromBase58(msg) - Convert a base58 string to a byte array.
  • isBase58(msg) - Test msg to see if it is a base58 string.
  • ripemd160(data, [enc]) - RIPEMD160 hash function. Returns byte array.
  • sha1(data, [enc]) - SHA1 hash function. Returns byte array.
  • ripesha(data, [enc]) - SHA256+RIPEMD160 hash function. Returns byte array.
  • checksum(data, [enc]) - Create a checksum using a double SHA256.
  • sha256(data, [enc]) - SHA256 hash function. Returns byte array.
  • dsha256(data, [enc]) - Double SHA256 hash function. Returns byte array.
  • writeAscii(dst, str, off) - Write an ascii string to a byte array. Returns number of bytes written.
  • readAscii(arr, off, len, printable) - Read ascii from a byte array. Set printable to get only printable characters.
  • ascii2array(str) - Convert ASCII string to byte array.
  • array2ascii(arr) - Convert byte array to ASCII string.
  • array2utf8(arr) - Convert byte array to UTF8 string.
  • copy(src, dst, off, [force]) - Copy data from src to dst at offset off. Set force to increase dst size if necessary.
  • stringify(arr) - Convert byte array to ASCII string.
  • toHex(arr) - Convert byte array to hex string.
  • binaryInsert(list, item, compare, [search]) - Do a binary insert on list. compare is a compare callback. Set search for just a binary search.
  • utils.isEqual(a, b) - Compare two byte arrays.
  • utils.nextTick(callback) - process.nextTick or setImmediate if available.
  • utils.RequestCache - TODO.
  • utils.asyncify(callback) - Ensure that a callback executes asynchronously by wrapping it in a nextTick.
  • utils.assert()
  • utils.assert.equal()
  • utils.btc() - Convert satoshis (big number) to BTC string.
  • utils.satoshi() - Convert BTC string (must have a decimal point) to satoshis (big number).

Packet List

TODO

LICENSE

This software is licensed under the MIT License.

Copyright Fedor Indutny, 2014-2016.

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.

About

Javascript bitcoin library for node.js and browsers

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 99.8%
  • Other 0.2%