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, authResponseToken: String, transitKey: String): Promise
Parameters
nameLookupURL (String = 'https://core.blockstack.org/v1/names/') the endpoint against which to verify public keys match claimed username
authResponseToken (String = getAuthResponseToken()) the signed authentication response token
transitKey (String = getTransitKey()) the transit private key that corresponds to the transit public key that was provided in the authentication request
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 = null) The URL to use for zonefile lookup. If falsey, lookupProfile will use the blockstack.js getNameInfo function.
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 true) try to decrypt the data with the app private key
options.username String the Blockstack ID to lookup for multi-player storage
options.verify Boolean Whether the content should be verified, only to be used when putFile was set to sign = true
options.app String the app to lookup for multi-player storage - defaults to current origin
options.zoneFileLookupURL String (default null) The URL to use for zonefile lookup. If falsey, this will use the blockstack.js's getNameInfo function instead.
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 | String) (default true) encrypt the data with the app private key or the provided public key
options.sign Boolean (default false) sign the data using ECDSA on SHA256 hashes with the app private key
Returns
Promise: that resolves if the operation succeed and rejects if it failed

encryptContent

Encrypts the data provided with the app public key.

encryptContent(content: (String | Buffer), options: Object): String
Parameters
content ((String | Buffer)) data to encrypt
options (Object = null) options object
Name Description
options.publicKey String the hex string of the ECDSA public key to use for encryption. If not provided, will use user's appPrivateKey.
Returns
String: Stringified ciphertext object

decryptContent

Decrypts data encrypted with encryptContent with the transit private key.

decryptContent(content: (String | Buffer), options: Object): (String | Buffer)
Parameters
content ((String | Buffer)) encrypted content.
options (Object = null) options object
Name Description
options.privateKey String the hex string of the ECDSA private key to use for decryption. If not provided, will use user's appPrivateKey.
Returns
(String | Buffer): decrypted content.

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 = null) The URL to use for zonefile lookup. If falsey, this will use the blockstack.js's getNameInfo function instead.
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

signECDSA

Sign content using ECDSA

signECDSA(privateKey: String, content: Object): Object
Parameters
privateKey (String) secp256k1 private key hex string
content (Object) content to sign
Returns
Object: contains: signature - Hex encoded DER signature public key - Hex encoded private string taken from privateKey

verifyECDSA

Verify content using ECDSA

verifyECDSA(content: (String | Buffer), publicKey: String, signature: String): Boolean
Parameters
content ((String | Buffer)) Content to verify was signed
publicKey (String) secp256k1 private key hex string
signature (String) Hex encoded DER signature
Returns
Boolean: returns true when signature matches publickey + content, false if not

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

signerVersion

signerVersion
Returns
any: version number of the signer, currently, should always be 1

getAddress

getAddress
Returns
any: a string representing the transaction signer's address (usually Base58 check encoding)

signTransaction

Signs a transaction input

signTransaction
Parameters
transaction (TransactionBuilder) the transaction to sign
inputIndex (number) the input on the transaction to sign

PubkeyHashSigner

Class representing a transaction signer for pubkeyhash addresses (a.k.a. single-sig addresses)

new PubkeyHashSigner(ecPair: bitcoinjs.ECPair)
Parameters
ecPair (bitcoinjs.ECPair)

estimateNamespaceReveal

Estimates cost of a namesapce reveal transaction for a namespace

estimateNamespaceReveal(namespace: BlockstackNamespace, revealAddress: String, paymentAddress: String, paymentUtxos: Number): Promise
Parameters
namespace (BlockstackNamespace) the namespace to reveal
revealAddress (String) the address to receive the namespace (this must have been passed as 'revealAddress' to a prior namespace preorder)
paymentAddress (String) the address that pays for this transaction
paymentUtxos (Number = 1) the number of UTXOs we expect will be required from the payment address
Returns
Promise: a promise which resolves to the satoshi cost to fund the reveal. This includes a 5500 satoshi dust output for the preorder. Even though this is a change output, the payer must have enough funds to generate this output, so we include it in the cost.

estimateNamespaceReady

Estimates the cost of a namespace-ready transaction for a namespace

estimateNamespaceReady(namespaceID: String, revealUtxos: Number): Promise
Parameters
namespaceID (String) the namespace to ready
revealUtxos (Number = 1) the number of UTXOs we expect will be required from the reveal address
Returns
Promise: a promise which resolves to the satoshi cost to fund this namespacey-ready transaction.

estimateNameImport

Estimates the cost of a name-import transaction

estimateNameImport(name: String, recipientAddr: String, zonefileHash: String, importUtxos: Number): Promise
Parameters
name (String) the fully-qualified name
recipientAddr (String) the recipient
zonefileHash (String) the zone file hash
importUtxos (Number = 1) the number of UTXOs we expect will be required from the importer address
Returns
Promise: a promise which resolves to the satoshi cost to fund this name-import transaction

estimateAnnounce

Estimates the cost of an announce transaction

estimateAnnounce(messageHash: String, senderUtxos: Number): Promise
Parameters
messageHash (String) the hash of the message
senderUtxos (Number = 1) the number of utxos we expect will be required from the importer address
Returns
Promise: a promise which resolves to the satoshi cost to fund this announce transaction