### blockstack

`0.16.1`
Need help reading this?

## Authentication

Single sign on and authentication without third parties or remote servers.

Read more about authentication

### redirectToSignIn

Generates an authentication request and redirects the user to the Blockstack browser to approve the sign in request.

Please note that this requires that the web browser properly handles the `blockstack:` URL protocol handler.

Most applications should use this method for sign in unless they require more fine grained control over how the authentication request is generated. If your app falls into this category, use `generateAndStoreTransitKey`, `makeAuthRequest`, and `redirectToSignInWithAuthRequest` to build your own sign in process.

redirectToSignIn(redirectURI: String, manifestURI: String, scopes: Array): void
Parameters
redirectURI `(String = ``${window.location.origin}/``)` The location to which the identity provider will redirect the user after the user approves sign in.
manifestURI `(String = ``${window.location.origin}/manifest.json``)` Location of the manifest file.
scopes `(Array = `DEFAULT_SCOPE`)` Defaults to requesting write access to this app's data store. An array of strings indicating which permissions this app is requesting.
Returns
`void`:

### isSignInPending

Check if there is a authentication request that hasn't been handled.

isSignInPending(): Boolean
Returns
`Boolean`: `true` if there is a pending sign in, otherwise `false`

### handlePendingSignIn

Try to process any pending sign in request by returning a `Promise` that resolves to the user data object if the sign in succeeds.

handlePendingSignIn(nameLookupURL: String): Promise
Parameters
nameLookupURL `(String = `'https://core.blockstack.org/v1/names/'`)` the endpoint against which to verify public keys match claimed username
Returns
`Promise`: that resolves to the user data object if successful and rejects if handling the sign in request fails or there was no pending sign in request.

### loadUserData

Retrieves the user data object. The user's profile is stored in the key `profile`.

loadUserData(): Object
Returns
`Object`: User data object.

### isUserSignedIn

Check if a user is currently signed in.

isUserSignedIn(): Boolean
Returns
`Boolean`: `true` if the user is signed in, `false` if not.

### signUserOut

Sign the user out and optionally redirect to given location.

signUserOut(redirectURL: String): void
Parameters
redirectURL `(String = `null`)` Location to redirect user to after sign out.
Returns
`void`:

### makeAuthRequest

Generates an authentication request that can be sent to the Blockstack browser for the user to approve sign in. This authentication request can then be used for sign in by passing it to the `redirectToSignInWithAuthRequest` method.

Note: This method should only be used if you want to roll your own authentication flow. Typically you'd use `redirectToSignIn` which takes care of this under the hood.

makeAuthRequest(transitPrivateKey: String, redirectURI: String, manifestURI: String, scopes: Array<String>, appDomain: String, expiresAt: Number): String
Parameters
transitPrivateKey `(String = `generateAndStoreTransitKey()`)` hex encoded transit private key
redirectURI `(String = ``${window.location.origin}/``)` location to redirect user to after sign in approval
manifestURI `(String = ``${window.location.origin}/manifest.json``)` location of this app's manifest file
scopes `(Array<String> = `DEFAULT_SCOPE`)` the permissions this app is requesting
appDomain `(String = `window.location.origin`)` the origin of this app
expiresAt `(Number = `nextHour().getTime()`)` the time at which this request is no longer valid
Returns
`String`: the authentication request

### redirectToSignInWithAuthRequest

Redirects the user to the Blockstack browser to approve the sign in request given.

The user is redirected to the `blockstackIDHost` if the `blockstack:` protocol handler is not detected. Please note that the protocol handler detection does not work on all browsers.

redirectToSignInWithAuthRequest(authRequest: String, blockstackIDHost: String): void
Parameters
authRequest `(String = `makeAuthRequest()`)` the authentication request generated by `makeAuthRequest`
blockstackIDHost `(String = `DEFAULT_BLOCKSTACK_HOST`)` the URL to redirect the user to if the blockstack protocol handler is not detected
Returns
`void`:

### getAuthResponseToken

Retrieve the authentication token from the URL query

getAuthResponseToken(): String
Returns
`String`: the authentication token if it exists otherwise `null`

## Profiles

Identity you own and control.

Read more about profiles

### extractProfile

Extracts a profile from an encoded token and optionally verifies it, if `publicKeyOrAddress` is provided.

extractProfile(token: String, publicKeyOrAddress: String): Object
Parameters
token `(String)` the token to be extracted
publicKeyOrAddress `(String = `null`)` the public key or address of the keypair that is thought to have signed the token
Returns
`Object`: the profile extracted from the encoded token
Throws

- Error: if the token isn't signed by the provided `publicKeyOrAddress`

### wrapProfileToken

Wraps a token for a profile token file

wrapProfileToken(token: String): Object
Parameters
token `(String)` the token to be wrapped
Returns
`Object`: including `token` and `decodedToken`

### signProfileToken

Signs a profile token

signProfileToken(profile: Object, privateKey: String, subject: Object, issuer: Object, signingAlgorithm: String, issuedAt: Date, expiresAt: Date): Object
Parameters
profile `(Object)` the JSON of the profile to be signed
privateKey `(String)` the signing private key
subject `(Object = `null`)` the entity that the information is about
issuer `(Object = `null`)` the entity that is issuing the token
signingAlgorithm `(String = `'ES256K'`)` the signing algorithm to use
issuedAt `(Date = `new Date()`)` the time of issuance of the token
expiresAt `(Date = `nextYear()`)` the time of expiration of the token
Returns
`Object`: the signed profile token

### verifyProfileToken

Verifies a profile token

verifyProfileToken(token: String, publicKeyOrAddress: String): Object
Parameters
token `(String)` the token to be verified
publicKeyOrAddress `(String)` the public key or address of the keypair that is thought to have signed the token
Returns
`Object`: the verified, decoded profile token
Throws

- Error: throws an error if token verification fails

### validateProofs

Validates the social proofs in a user's profile. Currently supports validation of Facebook, Twitter, GitHub, Instagram, LinkedIn and HackerNews accounts.

validateProofs(profile: Object, ownerAddress: string, name: string): Promise
Parameters
profile `(Object)` The JSON of the profile to be validated
ownerAddress `(string)` The owner bitcoin address to be validated
name `(string = `null`)` The Blockstack name to be validated
Returns
`Promise`: that resolves to an array of validated proof objects

### lookupProfile

Look up a user profile by blockstack ID

lookupProfile(username: string, zoneFileLookupURL: string): Promise
Parameters
username `(string)` The Blockstack ID of the profile to look up
zoneFileLookupURL `(string = `https://core.blockstack.org/v1/names/`)` The URL to use for zonefile lookup
Returns
`Promise`: that resolves to a profile object

## Storage

Store your app's data without servers in storage your user controls.

Note: Blockstack Gaia Storage APIs and on-disk format will change in upcoming pre-releases breaking backward compatibility. File encryption is currently opt-in on a file by file basis.

Certain storage features such as and collections are not implemented in the current version. These features will be rolled out in future updates.

Read more about storage

### getFile

Retrieves the specified file from the app's data store.

getFile(path: String, options: Object): Promise
Parameters
path `(String)` the path to the file to read
options `(Object = `null`)` options object

Name | Description
--- | ---
options.decrypt `Boolean` (default `false`) | try to decrypt the data with the app private key
options.username `String` | the Blockstack ID to lookup for multi-player storage
options.app `String` | the app to lookup for multi-player storage - defaults to current origin
options.zoneFileLookupURL `String` (default `http://localhost:6270/v1/names/`) | the Blockstack core endpoint URL to use for zonefile lookup

Returns
`Promise`: that resolves to the raw data in the file or rejects with an error

### putFile

Stores the data provided in the app's data store to to the file specified.

putFile(path: String, content: (String | Buffer), options: Object): Promise
Parameters
path `(String)` the path to store the data in
content `((String | Buffer))` the data to store in the file
options `(Object = `null`)` options object

Name | Description
--- | ---
options.encrypt `Boolean` (default `false`) | encrypt the data with the app private key

Returns
`Promise`: that resolves if the operation succeed and rejects if it failed

### deleteFile

Deletes the specified file from the app's data store.

deleteFile(path: String): Promise
Parameters
path `(String)` the path to the file to delete
Returns
`Promise`: that resolves when the file has been removed or rejects with an error

### getAppBucketUrl

Get the app storage bucket URL

getAppBucketUrl(gaiaHubUrl: String, appPrivateKey: String): Promise
Parameters
gaiaHubUrl `(String)` the gaia hub URL
appPrivateKey `(String)` the app private key used to generate the app address
Returns
`Promise`: That resolves to the URL of the app index file or rejects if it fails

### getUserAppFileUrl

Fetch the public read URL of a user file for the specified app.

getUserAppFileUrl(path: String, username: String, appOrigin: String, zoneFileLookupURL: string): Promise
Parameters
path `(String)` the path to the file to read
username `(String)` The Blockstack ID of the user to look up
appOrigin `(String)` The app origin
zoneFileLookupURL `(string = `http://localhost:6270/v1/names/`)` The URL to use for zonefile lookup
Returns
`Promise`: that resolves to the public read URL of the file or rejects with an error

## Blockchain

Generate and broadcast Blockstack blockchain transactions.

### decryptPrivateKey

Decrypts the hex encrypted private key

decryptPrivateKey(privateKey: String, hexedEncrypted: String): String
Parameters
privateKey `(String)` the private key corresponding to the public key for which the ciphertext was encrypted
hexedEncrypted `(String)` the ciphertext
Returns
`String`: the decrypted private key
Throws

- Error: if unable to decrypt

### makeAuthResponse

Generates a signed authentication response token for an app. This token is sent back to apps which use contents to access the resources and data requested by the app.

makeAuthResponse(privateKey: String, profile: Object, username: String, metadata: AuthMetadata, coreToken: String, appPrivateKey: String, expiresAt: Number, transitPublicKey: String, hubUrl: String): String
Parameters
privateKey `(String)` the identity key of the Blockstack ID generating the authentication response
profile `(Object = `{}`)` the profile object for the Blockstack ID
username `(String = `null`)` the username of the Blockstack ID if any, otherwise `null`
metadata `(AuthMetadata)` an object containing metadata sent as part of the authentication response including `email` if requested and available and a URL to the profile
coreToken `(String = `null`)` core session token when responding to a legacy auth request or `null` for current direct to gaia authentication requests
appPrivateKey `(String = `null`)` the application private key. This private key is unique and specific for every Blockstack ID and application combination.
expiresAt `(Number = `nextMonth().getTime()`)` an integer in the same format as `new Date().getTime()` , milliseconds since the Unix epoch
transitPublicKey `(String = `null`)` the public key provide by the app in its authentication request with which secrets will be encrypted
hubUrl `(String = `null`)` URL to the write path of the user's Gaia hub
Returns
`String`: signed and encoded authentication response token

### isExpirationDateValid

Checks if the expiration date of the `token` is before the current time

isExpirationDateValid(token: String): Boolean
Parameters
token `(String)` encoded and signed authentication token
Returns
`Boolean`: `true` if the `token` has not yet expired, `false` if the `token` has expired

### isRedirectUriValid

Makes sure the `redirect_uri` is a same origin absolute URL.

isRedirectUriValid(token: String): Boolean
Parameters
token `(String)` encoded and signed authentication token
Returns
`Boolean`: `true` if valid, otherwise `false`

### broadcastTransaction

Broadcasts a signed bitcoin transaction to the network optionally waiting to broadcast the transaction until a second transaction has a certain number of confirmations.

broadcastTransaction(transaction: string, transactionToWatch: string, confirmations: number): Promise<(Object | Error)>
Parameters
transaction `(string)` the hex-encoded transaction to broadcast
transactionToWatch `(string = `null`)` the hex transaction id of the transaction to watch for the specified number of confirmations before broadcasting the `transaction`
confirmations `(number = `6`)` the number of confirmations `transactionToWatch` must have before broadcasting `transaction` .
Returns
`Promise<(Object | Error)>`: Returns a Promise that resolves to an object with a `transaction_hash` key containing the transaction hash of the broadcasted transaction.

In the event of an error, it rejects with:

- a `RemoteServiceError` if there is a problem with the transaction broadcast service
- `MissingParameterError` if you call the function without a required parameter

### broadcastZoneFile

Broadcasts a zone file to the Atlas network via the transaction broadcast service.

broadcastZoneFile(zoneFile: String, transactionToWatch: String): Promise<(Object | Error)>
Parameters
zoneFile `(String)` the zone file to be broadcast to the Atlas network
transactionToWatch `(String = `null`)` the hex transaction id of the transaction to watch for confirmation before broadcasting the zone file to the Atlas network
Returns
`Promise<(Object | Error)>`: Returns a Promise that resolves to an object with a `transaction_hash` key containing the transaction hash of the broadcasted transaction.

In the event of an error, it rejects with:

- a `RemoteServiceError` if there is a problem with the transaction broadcast service
- `MissingParameterError` if you call the function without a required parameter

### broadcastNameRegistration

Sends the preorder and registration transactions and zone file for a Blockstack name registration along with the to the transaction broadcast service.

The transaction broadcast:

- immediately broadcasts the preorder transaction
- broadcasts the register transactions after the preorder transaction has an appropriate number of confirmations
- broadcasts the zone file to the Atlas network after the register transaction has an appropriate number of confirmations

broadcastNameRegistration(preorderTransaction: String, registerTransaction: String, zoneFile: String): Promise<(Object | Error)>
Parameters
preorderTransaction `(String)` the hex-encoded, signed preorder transaction generated using the `makePreorder` function
registerTransaction `(String)` the hex-encoded, signed register transaction generated using the `makeRegister` function
zoneFile `(String)` the zone file to be broadcast to the Atlas network
Returns
`Promise<(Object | Error)>`: Returns a Promise that resolves to an object with a `transaction_hash` key containing the transaction hash of the broadcasted transaction.

In the event of an error, it rejects with:

- a `RemoteServiceError` if there is a problem with the transaction broadcast service
- `MissingParameterError` if you call the function without a required parameter