btcnano-lib
Version:
A pure and powerful JavaScript Btcnano library.
48 lines (35 loc) • 1.8 kB
Markdown
Represents a btcnano private key and is needed to be able to spend btcnano and sign transactions. See the official [Btcnano 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).
Here is how to create a new private key. It will generate a new random number using `window.crypto` or the Node.js `crypto` library.
```javascript
var privateKey = new PrivateKey();
// Creates a private key from a hexa encoded number
var privateKey2 = new PrivateKey('b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79');
```
To export and import a private key, you can do the following:
```javascript
// encode into wallet export format
var exported = privateKey.toWIF();
// instantiate from the exported (and saved) private key
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 btcnano address will be generated by using this format).
To generate an Address or PublicKey from a PrivateKey:
```javascript
var publicKey = privateKey.toPublicKey();
var address = publicKey.toAddress(Networks.livenet);
```
The code to do these validations looks like this:
```javascript
// validate an address
if (PrivateKey.isValid(input)){
...
}
// get the specific validation error that can occurred
var error = PrivateKey.getValidationError(input, Networks.livenet);
if (error) {
// handle the error
}
```