UNPKG

2.61 kBMarkdownView Raw
1# Bitcoin Address
2
3Represents 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.
4
5## Instantiate an Address
6
7To 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.
8
9```javascript
10var privateKey = new PrivateKey();
11var address = privateKey.toAddress();
12```
13
14You can also instantiate an Address from a String, [PublicKey](publickey.md), or [HDPublicKey](hierarchical.md), in case you are not the owner of the private key.
15
16```javascript
17// from a string
18var address = Address.fromString('mwkXG8NnB2snbqWTcpNiK6qqGHm1LebHDc');
19
20// a default network address from a public key
21var publicKey = PublicKey(privateKey);
22var address = new Address(publicKey);
23// alternative interface
24var address = Address.fromPublicKey(publicKey);
25
26// a testnet address from a public key
27var publicKey = new PublicKey(privateKey);
28var address = new Address(publicKey, Networks.testnet);
29```
30
31A pay-to-script-hash multisignature Address can be instantiated from an array of [PublicKeys](publickey.md).
32
33```javascript
34// a 2-of-3 address from public keys
35var p2shAddress = new Address([publicKey1, publicKey2, publicKey3], 2);
36```
37
38## Validating an Address
39
40The 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.
41
42The code to do these validations looks like this:
43
44```javascript
45// validate an address
46if (Address.isValid(input){
47 ...
48}
49
50// validate that an input field is a valid testnet address
51if (Address.isValid(input, Networks.testnet){
52 ...
53}
54
55// validate that an input field is a valid livenet pubkeyhash
56if (Address.isValid(input, Networks.livenet, Address.PayToPublicKeyHash){
57 ...
58}
59
60// get the specific validation error that can occurred
61var error = Address.getValidationError(input, Networks.testnet);
62 if (error) {
63 // handle the error
64 }
65}
66```
67
68The errors are listed in the generated file in the [errors folder](https://github.com/bitpay/bitcore/tree/master/packages/bitcore-lib/lib/errors). There's a structure to errors defined in the [spec.js file](https://github.com/bitpay/bitcore/tree/master/packages/bitcore-lib/lib/errors/spec.js).