format docs

This commit is contained in:
Jason Dreyzehner 2015-10-16 12:43:27 -04:00
parent 461852e104
commit 004e793217
14 changed files with 70 additions and 222 deletions

View File

@ -1,15 +1,7 @@
---
title: Address
description: A simple interface to generate and validate a bitcoin address.
---
# Address
## Description
# Bitcoin Address
Represents a bitcoin address. Addresses are the most popular way to make bitcoin transactions. See [the official Bitcoin Wiki](https://en.bitcoin.it/wiki/Address) for technical background information.
## Instantiate an Address
To be able to receive bitcoins an address is needed, but in order to spend them a private key is necessary. Please take a look at the [`PrivateKey`](privatekey.md) docs for more information about exporting and saving a key.
```javascript
@ -42,7 +34,6 @@ var p2shAddress = new Address([publicKey1, publicKey2, publicKey3], 2);
```
## Validating an Address
The main use that we expect you'll have for the `Address` class in Bitcore is validating that an address is a valid one, what type of address it is (you may be interested on knowing if the address is a simple "pay to public key hash" address or a "pay to script hash" address) and what network does the address belong to.
The code to do these validations looks like this:

View File

@ -1,12 +1,5 @@
---
title: Block
description: A simple interface to parse and validate a bitcoin blocks.
---
# Block
## Description
A Block instance represents the information of a block in the bitcoin network. Given a hexadecimal string representation of the serialization of a block with its transactions, you can instantiate a Block instance. Methods are provided to calculate and check the merkle root hash (if enough data is provided), but transactions won't necessarily be valid spends, and this class won't validate them. A binary representation as a `Buffer` instance is also valid input for a Block's constructor.
# Bitcoin Block
A Block instance represents the information of a block in the bitcoin network. Given a hexadecimal string representation of the serialization of a block with its transactions, you can instantiate a Block instance. Methods are provided to calculate and check the merkle root hash (if enough data is provided), but transactions won't necessarily be valid spends, and this class won't validate them. A binary representation as a `Buffer` instance is also valid input for a Block's constructor.
```javascript
// instantiate a new block instance
@ -18,14 +11,12 @@ assert(block.validMerkleRoot());
// blocks have several properties
assert(block.header); // an instance of block header, more info below
assert(block.transactions); // an array of transactions, more info below
```
For detailed technical information about a block please visit [Blocks](https://en.bitcoin.it/wiki/Blocks#Block_structure) on the Bitcoin Wiki.
## Block Header
Each instance of Block has a BlockHeader *(which can be instantiated separately)*. The header has validation methods, to verify that the block.
Each instance of Block has a BlockHeader _(which can be instantiated separately)_. The header has validation methods, to verify that the block.
```javascript
// will verify that the nonce demonstrates enough proof of work
@ -41,12 +32,11 @@ assert(block.header.merkleRoot);
assert(block.header.time);
assert(block.header.bits);
assert(block.header.nonce);
```
For more information about the specific properties of a block header please visit the [Block hashing algorithm](https://en.bitcoin.it/wiki/Block_hashing_algorithm) page on the Bitcoin Wiki.
## Transactions
The set of transactions in a block is an array of instances of [Transaction](transaction.md) and can be explored by iterating on the block's `transactions` member.
```javascript
@ -54,4 +44,3 @@ for (var i in block.transactions) {
var transaction = block.transactions[i];
}
```

View File

@ -1,14 +1,7 @@
---
title: Browser Builds
description: Guide to using and writing modules and optimizing browser bundles.
---
# Browser Builds
Bitcore and most official submodules work in the browser, thanks to [browserify](http://browserify.org/) (some modules are not fully compatible with web browsers).
The easiest and recommended way to use them, is via [Bower](http://bower.io/), a browser package manager, and get the release bundles.
For example, when building an app that uses `bitcore` and `bitcore-ecies`, you do:
The easiest and recommended way to use them, is via [Bower](http://bower.io/), a browser package manager, and get the release bundles. For example, when building an app that uses `bitcore` and `bitcore-ecies`, you do:
```sh
bower install bitcore
@ -28,9 +21,11 @@ You can also use a `bower.json` file to store the dependencies of your project:
}
}
```
and run `bower install` to install the dependencies.
After this, you can include the bundled release versions in your HTML file:
```html
<!DOCTYPE html>
<html lang="en">
@ -55,28 +50,26 @@ After this, you can include the bundled release versions in your HTML file:
```
## Building Custom Bundles
If you want to use a specific version of a module, instead of a release version (not recommended), you must run browserify yourself. You can get a minified browser bundle by running the following on the project root folder.
If you want to use a specific version of a module, instead of a release version (not recommended), you must run browserify yourself.
You can get a minified browser bundle by running the following on the project root folder.
```sh
browserify --require ./index.js:bitcore | uglifyjs > bitcore.min.js
```
(for bitcore)
```sh
browserify --require ./index.js:bitcore-ecies --external bitcore | uglifyjs > bitcore-ecies.min.js
```
(for a bitcore module, `bitcore-ecies` in the example)
## Development of Modules
*Note:* You probably don't want to use this method, but `bitcore-build`, as explained above. This is left here as documentation on what happens under the hood with `bitcore-build`.
_Note:_ You probably don't want to use this method, but `bitcore-build`, as explained above. This is left here as documentation on what happens under the hood with `bitcore-build`.
When developing a module that will depend on Bitcore, it's recommended to exclude Bitcore in the distributed browser bundle when using browserify and to use the `--external bitcore` parameter. It will produce a smaller browser bundle, as it will only include the JavaScript that is nessessary, and will depend on the Bitcore browser build which is better for distribution.
### Building the Bundle Manually
**Step 1**: Require Bitcore
Here we require Bitcore and define the namespace (`index.js`):

View File

@ -1,29 +1,17 @@
---
title: Crypto
description: Primitives and tools to deal with bitcoin cryptography.
---
# Crypto
## Description
# Bitcoin Crypto
The cryptographic primitives (ECDSA and HMAC) implementations in this package have been reviewed by the BitPay engineering team. More audits and reviews are welcomed.
## Random
The `bitcore.crypto.Random` namespace contains a single function, named `getRandomBuffer(size)` that returns a `Buffer` instance with random bytes. It may not work depending on the engine that bitcore is running on (doesn't work with IE versions lesser than 11).
## BN
The `bitcore.Crypto.BN` class contains a wrapper around [bn.js](https://github.com/indutny/bn.js), the bignum library used internally in bitcore.
## Point
The `bitcore.Crypto.Point` class contains a wrapper around the class Point of [elliptic.js](https://github.com/indutny/elliptic), the elliptic curve library used internally in bitcore.
## Hash
The `bitcore.Crypto.Hash` namespace contains a set of hashes and utilities. These are either the native `crypto` hash functions from `node.js` or their respective browser shims as provided by the `browserify` library.
## ECDSA
`bitcore.Crypto.ECDSA` contains a pure JavaScript implementation of the elliptic curve DSA signature scheme based on [elliptic.js](https://github.com/indutny/elliptic).

View File

@ -1,17 +1,8 @@
---
title: Encoding
description: Utilities for encoding information in bitcoin standard formats.
---
# Encoding
## Description
The `bitcore.Encoding` namespace contains utilities for encoding information in common formats in the bitcoin ecosystem.
## Base58 & Base58Check
Two classes are provided: `Base58` and `Base58Check`. The first one merely encodes/decodes a set of bytes in base58 format. The second one will also take the double `sha256` hash of the information and append the last 4 bytes of the hash as a checksum when encoding, and check this checksum when decoding.
## BufferReader & BufferWriter
These classes are used internally to write information in buffers.

View File

@ -1,15 +1,10 @@
---
title: HDKeys
description: Lets you create and derive extended public and private keys according to the BIP32 standard for Hierarchical Deterministic (HD) keys.
---
# HDKeys
Create and derive extended public and private keys according to the BIP32 standard for Hierarchical Deterministic (HD) keys.
## Hierarchically Derived Keys
Bitcore provides full support for [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), allowing for many key management schemas that benefit from this property. Please be sure to read and understand the basic concepts and the warnings on that BIP before using these classes.
## HDPrivateKey
An instance of a [PrivateKey](privatekey.md) that also contains information required to derive child keys.
Sample usage:
@ -29,11 +24,9 @@ var address = derived.privateKey.toAddress();
// obtain HDPublicKey
var hdPublicKey = hdPrivateKey.hdPublicKey;
```
## HDPublicKey
An instance of a PublicKey that can be derived to build extended public keys. Note that hardened paths are not available when deriving an HDPublicKey.
```javascript

View File

@ -1,24 +1,16 @@
---
title: Networks
description: A simple interface to handle livenet and testnet bitcoin networks.
---
# Networks
## Description
Bitcore provides support for the main bitcoin network as well as for `testnet3`, the current test blockchain. We encourage the use of `Networks.livenet` and `Networks.testnet` as constants. Note that the library sometimes may check for equality against this object. Please avoid creating a deep copy of this object.
The `Network` namespace has a function, `get(...)` that returns an instance of a `Network` or `undefined`. The only argument to this function is some kind of identifier of the network: either its name, a reference to a Network object, or a number used as a magic constant to identify the network (for example, the value `0` that gives bitcoin addresses the distinctive `'1'` at its beginning on livenet, is a `0x6F` for testnet).
## Setting the Default Network
Most projects will only need to work with one of the networks. The value of `Networks.defaultNetwork` can be set to `Networks.testnet` if the project will need to only to work on testnet (the default is `Networks.livenet`).
## Network constants
The functionality of testnet and livenet is mostly similar (except for some relaxed block validation rules on testnet). They differ in the constants being used for human representation of base58 encoded strings. These are sometimes referred to as "version" constants.
Take a look at this modified snippet from [networks.js](https://github.com/bitpay/bitcore/blob/master/lib/networks.js)
```javascript
var livenet = new Network();
_.extend(livenet, {

View File

@ -1,22 +1,14 @@
---
title: Private Key
description: A simple interface to generate, import and handle private keys.
---
# Private Key
## Description
Represents a bitcoin private key and is needed to be able to spend bitcoin and sign transactions. See the official [Bitcoin Wiki](https://en.bitcoin.it/wiki/Private_key) for more information about private keys. A PrivateKey in Bitcore is an immutable object that has methods to import and export into a variety of formats including [Wallet Import Format](https://en.bitcoin.it/wiki/Wallet_import_format).
## Instantiate a Private Key
Here is how to create a new private key. It will generate a new random number using `window.crypto` or the Node.js `crypto` library.
```javascript
var privateKey = new PrivateKey();
// Creates a private key from a hexa encoded number
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79');
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79');
```
To export and import a private key, you can do the following:
@ -39,7 +31,6 @@ var address = publicKey.toAddress(Networks.livenet);
```
## Validating a Private Key
The code to do these validations looks like this:
```javascript

View File

@ -1,18 +1,9 @@
---
title: Public Key
description: A simple interface for handling private keys.
---
# Public Key
## Description
Represents a bitcoin public key and is needed to be able to receive bitcoin, as is usually represented as a bitcoin [Address](address.md).
See the official [Bitcoin Wiki](https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses).
Represents a bitcoin public key and is needed to be able to receive bitcoin, as is usually represented as a bitcoin [Address](address.md). See the official [Bitcoin Wiki](https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses).
A PublicKey in Bitcore is an immutable object and can be instantiated from a [Point](crypto.md), string, [PrivateKey](privatekey.md), Buffer or a [BN](crypto.md).
## Instantiate a Public Key
Here is how to instantiate a public key:
```javascript
@ -24,11 +15,9 @@ var publicKey = new PublicKey(privateKey);
// from a der hex encoded string
var publicKey2 = new PublicKey('02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0be551b5dc');
```
## Validating a Public Key
A public key point should be on the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) curve, instantiating a new PublicKey will validate this and will throw an error if it's invalid. To check that a public key is valid:
```javascript
@ -38,13 +27,10 @@ if (PublicKey.isValid('02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0
```
## Compressed vs Uncompressed
It's important to note that there are two possible ways to represent a public key.
The standard is *compressed* and includes the X value and parity (as represented above in the documentation).
There is also a longer version that is *uncompressed* which includes both X and Y values. Using this encoding will generate a different bitcoin address, so be careful when selecting the encoding.
Uncompressed public keys start with 0x04; compressed public keys begin with 0x03 or 0x02 depending on whether they're greater or less than the midpoint of the curve. These prefix bytes are all used in official secp256k1 documentation.
It's important to note that there are two possible ways to represent a public key. The standard is _compressed_ and includes the X value and parity (as represented above in the documentation). There is also a longer version that is _uncompressed_ which includes both X and Y values. Using this encoding will generate a different bitcoin address, so be careful when selecting the encoding. Uncompressed public keys start with 0x04; compressed public keys begin with 0x03 or 0x02 depending on whether they're greater or less than the midpoint of the curve. These prefix bytes are all used in official secp256k1 documentation.
Example:
```javascript
> var bitcore = require('bitcore');

View File

@ -1,26 +1,16 @@
---
title: Script
description: A powerful interface to create, parse and validate bitcoin scripts.
---
# Script
## Description
All bitcoin transactions have scripts embedded into its inputs and outputs. The scripts use a very simple programming language, which is evaluated from left to right using a stack. The language is designed such that it guarantees all scripts will execute in a limited amount of time (it is not Turing-Complete).
When a transaction is validated, the input scripts are concatenated with the output scripts and evaluated. To be valid, all transaction scripts must evaluate to true. A good analogy for how this works is that the output scripts are puzzles that specify in which conditions can those bitcoins be spent. The input scripts provide the correct data to make those output scripts evaluate to true.
For more detailed information about the bitcoin scripting language, check the online reference [on bitcoin's wiki](https://en.bitcoin.it/wiki/Script).
The `Script` object provides an interface to construct, parse, and identify bitcoin scripts. It also gives simple interfaces to create most common script types. This class is useful if you want to create custom input or output scripts. In other case, you should probably use `Transaction`.
## Script creation
Here's how to use `Script` to create the five most common script types:
### Pay to Public Key Hash (p2pkh)
This is the most commonly used transaction output script. It's used to pay to a bitcoin address (a bitcoin address is a public key hash encoded in base58check)
```javascript
@ -29,9 +19,9 @@ var address = Address.fromString('1NaTVwXDDUJaXDQajoa9MqHhz4uTxtgK14');
var script = Script.buildPublicKeyHashOut(address);
assert(script.toString() === 'OP_DUP OP_HASH160 20 0xecae7d092947b7ee4998e254aa48900d26d2ce1d OP_EQUALVERIFY OP_CHECKSIG');
```
### Pay to Public Key (p2pk)
Pay to public key scripts are a simplified form of the p2pkh, but arent commonly used in new transactions anymore, because p2pkh scripts are more secure (the public key is not revealed until the output is spent).
### Pay to Public Key (p2pk)
Pay to public key scripts are a simplified form of the p2pkh, but aren't commonly used in new transactions anymore, because p2pkh scripts are more secure (the public key is not revealed until the output is spent).
```javascript
// create a new p2pk paying to a specific public key
@ -41,7 +31,6 @@ assert(script.toString() === '33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e
```
### Pay to Multisig (p2ms)
Multisig outputs allow to share control of bitcoins between several keys. When creating the script, one specifies the public keys that control the funds, and how many of those keys are required to sign off spending transactions to be valid. An output with N public keys of which M are required is called an m-of-n output (For example, 2-of-3, 3-of-5, 4-of-4, etc.)
Note that regular multisig outputs are rarely used nowadays. The best practice is to use a p2sh multisig output (See Script#toScriptHashOut()).
@ -61,8 +50,7 @@ assert(script.toString() === 'OP_2 33 0x022df8750480ad5b26950b25c7ba79d3e37d75f6
```
### Pay to Script Hash (p2sh)
Pay to script hash outputs are scripts that contain the hash of another script, called `redeemScript`. To spend bitcoins sent in a p2sh output, the spending transaction must provide a script matching the script hash and data which makes the script evaluate to true. This allows to defer revealing the spending conditions to the moment of spending. It also makes it possible for the receiver to set the conditions to spend those bitcoins.
Pay to script hash outputs are scripts that contain the hash of another script, called `redeemScript`. To spend bitcoins sent in a p2sh output, the spending transaction must provide a script matching the script hash and data which makes the script evaluate to true. This allows to defer revealing the spending conditions to the moment of spending. It also makes it possible for the receiver to set the conditions to spend those bitcoins.
Most multisig transactions today use p2sh outputs where the `redeemScript` is a multisig output.
@ -77,8 +65,8 @@ var redeemScript = Script.buildMultisigOut(pubkeys, 2);
var script = redeemScript.toScriptHashOut();
assert(script.toString() === 'OP_HASH160 20 0x620a6eeaf538ec9eb89b6ae83f2ed8ef98566a03 OP_EQUAL');
```
### Data output
### Data output
Data outputs are used to push data into the blockchain. Up to 40 bytes can be pushed in a standard way, but more data can be used, if a miner decides to accept the transaction.
```javascript
@ -88,7 +76,6 @@ assert(script.toString() === 'OP_RETURN 14 0x68656c6c6f20776f726c64212121'
```
### Custom Scripts
To create a custom `Script` instance, you must rely on the lower-level methods `add` and `prepend`. Both methods accept the same parameter types, and insert an opcode or data at the beginning (`prepend`) or end (`add`) of the `Script`.
```
@ -102,7 +89,6 @@ assert(script.toString() === 'OP_2SWAP OP_IF OP_NOT 4 0xbacacafe');
```
## Script Parsing and Identification
`Script` has an easy interface to parse raw scripts from the network or bitcoind, and to extract useful information. An illustrative example (for more options check the API reference)
```javascript
@ -117,9 +103,7 @@ s.isMultisigOut() // true
```
## Script Interpreting and Validation
To validate a transaction, the bitcoin network validates all of its inputs and outputs. To validate an input, the input's script is concatenated with the referenced output script, and the result is executed. If at the end of execution the stack contains a 'true' value, then the transaction is valid.
You can do this in `bitcore` by using the `Interpreter` class. The entry point (and probably the only interface you'll need for most applications) is the method `Interpreter#verify()`.
To validate a transaction, the bitcoin network validates all of its inputs and outputs. To validate an input, the input's script is concatenated with the referenced output script, and the result is executed. If at the end of execution the stack contains a 'true' value, then the transaction is valid. You can do this in `bitcore` by using the `Interpreter` class. The entry point (and probably the only interface you'll need for most applications) is the method `Interpreter#verify()`.
You can use it like this:
@ -134,6 +118,7 @@ var verified = Interpreter().verify(inputScript, outputScript);
Note that `verify` expects two scripts: one is the input script (scriptSig) and the other is the output script (scriptPubkey). This is because different conditions are checked for each.
It also accepts some optional parameters, assuming defaults if not provided:
```
// first we create a transaction
var tx = new Transaction()

View File

@ -1,11 +1,4 @@
---
title: Transaction
description: A robust interface to create, parse and validate bitcoin transactions.
---
# Transaction
## Description
Bitcore provides a very simple API for creating transactions. We expect this API to be accessible for developers without knowing the working internals of bitcoin in deep detail. What follows is a small introduction to transactions with some basic knowledge required to use this API.
A Transaction contains a set of inputs and a set of outputs. Each input contains a reference to another transaction's output, and a signature that allows the value referenced in that output to be used in this transaction.
@ -33,13 +26,13 @@ bitcoin-cli sendrawtransaction <serialized transaction>
```
You can also override the fee estimation with another amount, specified in satoshis:
```javascript
var transaction = new Transaction().fee(5430); // Minimum non-dust amount
var transaction = new Transaction().fee(1e8); // Generous fee of 1 BTC
```
## Multisig Transactions
To send a transaction to a multisig address, the API is the same as in the above example. To spend outputs that require multiple signatures, the process needs extra information: the public keys of the signers that can unlock that output.
```javascript
@ -58,7 +51,7 @@ var multiSigTx = new Transaction(serialized)
.sign(anotherSetOfKeys);
assert(multiSigTx.isFullySigned());
```
```
Also, you can just send over the signature for your private key:
@ -82,113 +75,96 @@ transaction.applySignature(receivedSig);
```
## Adding inputs
Transaction inputs are instances of either [Input](https://github.com/bitpay/bitcore/tree/master/lib/transaction/input) or its subclasses. `Input` has some abstract methods, as there is no actual concept of a "signed input" in the bitcoin scripting system (just valid signatures for <tt>OP_CHECKSIG</tt> and similar opcodes). They are stored in the `input` property of `Transaction` instances.
Bitcore contains two implementations of `Input`, one for spending *Pay to Public Key Hash* outputs (called `PublicKeyHashInput`) and another to spend *Pay to Script Hash* outputs for which the redeem script is a Multisig script (called `MultisigScriptHashInput`).
Bitcore contains two implementations of `Input`, one for spending _Pay to Public Key Hash_ outputs (called `PublicKeyHashInput`) and another to spend _Pay to Script Hash_ outputs for which the redeem script is a Multisig script (called `MultisigScriptHashInput`).
All inputs have the following five properties:
* `prevTxId`: a `Buffer` with the id of the transaction with the output this input is spending
* `outputIndex`: a `number` the index of the output in the previous transaction
* `sequenceNumber`: a `number`, the sequence number, see [bitcoin's developer guide on nLockTime and the sequence number](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
* `script`: the `Script` instance for this input. Usually called `scriptSig` in the bitcoin community.
* `output`: if available, a `Output` instance of the output associated with this input.
- `prevTxId`: a `Buffer` with the id of the transaction with the output this input is spending
- `outputIndex`: a `number` the index of the output in the previous transaction
- `sequenceNumber`: a `number`, the sequence number, see [bitcoin's developer guide on nLockTime and the sequence number](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
- `script`: the `Script` instance for this input. Usually called `scriptSig` in the bitcoin community.
- `output`: if available, a `Output` instance of the output associated with this input.
Both `PublicKeyHashInput` and `MultisigScriptHashInput` cache the information about signatures, even though this information could somehow be encoded in the script. Both need to have the `output` property set in order to calculate the `sighash` so signatures can be created.
Some methods related to adding inputs are:
* `from`: A high level interface to add an input from a UTXO. It has a series of variants:
- `from`: A high level interface to add an input from a UTXO. It has a series of variants:
- `from(utxo)`: add an input from an [Unspent Transaction Output](http://bitcore.io/guide/unspentoutput.html). Currently, only P2PKH outputs are supported.
- `from(utxos)`: same as above, but passing in an array of Unspent Outputs.
- `from(utxo, publicKeys, threshold)`: add an input that spends a UTXO with a P2SH output for a Multisig script. The `publicKeys` argument is an array of public keys, and `threshold` is the number of required signatures in the Multisig script.
* `addInput`: Performs a series of checks on an input and appends it to the end of the `input` vector and updates the amount of incoming bitcoins of the transaction.
* `uncheckedAddInput`: adds an input to the end of the `input` vector and updates the `inputAmount` without performing any checks.
- `addInput`: Performs a series of checks on an input and appends it to the end of the `input` vector and updates the amount of incoming bitcoins of the transaction.
- `uncheckedAddInput`: adds an input to the end of the `input` vector and updates the `inputAmount` without performing any checks.
### PublicKeyHashInput
This input uses the `script` property to mark the input as unsigned if the script is empty.
### MultisigScriptHashInput
This input contains a set of signatures in a `signatures` property, and each time a signature is added, a potentially partial and/or invalid script is created. The `isFullySigned` method will only return true if all needed signatures are already added and valid. If `addSignature` is added after all need signatures are already set, an exception will be thrown.
## Signing a Transaction
The following methods are used to manage signatures for a transaction:
* `getSignatures`: takes an array of `PrivateKey` or strings from which a `PrivateKey` can be instantiated; the transaction to be signed; the kind of [signature hash to use](https://bitcoin.org/en/developer-guide#signature-hash-types). Returns an array of objects with the following properties:
- `getSignatures`: takes an array of `PrivateKey` or strings from which a `PrivateKey` can be instantiated; the transaction to be signed; the kind of [signature hash to use](https://bitcoin.org/en/developer-guide#signature-hash-types). Returns an array of objects with the following properties:
- `signature`: an instance of [Signature](https://github.com/bitpay/bitcore/blob/master/lib/crypto/signature.js)
- `prevTxId`: this input's `prevTxId`,
- `outputIndex`: this input's `outputIndex`,
- `inputIndex`: this input's index in the transaction
- `sigtype`: the "sighash", the type of transaction hash used to calculate the signature
- `publicKey`: a `PublicKey` of the `PrivateKey` used to create the signature
* `addSignature`: takes an element outputed by `getSignatures` and applies the signature to this input (modifies the script to include the new signature).
* `clearSignatures`: removes all signatures for this input
* `isFullySigned`: returns true if the input is fully signed
- `addSignature`: takes an element outputed by `getSignatures` and applies the signature to this input (modifies the script to include the new signature).
- `clearSignatures`: removes all signatures for this input
- `isFullySigned`: returns true if the input is fully signed
## Handling Outputs
Outputs can be added by:
* The `addOutput(output)` method, which pushes an `Output` to the end of the `outputs` property and updates the `outputAmount` field. It also clears signatures (as the hash of the transaction may have changed) and updates the change output.
* The `to(address, amount)` method, that adds an output with the script that corresponds to the given address. Builds an output and calls the `addOutput` method.
* Specifying a [change address](#Fee_calculation)
- The `addOutput(output)` method, which pushes an `Output` to the end of the `outputs` property and updates the `outputAmount` field. It also clears signatures (as the hash of the transaction may have changed) and updates the change output.
- The `to(address, amount)` method, that adds an output with the script that corresponds to the given address. Builds an output and calls the `addOutput` method.
- Specifying a [change address](#Fee_calculation)
To remove all outputs, you can use `clearOutputs()`, which preserves change output configuration.
## Serialization
There are a series of methods used for serialization:
* `toObject`: Returns a plain JavaScript object with no methods and enough information to fully restore the state of this transaction. Using other serialization methods (except for `toJSON`) will cause a some information to be lost.
* `toJSON`: Will be called when using `JSON.stringify` to return JSON-encoded string using the output from `toObject`.
* `toString` or `uncheckedSerialize`: Returns an hexadecimal serialization of the transaction, in the [serialization format for bitcoin](https://bitcoin.org/en/developer-reference#raw-transaction-format).
* `serialize`: Does a series of checks before serializing the transaction
* `inspect`: Returns a string with some information about the transaction (currently a string formated as `<Transaction 000...000>`, that only shows the serialized value of the transaction.
* `toBuffer`: Serializes the transaction for sending over the wire in the bitcoin network
* `toBufferWriter`: Uses an already existing BufferWriter to copy over the serialized transaction
- `toObject`: Returns a plain JavaScript object with no methods and enough information to fully restore the state of this transaction. Using other serialization methods (except for `toJSON`) will cause a some information to be lost.
- `toJSON`: Will be called when using `JSON.stringify` to return JSON-encoded string using the output from `toObject`.
- `toString` or `uncheckedSerialize`: Returns an hexadecimal serialization of the transaction, in the [serialization format for bitcoin](https://bitcoin.org/en/developer-reference#raw-transaction-format).
- `serialize`: Does a series of checks before serializing the transaction
- `inspect`: Returns a string with some information about the transaction (currently a string formated as `<Transaction 000...000>`, that only shows the serialized value of the transaction.
- `toBuffer`: Serializes the transaction for sending over the wire in the bitcoin network
- `toBufferWriter`: Uses an already existing BufferWriter to copy over the serialized transaction
## Serialization Checks
When serializing, the bitcore library performs a series of checks. These can be disabled by providing an object to the `serialize` method with the checks that you'll like to skip.
* `disableLargeFees` avoids checking that the fee is no more than `Transaction.FEE_PER_KB * Transaction.FEE_SECURITY_MARGIN * size_in_kb`.
* `disableSmallFees` avoids checking that the fee is less than `Transaction.FEE_PER_KB * size_in_kb / Transaction.FEE_SECURITY_MARGIN`.
* `disableIsFullySigned` does not check if all inputs are fully signed
* `disableDustOutputs` does not check for dust outputs being generated
* `disableMoreOutputThanInput` avoids checking that the sum of the output amounts is less than or equal to the sum of the amounts for the outputs being spent in the transaction
- `disableLargeFees` avoids checking that the fee is no more than `Transaction.FEE_PER_KB * Transaction.FEE_SECURITY_MARGIN * size_in_kb`.
- `disableSmallFees` avoids checking that the fee is less than `Transaction.FEE_PER_KB * size_in_kb / Transaction.FEE_SECURITY_MARGIN`.
- `disableIsFullySigned` does not check if all inputs are fully signed
- `disableDustOutputs` does not check for dust outputs being generated
- `disableMoreOutputThanInput` avoids checking that the sum of the output amounts is less than or equal to the sum of the amounts for the outputs being spent in the transaction
These are the current default values in the bitcore library involved on these checks:
* `Transaction.FEE_PER_KB`: `10000` (satoshis per kilobyte)
* `Transaction.FEE_SECURITY_MARGIN`: `15`
* `Transaction.DUST_AMOUNT`: `546` (satoshis)
- `Transaction.FEE_PER_KB`: `10000` (satoshis per kilobyte)
- `Transaction.FEE_SECURITY_MARGIN`: `15`
- `Transaction.DUST_AMOUNT`: `546` (satoshis)
## Fee calculation
When outputs' value don't sum up to the same amount that inputs, the difference in bitcoins goes to the miner of the block that includes this transaction. The concept of a "change address" usually is associated with this: an output with an address that can be spent by the creator of the transaction.
For this reason, some methods in the Transaction class are provided:
* `change(address)`: Set up the change address. This will set an internal `_changeScript` property that will store the change script associated with that address.
* `fee(amount)`: Sets up the exact amount of fee to pay. If no change address is provided, this will raise an exception.
* `getFee()`: returns the estimated fee amount to be paid, based on the size of the transaction, but disregarding the priority of the outputs.
- `change(address)`: Set up the change address. This will set an internal `_changeScript` property that will store the change script associated with that address.
- `fee(amount)`: Sets up the exact amount of fee to pay. If no change address is provided, this will raise an exception.
- `getFee()`: returns the estimated fee amount to be paid, based on the size of the transaction, but disregarding the priority of the outputs.
Internally, a `_changeIndex` property stores the index of the change output (so it can get updated when a new input or output is added).
## Time-Locking transaction
All bitcoin transactions contain a locktime field.
The locktime indicates the earliest time a transaction can be added to the blockchain.
Locktime allows signers to create time-locked transactions which will only become valid in the future, giving the signers a chance to change their minds.
Locktime can be set in the form of a bitcoin block height (the transaction can only be included in a block with a higher height than specified) or a linux timestamp (transaction can only be confirmed after that time).
For more information see [bitcoin's development guide section on locktime](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
All bitcoin transactions contain a locktime field. The locktime indicates the earliest time a transaction can be added to the blockchain. Locktime allows signers to create time-locked transactions which will only become valid in the future, giving the signers a chance to change their minds. Locktime can be set in the form of a bitcoin block height (the transaction can only be included in a block with a higher height than specified) or a linux timestamp (transaction can only be confirmed after that time). For more information see [bitcoin's development guide section on locktime](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
In bitcore, you can set a `Transaction`'s locktime by using the methods `Transaction#lockUntilDate` and `Transaction#lockUntilBlockHeight`. You can also get a friendly version of the locktime field via `Transaction#getLockTime`;
For example:
```javascript
var future = new Date(2025,10,30); // Sun Nov 30 2025
var transaction = new Transaction()
@ -197,8 +173,5 @@ console.log(transaction.getLockTime());
// output similar to: Sun Nov 30 2025 00:00:00 GMT-0300 (ART)
```
## Upcoming changes
We're debating an API for Merge Avoidance, CoinJoin, Smart contracts, CoinSwap, and Stealth Addresses. We're expecting to have all of them by some time in 2015. Payment channel creation is avaliable in the [bitcore-channel](https://github.com/bitpay/bitcore-channel) module.

View File

@ -1,14 +1,8 @@
---
title: Bitcoin Units
description: Utility to easily convert between bitcoin units.
---
# Unit
## Description
Unit is a utility for handling and converting bitcoin units. We strongly recommend to always use satoshis to represent amount inside your application and only convert them to other units in the front-end.
To understand the need of using the `Unit` class when dealing with unit conversions, see this example:
```
> 81.99 * 100000 // wrong
8198999.999999999
@ -19,7 +13,6 @@ To understand the need of using the `Unit` class when dealing with unit conversi
```
## Supported units
The supported units are BTC, mBTC, bits (micro BTCs, uBTC) and satoshis. The codes for each unit can be found as members of the Unit class.
```javascript
@ -31,7 +24,6 @@ var satsCode = Unit.satoshis;
```
## Creating units
There are two ways for creating a unit instance. You can instantiate the class using a value and a unit code; alternatively if the unit it's fixed you could you some of the static methods. Check some examples below:
```javascript
@ -50,7 +42,6 @@ unit = Unit.fromSatoshis(amount);
```
## Conversion
Once you have a unit instance, you can check its representation in all the available units. For your convenience the classes expose three ways to accomplish this. Using the `.to(unitCode)` method, using a fixed unit like `.toSatoshis()` or by using the accessors.
```javascript
@ -74,7 +65,6 @@ value = Unit.fromBTC(amount).satoshis;
```
## Using a fiat currency
The unit class also provides a convenient alternative to create an instance from a fiat amount and the corresponding BTC/fiat exchange rate. Any unit instance can be converted to a fiat amount by providing the current exchange rate. Check the example below:
```javascript

View File

@ -1,11 +1,4 @@
---
title: UnspentOutput
description: A stateless model to represent an unspent output and associated information.
---
# UnspentOutput
## Description
`bitcore.Transaction.UnspentOutput` is a class with stateless instances that provides information about an unspent output:
- Transaction ID and output index
- The "scriptPubKey", the script included in the output
@ -13,7 +6,6 @@ description: A stateless model to represent an unspent output and associated inf
- Address, if available
## Parameters
The constructor is quite permissive with the input arguments. It can take outputs straight out of bitcoind's getunspent RPC call. Some of the names are not very informative for new users, so the UnspentOutput constructor also understands these aliases:
- `scriptPubKey`: just `script` is also accepted
- `amount`: expected value in BTC. If the `satoshis` alias is used, make sure to use satoshis instead of BTC.

View File

@ -1,14 +1,8 @@
---
title: Bitcoin URIs
description: Utility to parse and create standard bitcoin URIs.
---
# URI
## Description
# Bitcoin URIs
Represents a bitcoin payment URI. Bitcoin URI strings became the most popular way to share payment request, sometimes as a bitcoin link and others using a QR code.
URI Examples:
```
bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu
bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2
@ -16,10 +10,10 @@ bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2&message=Payment&label=Sato
```
## URI Validation
The main use that we expect you'll have for the `URI` class in bitcore is validating and parsing bitcoin URIs. A `URI` instance exposes the address as a bitcore `Address` object and the amount in Satoshis, if present.
The code for validating URIs looks like this:
```javascript
var uriString = 'bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2';
var valid = URI.isValid(uriString);
@ -33,10 +27,10 @@ All standard parameters can be found as members of the `URI` instance. However a
See [the official BIP21 spec](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki) for more information.
## Create URI
Another important use case for the `URI` class is creating a bitcoin URI for sharing a payment request. That can be accomplished by using a dictionary to create an instance of URI.
The code for creating an URI from an Object looks like this:
```javascript
var uriString = new URI({
address: '12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu',