Merge pull request #752 from eordano/review/doc
Update docs and minor changes to codebase
This commit is contained in:
commit
e52be70ed0
@ -1,57 +1,40 @@
|
|||||||
# Address
|
# Address
|
||||||
|
|
||||||
Represents a bitcoin Address. Addresses became the most popular way to make
|
Represents a bitcoin Address. Addresses became the most popular way to make bitcoin transactions. See [the official Bitcoin Wiki](https://en.bitcoin.it/wiki/Address) for more information.
|
||||||
bitcoin transactions. See [the official Bitcoin
|
|
||||||
Wiki](https://en.bitcoin.it/wiki/Address) for more information.
|
|
||||||
|
|
||||||
|
|
||||||
## Instantiate an Address
|
## Instantiate an Address
|
||||||
|
|
||||||
To be able to receive bitcoin an address is needed, here is how to create an
|
To be able to receive bitcoins an address is needed, but in order to spend them a private key is necessary. Take a look at the [`PrivateKey`](PrivateKey.md) docs for more information about exporting and saving a key.
|
||||||
address from a new private key. Please see the [`PrivateKey`](PrivateKey.md) docs
|
|
||||||
for more information about exporting and saving a key.
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
var PrivateKey = require('bitcore/lib/privatekey');
|
|
||||||
var privateKey = new PrivateKey();
|
var privateKey = new PrivateKey();
|
||||||
var address = privateKey.toAddress();
|
var address = privateKey.toAddress();
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also instantiate an address from a String or PublicKey.
|
You can also instantiate an address from a String, `PublicKey`, or [HDPublicKey](Hierarchical.md), in case you are not the owner of the private key.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
var Address = require('bitcore/lib/address');
|
|
||||||
var PublicKey = require('bitcore/lib/publickey');
|
|
||||||
var Networks = require('bitcore/lib/networks');
|
|
||||||
|
|
||||||
// from a string
|
// from a string
|
||||||
var address = Address.fromString('mwkXG8NnB2snbqWTcpNiK6qqGHm1LebHDc');
|
var address = Address.fromString('mwkXG8NnB2snbqWTcpNiK6qqGHm1LebHDc');
|
||||||
|
|
||||||
// a default network address from a public key
|
// a default network address from a public key
|
||||||
var publicKey = PublicKey(privateKey);
|
var publicKey = PublicKey(privateKey);
|
||||||
|
var address = new Address(publicKey);
|
||||||
|
// alternative interface
|
||||||
var address = Address.fromPublicKey(publicKey);
|
var address = Address.fromPublicKey(publicKey);
|
||||||
|
|
||||||
// a testnet address from a public key
|
// a testnet address from a public key
|
||||||
var publicKey = PublicKey(privateKey);
|
var publicKey = new PublicKey(privateKey);
|
||||||
var address = Address.fromPublicKey(publicKey, Networks.testnet);
|
var address = new Address(publicKey, Networks.testnet);
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Validating an Address
|
## Validating an Address
|
||||||
|
|
||||||
The main use that we expect you'll have for the `Address` class in bitcore is
|
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.
|
||||||
validating that an address is a valid one, what type of address it is (you may
|
|
||||||
be interested on knowning 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:
|
The code to do these validations looks like this:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
// validate an address
|
// validate an address
|
||||||
if (Address.isValid(input){
|
if (Address.isValid(input){
|
||||||
...
|
...
|
||||||
@ -73,5 +56,6 @@ var error = Address.getValidationError(input, Networks.testnet);
|
|||||||
// handle the error
|
// handle the error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The errors are listed in the generated file in the [errors folder](https://github.com/bitpay/bitcore/tree/master/lib/errors). There's a structure to errors defined in the [spec.js file](https://github.com/bitpay/bitcore/tree/master/lib/errors/spec.js).
|
||||||
|
|||||||
@ -1,15 +1,8 @@
|
|||||||
# Block
|
# Block
|
||||||
|
|
||||||
A Block instance represents the information on a block in the bitcoin network.
|
A Block instance represents the information on a block in the bitcoin network. Instantiating it is not a cheap operation, as the tree of transactions needs to be created or verified. There's a (BlockHeader)[https://github.com/bitpay/bitcore/tree/master/lib/blockheader.js] interface that is easier on the javascript VM.
|
||||||
Note that creating it takes some computing power, as the tree of transactions
|
|
||||||
is created or verified.
|
|
||||||
|
|
||||||
Given a hexa or base64 string representation of the serialization of a block
|
Given a hexa or base64 string representation of the serialization of a block with its transactions, you can instantiate a Block instance. It will 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.
|
||||||
with its transactions, you can instantiate a Block instance. It will calculate
|
|
||||||
and check the merkle root hash (if enough data is provided), but transactions
|
|
||||||
won't neccesarily 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
|
```javascript
|
||||||
assert(Block.isValidHeader(data);
|
assert(Block.isValidHeader(data);
|
||||||
@ -35,17 +28,3 @@ for (var transaction in block.transactions) {
|
|||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
It is also possible to explore a block's Merkle tree of transaction hashes.
|
|
||||||
Head to the [Merkle tree](./DataStructures.html#MerkleTree) documentation for
|
|
||||||
more information:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
var root = block.tree.root;
|
|
||||||
assert(root instanceof bitcore.DataStructures.MerkleTree.Node);
|
|
||||||
assert(root.hash === block.id);
|
|
||||||
assert(root.isLeaf === false);
|
|
||||||
assert(root.left instanceof bitcore.DataStructures.MerkleTree.Node);
|
|
||||||
assert(root.right instanceof bitcore.DataStructures.MerkleTree.Node);
|
|
||||||
assert(root.left.left.left.left.content === block.transactions[0]);
|
|
||||||
```
|
|
||||||
|
|||||||
@ -1,36 +1,23 @@
|
|||||||
# Crypto
|
# Crypto
|
||||||
|
|
||||||
The cryptographic primitives (ECDSA and HMAC) implementations in this package
|
The cryptographic primitives (ECDSA and HMAC) implementations in this package have been audited bythe BitPay engineering team. More review and certifications are always welcomed.
|
||||||
have been audited by:
|
|
||||||
|
|
||||||
* The BitPay engineering team
|
|
||||||
|
|
||||||
## random
|
## random
|
||||||
|
|
||||||
The `bitcore.Crypto.Random` namespace contains a single function, named
|
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).
|
||||||
`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
|
## bn
|
||||||
|
|
||||||
The `bitcore.Crypto.BN` class contains a wrapper around
|
The `bitcore.Crypto.BN` class contains a wrapper around [bn.js](https://github.com/indutny/bn.js), the bignum library used internally in bitcore.
|
||||||
[bn.js](https://github.com/indutny/bn.js), the bignum library used internally
|
|
||||||
in bitcore.
|
|
||||||
|
|
||||||
## point
|
## point
|
||||||
|
|
||||||
The `bitcore.Crypto.Point` class contains a wrapper around the class Point of
|
The `bitcore.Crypto.Point` class contains a wrapper around the class Point of [elliptic.js](https://github.com/indutny/elliptic.js), the elliptic curve library used internally in bitcore.
|
||||||
[elliptic.js](https://github.com/indutny/elliptic.js), the elliptic curve
|
|
||||||
library used internally in bitcore.
|
|
||||||
|
|
||||||
## hash
|
## hash
|
||||||
|
|
||||||
The `bitcore.Crypto.Hash` namespace contains a set of hashes and utilities.
|
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.
|
||||||
These are either the native `crypto` hash functions from `node.js` or their
|
|
||||||
respective browser shims as provided by the `browserify` library.
|
|
||||||
|
|
||||||
## ecdsa
|
## ecdsa
|
||||||
|
|
||||||
`bitcore.Crypto.ECDSA` contains a pure javascript implementation of the
|
`bitcore.Crypto.ECDSA` contains a pure javascript implementation of the elliptic curve DSA signature scheme.
|
||||||
elliptic curve DSA signature scheme.
|
|
||||||
|
|||||||
@ -1,20 +1,11 @@
|
|||||||
# Encoding
|
# Encoding
|
||||||
|
|
||||||
The `bitcore.Encoding` namespace contains utilities for encoding information in
|
The `bitcore.Encoding` namespace contains utilities for encoding information in common formats in the bitcoin ecosystem.
|
||||||
common formats in the bitcoin ecosystem.
|
|
||||||
|
|
||||||
## Base58
|
## Base58
|
||||||
|
|
||||||
Two classes are provided: `Base58` and `Base58Check`. The first one merely
|
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.
|
||||||
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 checking this checksum when decoding.
|
|
||||||
|
|
||||||
## BufferReader & BufferWriter
|
## BufferReader & BufferWriter
|
||||||
|
|
||||||
These classes are used internally to write information in buffers.
|
These classes are used internally to write information in buffers.
|
||||||
|
|
||||||
## Varint
|
|
||||||
|
|
||||||
The bitcore implementation uses a quite complex way of compressing integers
|
|
||||||
representing the size of fields.
|
|
||||||
|
|||||||
@ -1,12 +1,38 @@
|
|||||||
# Hierarichically Derived Keys
|
# Hierarichically Derived Keys
|
||||||
|
|
||||||
Bitcore provides full support for
|
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.
|
||||||
[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
|
## HDPrivateKey
|
||||||
|
|
||||||
This class initially meant to share the interface of
|
An instance of a [PrivateKey](#PrivateKey.md) that also contains information required to derive child keys.
|
||||||
[PrivateKey](http://missing-link) but add the ability to derive new keys.
|
|
||||||
|
Sample usage:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var hdPrivateKey = new HDPrivateKey();
|
||||||
|
var retrieved = new HDPrivateKey('xpriv...');
|
||||||
|
var derived = privateKey.derive("m/0'");
|
||||||
|
var derivedByNumber = privateKey.derive(1).derive(2, true);
|
||||||
|
var derivedByArgument = privateKey.derive("m/1/2'");
|
||||||
|
assert(derivedByNumber.xprivkey === derivedByArgument.xprivkey);
|
||||||
|
|
||||||
|
var address = new Address(privateKey.publicKey, Networks.livenet);
|
||||||
|
var redeem = new Transaction().from(output).to(target, 10000).sign(derived.privateKey);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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
|
||||||
|
var hdPrivateKey = new HDPrivateKey();
|
||||||
|
var hdPublicKey = privateKey.hdPublicKey;
|
||||||
|
try {
|
||||||
|
new HDPublicKey();
|
||||||
|
} catch(e) {
|
||||||
|
console.log("Can't generate a public key without a private key");
|
||||||
|
}
|
||||||
|
|
||||||
|
var address = new Address(hdPublicKey.publicKey, Networks.livenet);
|
||||||
|
var derivedAddress = new Address(hdPublicKey.derive(100).publicKey, Networks.testnet);
|
||||||
|
```
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
# Input
|
|
||||||
@ -1,23 +1,40 @@
|
|||||||
# Networks
|
# Networks
|
||||||
|
|
||||||
Bitcore provides support for both the main bitcoin network as well as for
|
Bitcore provides support for both 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. Avoid creating a deep copy of this object and using that.
|
||||||
`testnet3`, the current test blockchain. We encourage the use of
|
|
||||||
`Networks.livenet` and `Networks.testnet` as constants. Note that the library
|
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).
|
||||||
sometimes may check for equality against this object. Avoid creating a deep
|
|
||||||
copy of this object and using that.
|
|
||||||
|
|
||||||
## Setting the default network
|
## Setting the default network
|
||||||
|
|
||||||
Most project will only need to work in one of either networks. The value of
|
Most project will only need to work in one of either networks. The value of `Networks.defaultNetwork` can be set to `Networks.testnet` if the project will needs only to work on testnet (the default is `Networks.livenet`).
|
||||||
`Networks.defaultNetwork` can be set to `Networks.testnet` if the project will
|
|
||||||
needs only to work on testnet (the default is `Networks.livenet`).
|
|
||||||
|
|
||||||
## Network constants
|
## Network constants
|
||||||
|
|
||||||
The functionality of testnet and livenet is mostly similar (except for some
|
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.
|
||||||
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.
|
|
||||||
|
|
||||||
## Source
|
Take a look at this modified snippet from (networks.js)[https://github.com/bitpay/bitcore/blob/master/lib/networks.js]
|
||||||
TODO: Include source here
|
```javascript
|
||||||
|
var livenet = new Network();
|
||||||
|
_.extend(livenet, {
|
||||||
|
name: 'livenet',
|
||||||
|
alias: 'mainnet',
|
||||||
|
pubkeyhash: 0x00,
|
||||||
|
privatekey: 0x80,
|
||||||
|
scripthash: 0x05,
|
||||||
|
xpubkey: 0x0488b21e,
|
||||||
|
xprivkey: 0x0488ade4,
|
||||||
|
port: 8333
|
||||||
|
});
|
||||||
|
|
||||||
|
var testnet = new Network();
|
||||||
|
_.extend(testnet, {
|
||||||
|
name: 'testnet',
|
||||||
|
alias: 'testnet',
|
||||||
|
pubkeyhash: 0x6f,
|
||||||
|
privatekey: 0xef,
|
||||||
|
scripthash: 0xc4,
|
||||||
|
xpubkey: 0x043587cf,
|
||||||
|
xprivkey: 0x04358394,
|
||||||
|
port: 18333
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
# Opcode
|
|
||||||
@ -1 +0,0 @@
|
|||||||
# Output
|
|
||||||
@ -7,22 +7,20 @@ Represents a bitcoin private key and is needed to be able to spend bitcoin and s
|
|||||||
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.
|
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
|
```javascript
|
||||||
|
|
||||||
var PrivateKey = require('bitcore/lib/privatekey');
|
|
||||||
var privateKey = new PrivateKey();
|
var privateKey = new PrivateKey();
|
||||||
|
|
||||||
|
// Creates a private key from a hexa encoded number
|
||||||
|
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79');
|
||||||
```
|
```
|
||||||
|
|
||||||
To export and import a private key, you can do the following:
|
To export and import a private key, you can do the following:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
// encode into wallet export format
|
// encode into wallet export format
|
||||||
var exported = privateKey.toWIF();
|
var exported = privateKey.toWIF();
|
||||||
|
|
||||||
// instantiate from the exported (and saved) private key
|
// instantiate from the exported (and saved) private key
|
||||||
var imported = PrivateKey.fromWIF('L3T1s1TYP9oyhHpXgkyLoJFGniEgkv2Jhi138d7R2yJ9F4QdDU2m');
|
var imported = PrivateKey.fromWIF('L3T1s1TYP9oyhHpXgkyLoJFGniEgkv2Jhi138d7R2yJ9F4QdDU2m');
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: The WIF (Wallet Import Format) includes information about the network and if the associated public key is compressed or uncompressed (thus the same bitcoin address will be generated by using this format).
|
Note: The WIF (Wallet Import Format) includes information about the network and if the associated public key is compressed or uncompressed (thus the same bitcoin address will be generated by using this format).
|
||||||
@ -30,10 +28,8 @@ Note: The WIF (Wallet Import Format) includes information about the network and
|
|||||||
To generate an Address or PublicKey from a PrivateKey:
|
To generate an Address or PublicKey from a PrivateKey:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
var address = privateKey.toAddress();
|
|
||||||
var publicKey = privateKey.toPublicKey();
|
var publicKey = privateKey.toPublicKey();
|
||||||
|
var address = publicKey.toAddress(Networks.livenet);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Validating a Private Key
|
## Validating a Private Key
|
||||||
@ -41,7 +37,6 @@ var publicKey = privateKey.toPublicKey();
|
|||||||
The code to do these validations looks like this:
|
The code to do these validations looks like this:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
|
||||||
// validate an address
|
// validate an address
|
||||||
if (PrivateKey.isValid(input)){
|
if (PrivateKey.isValid(input)){
|
||||||
...
|
...
|
||||||
@ -52,5 +47,4 @@ var error = PrivateKey.getValidationError(input, Networks.livenet);
|
|||||||
if (error) {
|
if (error) {
|
||||||
// handle the error
|
// handle the error
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,25 +1,13 @@
|
|||||||
# Script
|
# Script
|
||||||
|
|
||||||
All bitcoin transactions have scripts embedded into its inputs and outputs.
|
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).
|
||||||
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
|
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.
|
||||||
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
|
For more detailed information about the bitcoin scripting language, check the online reference (on bitcoin's wiki)[https://en.bitcoin.it/wiki/Script].
|
||||||
online reference: 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`.
|
|
||||||
|
|
||||||
|
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
|
## Script creation
|
||||||
|
|
||||||
@ -27,39 +15,30 @@ Here's how to use `Script` to create the five most common script types:
|
|||||||
|
|
||||||
### Pay to Public Key Hash (p2pkh)
|
### Pay to Public Key Hash (p2pkh)
|
||||||
|
|
||||||
This is the most commonly used transaction output script. It's used to pay to
|
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)
|
||||||
a bitcoin address (a bitcoin address is a public key hash encoded in base58check)
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// create a new p2pkh paying to a specific address
|
// create a new p2pkh paying to a specific address
|
||||||
var address = Address.fromString('1NaTVwXDDUJaXDQajoa9MqHhz4uTxtgK14');
|
var address = Address.fromString('1NaTVwXDDUJaXDQajoa9MqHhz4uTxtgK14');
|
||||||
var s = Script.buildPublicKeyHashOut(address);
|
var script = Script.buildPublicKeyHashOut(address);
|
||||||
console.log(s.toString());
|
assert(script.toString() === 'OP_DUP OP_HASH160 20 0xecae7d092947b7ee4998e254aa48900d26d2ce1d OP_EQUALVERIFY OP_CHECKSIG');
|
||||||
// 'OP_DUP OP_HASH160 20 0xecae7d092947b7ee4998e254aa48900d26d2ce1d OP_EQUALVERIFY OP_CHECKSIG'
|
|
||||||
```
|
```
|
||||||
### Pay to Public Key (p2pk)
|
### Pay to Public Key (p2pk)
|
||||||
|
|
||||||
Pay to public key scripts are a simplified form of the p2pkh,
|
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).
|
||||||
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
|
```javascript
|
||||||
// create a new p2pk paying to a specific public key
|
// create a new p2pk paying to a specific public key
|
||||||
var pubkey = new PublicKey('022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da');
|
var pubkey = new PublicKey('022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da');
|
||||||
var s = Script.buildPublicKeyOut(pubkey);
|
var script = Script.buildPublicKeyOut(pubkey);
|
||||||
console.log(s.toString());
|
assert(script.toString() === '33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da OP_CHECKSIG');
|
||||||
// '33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da OP_CHECKSIG'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Pay to Multisig (p2ms)
|
### Pay to Multisig (p2ms)
|
||||||
|
|
||||||
Multisig outputs allow to share control of bitcoins between several keys. When creating
|
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.)
|
||||||
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
|
Note that regular multisig outputs are rarely used nowadays. The best practice is to use a p2sh multisig output (See Script#toScriptHashOut()).
|
||||||
is to use a p2sh multisig output (See Script#toScriptHashOut()).
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// create a new 2-of-3 multisig output from 3 given public keys
|
// create a new 2-of-3 multisig output from 3 given public keys
|
||||||
@ -68,19 +47,16 @@ var pubkeys = [
|
|||||||
new PublicKey('03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9'),
|
new PublicKey('03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9'),
|
||||||
new PublicKey('021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18'),
|
new PublicKey('021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18'),
|
||||||
];
|
];
|
||||||
var m = 2;
|
var threshold = 2;
|
||||||
var s = Script.buildMultisigOut(pubkeys, m);
|
var script = Script.buildMultisigOut(pubkeys, threshold);
|
||||||
console.log(s.toString());
|
assert(script.toString() === 'OP_2 33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da'
|
||||||
// 'OP_2 33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da 33 0x03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9 33 0x021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18 OP_3 OP_CHECKMULTISIG'
|
+ ' 33 0x03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9'
|
||||||
|
+ ' 33 0x021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18 OP_3 OP_CHECKMULTISIG');
|
||||||
```
|
```
|
||||||
|
|
||||||
### Pay to Script Hash (p2sh)
|
### Pay to Script Hash (p2sh)
|
||||||
|
|
||||||
Pay to script hash outputs are scripts that contain the hash of another script, called redeemScript.
|
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.
|
||||||
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.
|
Most multisig transactions today use p2sh outputs where the redeemScript is a multisig output.
|
||||||
|
|
||||||
@ -92,44 +68,38 @@ var pubkeys = [
|
|||||||
new PublicKey('021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18'),
|
new PublicKey('021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18'),
|
||||||
];
|
];
|
||||||
var redeemScript = Script.buildMultisigOut(pubkeys, 2);
|
var redeemScript = Script.buildMultisigOut(pubkeys, 2);
|
||||||
var s = redeemScript.toScriptHashOut();
|
var script = redeemScript.toScriptHashOut();
|
||||||
console.log(s.toString());
|
assert(script.toString() === 'OP_HASH160 20 0x620a6eeaf538ec9eb89b6ae83f2ed8ef98566a03 OP_EQUAL');
|
||||||
// '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
|
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.
|
||||||
in a standard way, but more data can be used, if a miner decides to accept the transaction.
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var data = 'hello world!!!';
|
var data = 'hello world!!!';
|
||||||
var s = Script.buildDataOut(data);
|
var script = Script.buildDataOut(data);
|
||||||
console.log(s.toString());
|
assert(script.toString() === 'OP_RETURN 14 0x68656c6c6f20776f726c64212121'
|
||||||
// 'OP_RETURN 14 0x68656c6c6f20776f726c64212121'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Custom scripts
|
### Custom scripts
|
||||||
|
|
||||||
To create a custom `Script` instance, you must rely on the lower-level methods `add`
|
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`.
|
||||||
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`.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
var s = Script()
|
var script = Script()
|
||||||
.add('OP_IF') // add an opcode by name
|
.add('OP_IF') // add an opcode by name
|
||||||
.prepend(114) // add OP_2SWAP by code
|
.prepend(114) // add OP_2SWAP by code
|
||||||
.add(new Opcode('OP_NOT')) // add an opcode object
|
.add(Opcode.OP_NOT) // add an opcode object
|
||||||
.add(new Buffer('bacacafe', 'hex')) // add a data buffer
|
.add(new Buffer('bacacafe', 'hex')) // add a data buffer (will append the size of the push operation first)
|
||||||
console.log(s.toString());
|
|
||||||
// 'OP_2SWAP OP_IF OP_NOT 4 0xbacacafe'
|
assert(script.toString() === 'OP_2SWAP OP_IF OP_NOT 4 0xbacacafe');
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Script parsing and identification
|
## Script parsing and identification
|
||||||
|
|
||||||
`Script` has an easy interface to parse raw scripts from the newtwork or bitcoind,
|
`Script` has an easy interface to parse raw scripts from the newtwork or bitcoind, and to extract useful information. An illustrative example (for more options check the API reference)
|
||||||
and to extract useful information.
|
|
||||||
An illustrative example (for more options check the API reference)
|
|
||||||
```javascript
|
```javascript
|
||||||
var raw_script = new Buffer('5221022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da2103e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e921021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc1853ae', 'hex');
|
var raw_script = new Buffer('5221022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da2103e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e921021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc1853ae', 'hex');
|
||||||
var s = new Script(raw_script);
|
var s = new Script(raw_script);
|
||||||
@ -139,5 +109,4 @@ console.log(s.toString());
|
|||||||
s.isPublicKeyHashOut() // false
|
s.isPublicKeyHashOut() // false
|
||||||
s.isScriptHashOut() // false
|
s.isScriptHashOut() // false
|
||||||
s.isMultisigOut() // true
|
s.isMultisigOut() // true
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
# Signature
|
|
||||||
@ -1,25 +1,12 @@
|
|||||||
# Transaction
|
# Transaction
|
||||||
|
|
||||||
Bitcore provides a very simple API for creating transactions. We expect this
|
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. What follows is a small introduction to transactions with some basic knowledge required to use this API.
|
||||||
API to be accessible for developers without knowing the working internals of
|
|
||||||
bitcoin in deep. 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
|
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 ouput to be used in this transaction.
|
||||||
contains a reference to another transaction's output, and a signature
|
|
||||||
that allows the value referenced in that ouput to be used in this transaction.
|
|
||||||
|
|
||||||
Note also that an output can be used only once. That's why there's a concept of
|
Note also that an output can be used only once. That's why there's a concept of "change address" in the bitcoin ecosystem: if an output of 10 BTC is available for me to spend, but I only need to transmit 1 BTC, I'll create a transaction with two outputs, one with 1 BTC that I want to spend, and the other with 9 BTC to a change address, so I can spend this 9 BTC with another private key that I own.
|
||||||
"change address" in the bitcoin ecosystem: if an output of 10 BTC is available
|
|
||||||
for me to spend, but I only need to transmit 1 BTC, I'll create a transaction
|
|
||||||
with two outputs, one with 1 BTC that I want to spend, and the other with 9 BTC
|
|
||||||
to a change address, so I can spend this 9 BTC with another private key that I
|
|
||||||
own.
|
|
||||||
|
|
||||||
So, in order to transmit a valid transaction, you must know what other transactions
|
So, in order to transmit a valid transaction, you must know what other transactions on the network store outputs that have not been spent and that are available for you to spend (meaning that you have the set of keys that can validate you own those funds). The unspent outputs are usually referred to as "utxo"s.
|
||||||
on the network store outputs that have not been spent and that are available
|
|
||||||
for you to spend (meaning that you have the set of keys that can validate you
|
|
||||||
own those funds). The unspent outputs are usually referred to as "utxo"s.
|
|
||||||
|
|
||||||
Let's take a look at some very simple transactions:
|
Let's take a look at some very simple transactions:
|
||||||
|
|
||||||
@ -29,15 +16,9 @@ var transaction = new Transaction()
|
|||||||
.to(address, amount) // Add an output with the given amount of satoshis
|
.to(address, amount) // Add an output with the given amount of satoshis
|
||||||
.change(address) // Sets up a change address where the rest of the funds will go
|
.change(address) // Sets up a change address where the rest of the funds will go
|
||||||
.sign(privkeySet) // Signs all the inputs it can
|
.sign(privkeySet) // Signs all the inputs it can
|
||||||
|
|
||||||
var transaction2 = new Transaction()
|
|
||||||
.from(utxos) // Feed information about what unspend outputs one can use
|
|
||||||
.spendAllTo(address) // Spends all outputs into one address
|
|
||||||
.sign(privkeySet) // Signs all the inputs it can
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Now, one could just serialize this transaction in hexadecimal ASCII values
|
Now, this could just be serialized to hexadecimal ASCII values (`transaction.serialize()`) and sent over to the bitcoind reference client.
|
||||||
(`transaction.serialize()`) and send it over to the bitcoind reference client.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bitcoin-cli sendrawtransaction <serialized transaction>
|
bitcoin-cli sendrawtransaction <serialized transaction>
|
||||||
@ -45,19 +26,23 @@ bitcoin-cli sendrawtransaction <serialized transaction>
|
|||||||
|
|
||||||
## Transaction API
|
## Transaction API
|
||||||
|
|
||||||
You can take a look at the javadocs for the [Transaction class here](link
|
You can take a look at the javadocs for the [Transaction class here](link missing).
|
||||||
missing).
|
|
||||||
|
## Input
|
||||||
|
|
||||||
|
Transaction inputs are instances of either [Input](https://github.com/bitpay/bitcore/tree/master/lib/transaction/input) or its subclasses. The internal workings of it can be understood from the [API reference](link missing).
|
||||||
|
|
||||||
|
## Output
|
||||||
|
|
||||||
|
Transaction outputs are a very thin wrap around the information provided by a transaction output: its script and its output amount.
|
||||||
|
|
||||||
## Multisig Transactions
|
## Multisig Transactions
|
||||||
|
|
||||||
To send a transaction to a multisig address, the API is the same as in the
|
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.
|
||||||
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
|
```javascript
|
||||||
var multiSigTx = new Transaction()
|
var multiSigTx = new Transaction()
|
||||||
.fromMultisig(utxo, publicKeys, threshold)
|
.from(utxo, publicKeys, threshold)
|
||||||
.change(address)
|
.change(address)
|
||||||
.sign(myKeys);
|
.sign(myKeys);
|
||||||
|
|
||||||
@ -69,6 +54,8 @@ signatures:
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var multiSigTx = new Transaction(serialized)
|
var multiSigTx = new Transaction(serialized)
|
||||||
|
.from(utxo, publicKeys, threshold) // provide info about the multisig output
|
||||||
|
// (lost on serialization)
|
||||||
.sign(anotherSetOfKeys);
|
.sign(anotherSetOfKeys);
|
||||||
|
|
||||||
assert(multiSigTx.isFullySigned());
|
assert(multiSigTx.isFullySigned());
|
||||||
@ -78,60 +65,23 @@ signatures:
|
|||||||
|
|
||||||
### Internal Workings
|
### Internal Workings
|
||||||
|
|
||||||
There are a number of data structures being stored internally in a
|
There are a number of data structures being stored internally in a `Transaction` instance. These are kept up to date and change through successive calls to its methods.
|
||||||
`Transaction` instance. These are kept up to date and change through successive
|
|
||||||
calls to its methods.
|
|
||||||
|
|
||||||
* `inputs`: The ordered set of inputs for this transaction
|
* `inputs`: The ordered set of inputs for this transaction
|
||||||
* `outputs`: This is the ordered set of output scripts
|
* `outputs`: This is the ordered set of output scripts
|
||||||
* `_outpoints`: The ordered set of outpoints (a string that combines a
|
* `_inputAmount`: sum of the amount for all the inputs
|
||||||
transaction hash and output index), UTXOs that will be inputs to this
|
* `_outputAmount`: sum of the amount for all the outputs
|
||||||
transaction. This gets populated on calls to `from` and also when
|
|
||||||
deserializing from a serialized transaction.
|
|
||||||
* `_utxos`: Maps an outpoint to information regarding the output on that
|
|
||||||
transaction. The values of an output are:
|
|
||||||
- script: the associated script for this output. Will be an instance of
|
|
||||||
`Script`
|
|
||||||
- satoshis: amount of satoshis associated with this output
|
|
||||||
- txId: the transaction id from the outpoint
|
|
||||||
- outputIndex: the index of this output in the previous transaction
|
|
||||||
* `_inputAmount`: sum the amount for all the inputs
|
|
||||||
* `_signatures`: This is the ordered set of `scriptSig`s that are going to be
|
|
||||||
included in the serialized transaction. These are objects with the following
|
|
||||||
values:
|
|
||||||
- publicKey: the public key that generated the signature
|
|
||||||
- prevTxId: the previous transaction hash
|
|
||||||
- outputIndex: the index for the output that this input is signing
|
|
||||||
- signature: the `Signature` for that public key
|
|
||||||
- sigtype: the type of the signature (`Signature.SIGHASH_ALL` is the only one implemented)
|
|
||||||
* `_change`: stores the value provided by calling the `change` method.
|
|
||||||
|
|
||||||
TO BE IMPLEMENTED YET:
|
TO BE IMPLEMENTED YET:
|
||||||
* `_fee`: if user specified a non-standard fee, the amount (in satoshis) will
|
* `_fee`: if user specified a non-standard fee, the amount (in satoshis) will be stored in this variable so the change amount can be calculated.
|
||||||
be stored in this variable so the change amount can be calculated.
|
* `_change`: stores the value provided by calling the `change` method.
|
||||||
* `_p2shMap`: For the case of P2SH spending, the user needs to supply
|
|
||||||
information about the script that hashes to the hash of an UTXO. This map
|
|
||||||
goes from the hash of the spend script to that script. When using the
|
|
||||||
`from(utxo, publicKeys, threshold)` function, this map gets populated with a
|
|
||||||
standard multisig spend script with public keys in the order provided.
|
|
||||||
|
|
||||||
### Unspent Output Selection
|
### Unspent Output Selection
|
||||||
|
|
||||||
If you have a larger set of unspent outputs, only some of them will be selected
|
If you have a larger set of unspent outputs, only some of them will be selected to fulfill the amount. This is done by storing a cache of unspent outputs in a protected member called `_utxos`. When the `to()` method is called, some of these outputs will be selected to pay the requested amount to the appropriate address.
|
||||||
to fulfill the amount. This is done by storing a cache of unspent outputs in a
|
|
||||||
protected member called `_utxos`. When the `to()` method is called, some of
|
|
||||||
these outputs will be selected to pay the requested amount to the appropriate
|
|
||||||
address.
|
|
||||||
|
|
||||||
A nit that you should have in mind is that when the transaction is serialized,
|
A nit that you should have in mind is that when the transaction is serialized, this cache can't be included in the serialized form.
|
||||||
this cache can't be included in the serialized form.
|
|
||||||
|
|
||||||
## Upcoming changes
|
## Upcoming changes
|
||||||
|
|
||||||
We're debating an API for Merge Avoidance, CoinJoin, Smart contracts, CoinSwap,
|
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 early 2015. First draft implementations of Payment Channel smart contracts extensions to this library are already being implemented independently.
|
||||||
and Stealth Addresses. We're expecting to have all of them by some time in
|
|
||||||
early 2015.
|
|
||||||
|
|
||||||
A first draft of a Payment Channel smart contract modular extension to this
|
|
||||||
library is being implemented independently
|
|
||||||
(https://github.com/eordano/bitcore-channel).
|
|
||||||
|
|||||||
18
docs/URI.md
18
docs/URI.md
@ -1,7 +1,6 @@
|
|||||||
# URI
|
# URI
|
||||||
|
|
||||||
Represents a bitcoin payment uri. Bitcoin URI strings became the most popular
|
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.
|
||||||
way to share payment request, sometimes as a bitcoin link and others using a QR code.
|
|
||||||
|
|
||||||
URI Examples:
|
URI Examples:
|
||||||
```
|
```
|
||||||
@ -10,9 +9,7 @@ bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2
|
|||||||
bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2&message=Payment&label=Satoshi&extra=other-param
|
bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2&message=Payment&label=Satoshi&extra=other-param
|
||||||
```
|
```
|
||||||
|
|
||||||
The main use that we expect you'll have for the `URI` class in bitcore is
|
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.
|
||||||
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:
|
The code for validating uris looks like this:
|
||||||
```javascript
|
```javascript
|
||||||
@ -22,16 +19,11 @@ var uri = new URI(uriString);
|
|||||||
console.log(uri.address.network, uri.amount); // 'livenet', 120000000
|
console.log(uri.address.network, uri.amount); // 'livenet', 120000000
|
||||||
```
|
```
|
||||||
|
|
||||||
All standard parameters can be found as members of the `URI` instance. However
|
All standard parameters can be found as members of the `URI` instance. However a bitcoin uri may contain other non-standard parameters, all those can be found under the `extra` namespace.
|
||||||
a bitcoin uri may contain other non-standard parameters, all those can be found
|
|
||||||
under the `extra` namespace.
|
|
||||||
|
|
||||||
See [the official BIP21 spec](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki)
|
See [the official BIP21 spec](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki) for more information.
|
||||||
for more information.
|
|
||||||
|
|
||||||
Other usecase important usecase for the `URI` class is creating a bitcoin URI for
|
Other usecase important usecase for the `URI` class is creating a bitcoin URI for sharing a payment request. That can be acomplished by using an Object to create an instance of URI.
|
||||||
sharing a payment request. That can be acomplished by using an Object to create
|
|
||||||
an instance of URI.
|
|
||||||
|
|
||||||
The code for creating an URI from an Object looks like this:
|
The code for creating an URI from an Object looks like this:
|
||||||
```javascript
|
```javascript
|
||||||
|
|||||||
17
docs/Unit.md
17
docs/Unit.md
@ -1,22 +1,18 @@
|
|||||||
# Unit
|
# Unit
|
||||||
|
|
||||||
Unit it's a utility for handling and converting bitcoins units. We strongly
|
Unit is an utility for handling and converting bitcoins units. We strongly recommend you to always use satoshis to represent amount inside your application and only convert them to other units in the front-end.
|
||||||
recommend you to always use satoshis to represent amount inside your application
|
|
||||||
and only convert them to other units in the front-end.
|
|
||||||
|
|
||||||
The supported units are BTC, mBTC, bits and satoshis. The codes for each unit
|
The supported units are BTC, mBTC, bits and satoshis. The codes for each unit can be found as members of the Unit class.
|
||||||
can be found as members of the Unit class.
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var btcCode = Unit.BTC;
|
var btcCode = Unit.BTC;
|
||||||
var mbtcCode = Unit.mBTC;
|
var mbtcCode = Unit.mBTC;
|
||||||
|
var ubtcCode = Unit.uBTC;
|
||||||
var bitsCode = Unit.bits;
|
var bitsCode = Unit.bits;
|
||||||
var satsCode = Unit.satoshis;
|
var satsCode = Unit.satoshis;
|
||||||
```
|
```
|
||||||
|
|
||||||
There are two ways for creating a unit instance. You can instanciate the class
|
There are two ways for creating a unit instance. You can instanciate 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:
|
||||||
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
|
```javascript
|
||||||
var unit;
|
var unit;
|
||||||
@ -33,10 +29,7 @@ unit = Unit.fromBits(amount);
|
|||||||
unit = Unit.fromSatoshis(amount);
|
unit = Unit.fromSatoshis(amount);
|
||||||
```
|
```
|
||||||
|
|
||||||
Once you have a unit instance, you can check it's representantion in all the
|
Once you have a unit instance, you can check it's representantion in all the available units. For your convinience the classes expose three ways to acomplish this. Using the `.to(unitCode)` method, using a fixed unit like `.toSatoshis()` or by using the accessors.
|
||||||
available units. For your convinience the classes expose three ways to acomplish
|
|
||||||
this. Using the `.to(unitCode)` method, using a fixed unit like `.toSatoshis()`
|
|
||||||
or by using the accessors.
|
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var unit;
|
var unit;
|
||||||
|
|||||||
25
lib/block.js
25
lib/block.js
@ -24,6 +24,7 @@ var Block = function Block(arg) {
|
|||||||
return new Block(arg);
|
return new Block(arg);
|
||||||
}
|
}
|
||||||
_.extend(this, Block._from(arg));
|
_.extend(this, Block._from(arg));
|
||||||
|
this._setupProperties();
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -53,6 +54,29 @@ Block._from = function _from(arg) {
|
|||||||
return info;
|
return info;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal function that sets up a some properties from blockheader for
|
||||||
|
* easier access
|
||||||
|
*/
|
||||||
|
Block.prototype._setupProperties = function() {
|
||||||
|
Object.defineProperty(this, 'version', {
|
||||||
|
configurable: false,
|
||||||
|
value: this.blockheader.version
|
||||||
|
});
|
||||||
|
Object.defineProperty(this, 'timestamp', {
|
||||||
|
configurable: false,
|
||||||
|
value: this.blockheader.timestamp
|
||||||
|
});
|
||||||
|
Object.defineProperty(this, 'nonce', {
|
||||||
|
configurable: false,
|
||||||
|
value: this.blockheader.nonce
|
||||||
|
});
|
||||||
|
Object.defineProperty(this, 'size', {
|
||||||
|
configurable: false,
|
||||||
|
value: this.blockheader.size
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {String|Object} - A JSON string or object
|
* @param {String|Object} - A JSON string or object
|
||||||
* @returns {Object} - An object representing block data
|
* @returns {Object} - An object representing block data
|
||||||
@ -236,7 +260,6 @@ Block.prototype.getMerkleTree = function getMerkleTree() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return tree;
|
return tree;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -40,8 +40,10 @@ BlockHeader._from = function _from(arg) {
|
|||||||
info = {
|
info = {
|
||||||
version: arg.version,
|
version: arg.version,
|
||||||
prevblockidbuf: arg.prevblockidbuf,
|
prevblockidbuf: arg.prevblockidbuf,
|
||||||
|
prevHash: arg.prevblockidbuf,
|
||||||
merklerootbuf: arg.merklerootbuf,
|
merklerootbuf: arg.merklerootbuf,
|
||||||
time: arg.time,
|
time: arg.time,
|
||||||
|
timestamp: arg.time,
|
||||||
bits: arg.bits,
|
bits: arg.bits,
|
||||||
nonce: arg.nonce
|
nonce: arg.nonce
|
||||||
};
|
};
|
||||||
@ -63,8 +65,10 @@ BlockHeader._fromJSON = function _fromJSON(data) {
|
|||||||
var info = {
|
var info = {
|
||||||
version: data.version,
|
version: data.version,
|
||||||
prevblockidbuf: new Buffer(data.prevblockidbuf, 'hex'),
|
prevblockidbuf: new Buffer(data.prevblockidbuf, 'hex'),
|
||||||
|
prevHash: new Buffer(data.prevblockidbuf, 'hex'),
|
||||||
merklerootbuf: new Buffer(data.merklerootbuf, 'hex'),
|
merklerootbuf: new Buffer(data.merklerootbuf, 'hex'),
|
||||||
time: data.time,
|
time: data.time,
|
||||||
|
timestamp: data.time,
|
||||||
bits: data.bits,
|
bits: data.bits,
|
||||||
nonce: data.nonce
|
nonce: data.nonce
|
||||||
};
|
};
|
||||||
|
|||||||
@ -48,6 +48,7 @@ function Unit(amount, code) {
|
|||||||
var UNITS = {
|
var UNITS = {
|
||||||
'BTC' : [1e8, 8],
|
'BTC' : [1e8, 8],
|
||||||
'mBTC' : [1e5, 5],
|
'mBTC' : [1e5, 5],
|
||||||
|
'uBTC' : [1e2, 2],
|
||||||
'bits' : [1e2, 2],
|
'bits' : [1e2, 2],
|
||||||
'satoshis' : [1, 0]
|
'satoshis' : [1, 0]
|
||||||
};
|
};
|
||||||
@ -95,7 +96,7 @@ Unit.fromMilis = function(amount) {
|
|||||||
* @param {Number} amount - The amount in bits
|
* @param {Number} amount - The amount in bits
|
||||||
* @returns {Unit} A Unit instance
|
* @returns {Unit} A Unit instance
|
||||||
*/
|
*/
|
||||||
Unit.fromBits = function(amount) {
|
Unit.fromMicros = Unit.fromBits = function(amount) {
|
||||||
return new Unit(amount, Unit.bits);
|
return new Unit(amount, Unit.bits);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -152,7 +153,7 @@ Unit.prototype.toMilis = function(code) {
|
|||||||
*
|
*
|
||||||
* @returns {Number} The value converted to bits
|
* @returns {Number} The value converted to bits
|
||||||
*/
|
*/
|
||||||
Unit.prototype.toBits = function(code) {
|
Unit.prototype.toMicros = Unit.prototype.toBits = function(code) {
|
||||||
return this.to(Unit.bits);
|
return this.to(Unit.bits);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user