bitcore-lib
Advanced tools
Comparing version 0.13.7 to 0.13.8
{ | ||
"name": "bitcore-lib", | ||
"main": "./bitcore.min.js", | ||
"version": "0.13.7", | ||
"main": "./bitcore-lib.min.js", | ||
"version": "0.13.8", | ||
"homepage": "http://bitcore.io", | ||
@@ -6,0 +6,0 @@ "authors": [ |
@@ -100,3 +100,3 @@ Contributing to Bitcore | ||
These should have a matching static method that can be used for instantiation: | ||
* `fromObject` - Should be able to instatiate with the output from `toObject/toJSON` | ||
* `fromObject` - Should be able to instantiate with the output from `toObject/toJSON` | ||
* `fromString` - Should be able to instantiate with output from `toString` | ||
@@ -103,0 +103,0 @@ * `fromBuffer` - Should likewise be able to instantiate from output from `toBuffer` |
@@ -1,13 +0,5 @@ | ||
--- | ||
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. | ||
@@ -45,3 +37,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. | ||
@@ -48,0 +39,0 @@ |
@@ -1,11 +0,4 @@ | ||
--- | ||
title: Block | ||
description: A simple interface to parse and validate a bitcoin blocks. | ||
--- | ||
# Block | ||
# 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. | ||
## 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. | ||
```javascript | ||
@@ -21,3 +14,2 @@ // instantiate a new block instance | ||
assert(block.transactions); // an array of transactions, more info below | ||
``` | ||
@@ -28,5 +20,4 @@ | ||
## 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 | ||
@@ -46,8 +37,7 @@ // will verify that the nonce demonstrates enough proof of work | ||
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. | ||
@@ -60,2 +50,1 @@ | ||
``` | ||
@@ -1,16 +0,9 @@ | ||
--- | ||
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-mnemonic`, you do: | ||
```sh | ||
bower install bitcore | ||
bower install bitcore-ecies | ||
bower install bitcore-lib | ||
bower install bitcore-mnemonic | ||
``` | ||
@@ -26,10 +19,12 @@ | ||
"dependencies": { | ||
"bitcore-ecies": "^0.10.0", | ||
"bitcore": "^0.10.4" | ||
"bitcore-lib": "^0.13.7", | ||
"bitcore-mnemonic": "^1.0.1" | ||
} | ||
} | ||
``` | ||
and run `bower install` to install the dependencies. | ||
After this, you can include the bundled release versions in your HTML file: | ||
```html | ||
@@ -41,4 +36,4 @@ <!DOCTYPE html> | ||
<meta charset="utf-8"> | ||
<script src="bower_components/bitcore/bitcore.min.js"></script> | ||
<script src="bower_components/bitcore-ecies/bitcore-ecies.min.js"></script> | ||
<script src="bower_components/bitcore/bitcore-lib.min.js"></script> | ||
<script src="bower_components/bitcore-mnemonic/bitcore-mnemonic.min.js"></script> | ||
</head> | ||
@@ -49,4 +44,4 @@ | ||
<script type="text/javascript"> | ||
var bitcore = require('bitcore'); | ||
var ECIES = require('bitcore-ecies'); | ||
var bitcore = require('bitcore-lib'); | ||
var Mnemonic = require('bitcore-mnemonic'); | ||
// etc... | ||
@@ -61,53 +56,15 @@ </script> | ||
## 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 | ||
browserify --require ./index.js:bitcore-lib | uglifyjs > bitcore-lib.min.js | ||
``` | ||
(for bitcore) | ||
```sh | ||
browserify --require ./index.js:bitcore-ecies --external bitcore | uglifyjs > bitcore-ecies.min.js | ||
browserify --require ./index.js:bitcore-mnemonic --external bitcore-lib | uglifyjs > bitcore-mnemonic.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`. | ||
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`): | ||
```javascript | ||
var bitcore = require('bitcore'); | ||
var PrivateKey = bitcore.PrivateKey; | ||
var PublicKey = bitcore.PublicKey; | ||
var Address = bitcore.Address; | ||
In many of the modules you can also run the command to build a browser bundle: | ||
```sh | ||
gulp browser | ||
``` | ||
See the [main file](https://github.com/bitpay/bitcore/blob/master/index.js) for bitcore for a complete list, as well as the [Bitcore Documentation](index.md). | ||
**Step 2**: Browserifying | ||
Next we will generate a browser bundle using [browserify](https://www.npmjs.com/package/browserify) by running the command: | ||
```bash | ||
browserify index.js:module-name --external bitcore -o module-name.js | ||
``` | ||
This will output a file `module-name.js` with only the code loaded from `index.js` (bitcore.js will need to be loaded beforehand, which is around 145KB gzipped) | ||
**Step 3**: Uglifying | ||
This can be further optimized by using [uglifyjs](https://www.npmjs.com/package/uglify-js), and running the command: | ||
```bash | ||
uglifyjs module-name.js --compress --mangle -o module-name.min.js | ||
``` |
@@ -1,29 +0,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). |
@@ -1,17 +0,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. |
@@ -1,13 +0,8 @@ | ||
--- | ||
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. | ||
@@ -32,7 +27,5 @@ | ||
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. | ||
@@ -39,0 +32,0 @@ |
@@ -1,9 +0,2 @@ | ||
--- | ||
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. | ||
@@ -14,10 +7,9 @@ | ||
## 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 | ||
@@ -24,0 +16,0 @@ var livenet = new Network(); |
@@ -1,13 +0,5 @@ | ||
--- | ||
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. | ||
@@ -19,3 +11,3 @@ | ||
// Creates a private key from a hexa encoded number | ||
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79'); | ||
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79'); | ||
``` | ||
@@ -43,3 +35,2 @@ | ||
## Validating a Private Key | ||
The code to do these validations looks like this: | ||
@@ -46,0 +37,0 @@ |
@@ -1,16 +0,7 @@ | ||
--- | ||
title: Public Key | ||
description: A simple interface for handling private keys. | ||
--- | ||
# Public Key | ||
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). | ||
## 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). | ||
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: | ||
@@ -27,7 +18,5 @@ | ||
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: | ||
@@ -42,9 +31,6 @@ | ||
## 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: | ||
Example: | ||
```javascript | ||
@@ -51,0 +37,0 @@ > var bitcore = require('bitcore'); |
@@ -1,9 +0,2 @@ | ||
--- | ||
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). | ||
@@ -13,3 +6,2 @@ | ||
For more detailed information about the bitcoin scripting language, check the online reference [on bitcoin's wiki](https://en.bitcoin.it/wiki/Script). | ||
@@ -20,7 +12,5 @@ | ||
## 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) | ||
@@ -34,6 +24,6 @@ | ||
``` | ||
### 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). | ||
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 | ||
@@ -47,3 +37,2 @@ // create a new p2pk paying to a specific public key | ||
### 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.) | ||
@@ -68,5 +57,4 @@ | ||
### 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. | ||
@@ -85,4 +73,4 @@ | ||
``` | ||
### 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. | ||
@@ -97,3 +85,2 @@ | ||
### 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`. | ||
@@ -112,3 +99,2 @@ | ||
## 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) | ||
@@ -128,6 +114,4 @@ | ||
## 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: | ||
@@ -146,2 +130,3 @@ | ||
It also accepts some optional parameters, assuming defaults if not provided: | ||
``` | ||
@@ -148,0 +133,0 @@ // first we create a transaction |
@@ -1,9 +0,2 @@ | ||
--- | ||
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. | ||
@@ -36,2 +29,3 @@ | ||
You can also override the fee estimation with another amount, specified in satoshis: | ||
```javascript | ||
@@ -43,3 +37,2 @@ var transaction = new Transaction().fee(5430); // Minimum non-dust amount | ||
## 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. | ||
@@ -63,3 +56,3 @@ | ||
assert(multiSigTx.isFullySigned()); | ||
``` | ||
``` | ||
@@ -88,39 +81,33 @@ Also, you can just send over the signature for your private key: | ||
## 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) | ||
@@ -132,62 +119,50 @@ - `prevTxId`: this input's `prevTxId`, | ||
- `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 formatted 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). | ||
@@ -197,2 +172,3 @@ 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 | ||
@@ -206,6 +182,3 @@ var future = new Date(2025,10,30); // Sun Nov 30 2025 | ||
## 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. | ||
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 available in the [bitcore-channel](https://github.com/bitpay/bitcore-channel) module. |
@@ -1,12 +0,6 @@ | ||
--- | ||
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: | ||
``` | ||
@@ -22,3 +16,2 @@ > 81.99 * 100000 // wrong | ||
## 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. | ||
@@ -35,3 +28,2 @@ | ||
## 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: | ||
@@ -55,3 +47,2 @@ | ||
## 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. | ||
@@ -80,3 +71,2 @@ | ||
## 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: | ||
@@ -83,0 +73,0 @@ |
@@ -1,9 +0,2 @@ | ||
--- | ||
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: | ||
@@ -16,3 +9,2 @@ - Transaction ID and output index | ||
## 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: | ||
@@ -19,0 +11,0 @@ - `scriptPubKey`: just `script` is also accepted |
@@ -1,12 +0,6 @@ | ||
--- | ||
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: | ||
``` | ||
@@ -19,6 +13,6 @@ bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu | ||
## 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 | ||
@@ -37,6 +31,6 @@ var uriString = 'bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2'; | ||
## 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 | ||
@@ -43,0 +37,0 @@ var uriString = new URI({ |
@@ -284,3 +284,3 @@ 'use strict'; | ||
/** | ||
* @returns {string} - A string formated for the console | ||
* @returns {string} - A string formatted for the console | ||
*/ | ||
@@ -287,0 +287,0 @@ BlockHeader.prototype.inspect = function inspect() { |
'use strict'; | ||
var hashjs = require('hash.js'); | ||
var sha512 = require('sha512'); | ||
@@ -35,12 +34,2 @@ var crypto = require('crypto'); | ||
// Node.js crypto ripemd160 hashes are not supported in a browser | ||
// We'll replace with a (slower) version that does. | ||
if (process.browser) { | ||
Hash.ripemd160 = function(buf) { | ||
$.checkArgument(BufferUtil.isBuffer(buf)); | ||
var hash = (new hashjs.ripemd160()).update(buf).digest(); | ||
return new Buffer(hash); | ||
}; | ||
} | ||
Hash.sha256ripemd160 = function(buf) { | ||
@@ -47,0 +36,0 @@ $.checkArgument(BufferUtil.isBuffer(buf)); |
@@ -90,4 +90,3 @@ 'use strict'; | ||
var buf = bn.toBuffer({size: 8}); | ||
var reversebuf = new Buffer(Array.apply(new Array(), buf).reverse()); | ||
this.write(reversebuf); | ||
this.writeReverse(buf); | ||
return this; | ||
@@ -94,0 +93,0 @@ }; |
@@ -131,3 +131,3 @@ 'use strict'; | ||
/** | ||
* Get a derivated child based on a string or number. | ||
* Get a derived child based on a string or number. | ||
* | ||
@@ -134,0 +134,0 @@ * If the first argument is a string, it's parsed as the full path of |
@@ -541,3 +541,3 @@ 'use strict'; | ||
* Adds a script element at the start of the script. | ||
* @param {*} obj a string, number, Opcode, Bufer, or object to add | ||
* @param {*} obj a string, number, Opcode, Buffer, or object to add | ||
* @returns {Script} this script instance | ||
@@ -575,3 +575,3 @@ */ | ||
* | ||
* @param {*} obj a string, number, Opcode, Bufer, or object to add | ||
* @param {*} obj a string, number, Opcode, Buffer, or object to add | ||
* @returns {Script} this script instance | ||
@@ -793,3 +793,3 @@ * | ||
* | ||
* @param {Signature|Buffer} signature - a Signature object, or the signature in DER cannonical encoding | ||
* @param {Signature|Buffer} signature - a Signature object, or the signature in DER canonical encoding | ||
* @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL) | ||
@@ -816,3 +816,3 @@ */ | ||
* @param {Buffer|string|PublicKey} publicKey | ||
* @param {Signature|Buffer} signature - a Signature object, or the signature in DER cannonical encoding | ||
* @param {Signature|Buffer} signature - a Signature object, or the signature in DER canonical encoding | ||
* @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL) | ||
@@ -934,3 +934,3 @@ */ | ||
/** | ||
* Analagous to bitcoind's FindAndDelete. Find and delete equivalent chunks, | ||
* Analogous to bitcoind's FindAndDelete. Find and delete equivalent chunks, | ||
* typically used with push data chunks. Note that this will find and delete | ||
@@ -992,3 +992,3 @@ * not just the same data, but the same data with the same push data op as | ||
/** | ||
* Comes from bitcoind's script DecodOP_N function | ||
* Comes from bitcoind's script DecodeOP_N function | ||
* @param {number} opcode | ||
@@ -995,0 +995,0 @@ * @returns {number} numeric value in range of 0 to 16 |
@@ -1183,3 +1183,3 @@ 'use strict'; | ||
/** | ||
* Analagous to bitcoind's IsCoinBase function in transaction.h | ||
* Analogous to bitcoind's IsCoinBase function in transaction.h | ||
*/ | ||
@@ -1186,0 +1186,0 @@ Transaction.prototype.isCoinbase = function() { |
@@ -87,3 +87,3 @@ 'use strict'; | ||
/** | ||
* Returns a plain object (no prototype or methods) with the associated infor for this output | ||
* Returns a plain object (no prototype or methods) with the associated info for this output | ||
* @return {object} | ||
@@ -90,0 +90,0 @@ */ |
@@ -98,3 +98,3 @@ 'use strict'; | ||
*/ | ||
Unit.fromMilis = function(amount) { | ||
Unit.fromMillis = Unit.fromMilis = function(amount) { | ||
return new Unit(amount, Unit.mBTC); | ||
@@ -177,3 +177,3 @@ }; | ||
*/ | ||
Unit.prototype.toMilis = function() { | ||
Unit.prototype.toMillis = Unit.prototype.toMilis = function() { | ||
return this.to(Unit.mBTC); | ||
@@ -180,0 +180,0 @@ }; |
@@ -14,3 +14,3 @@ 'use strict'; | ||
* can be created with a bitcoin uri string or an object. All instances of | ||
* URI are valid, the static method isValid allows checking before instanciation. | ||
* URI are valid, the static method isValid allows checking before instantiation. | ||
* | ||
@@ -17,0 +17,0 @@ * All standard parameters can be found as members of the class, the address |
{ | ||
"name": "bitcore", | ||
"version": "0.13.5", | ||
"version": "0.13.7", | ||
"dependencies": { | ||
@@ -29,10 +29,10 @@ "bn.js": { | ||
"resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" | ||
}, | ||
"hash.js": { | ||
"version": "1.0.3", | ||
"from": "hash.js@=1.0.3", | ||
"resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz" | ||
} | ||
} | ||
}, | ||
"hash.js": { | ||
"version": "1.0.2", | ||
"from": "hash.js@^1.0.0", | ||
"resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.2.tgz" | ||
}, | ||
"inherits": { | ||
@@ -39,0 +39,0 @@ "version": "2.0.1", |
{ | ||
"name": "bitcore-lib", | ||
"version": "0.13.7", | ||
"version": "0.13.8", | ||
"description": "A pure and powerful JavaScript Bitcoin library.", | ||
@@ -87,3 +87,2 @@ "author": "BitPay <dev@bitpay.com>", | ||
"elliptic": "=3.0.3", | ||
"hash.js": "=1.0.2", | ||
"inherits": "=2.0.1", | ||
@@ -90,0 +89,0 @@ "lodash": "=3.10.1", |
Bitcore Library | ||
============== | ||
======= | ||
@@ -4,0 +4,0 @@ [![NPM Package](https://img.shields.io/npm/v/bitcore-lib.svg?style=flat-square)](https://www.npmjs.org/package/bitcore-lib) |
@@ -52,2 +52,5 @@ 'use strict'; | ||
unit = Unit.fromMillis('1.00001'); | ||
unit.mBTC.should.equal(1.00001); | ||
unit = Unit.fromBits('100'); | ||
@@ -140,2 +143,3 @@ unit.bits.should.equal(100); | ||
unit.toMilis().should.equal(unit.mBTC); | ||
unit.toMillis().should.equal(unit.mBTC); | ||
unit.toBits().should.equal(unit.bits); | ||
@@ -142,0 +146,0 @@ unit.toSatoshis().should.equal(unit.satoshis); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
4104196
7
73709
- Removedhash.js@=1.0.2