Options
All
  • Public
  • Public/Protected
  • All
Menu

@stacks/keychain

Create and manage keys/wallets for the Stacks blockchain.

Installation

npm install @stacks/keychain

Mnemonic

Generate encrypted mnemonic

import { decrypt, generateEncryptedMnemonicRootKeychain } from '@stacks/keychain';

const password = '427706da374f435f959283de93652375';
const twelveWorder = await generateEncryptedMnemonicRootKeychain(password, 128);
const twentyFourWorder = await generateEncryptedMnemonicRootKeychain(password, 256);

const twelveWordDecrypted = await decrypt(twelveWorder.encryptedMnemonicPhrase, password);
console.log(twelveWordDecrypted);
  
const twentyFourWordDecrypted = await decrypt(twentyFourWorder.encryptedMnemonicPhrase, password);
console.log(twentyFourWordDecrypted);

Restore keychain from mnemonic

import { deriveRootKeychainFromMnemonic } from '@stacks/keychain';

const phrase =
    'eternal army wreck noodle click shock include orchard jungle only middle forget idle pulse give empower iron curtain silent blush blossom chef animal sphere';

const rootNode = await deriveRootKeychainFromMnemonic(phrase);
const privateKey = rootNode.privateKey?.toString('hex');
// privateKey

Encryption

Encrypt and decrypt

import { decrypt, encrypt } from '@stacks/keychain';

const phrase = 'vivid oxygen neutral wheat find thumb cigar wheel board kiwi portion business';
const password = 'supersecret';

const encryptedText = await encrypt(phrase, password);
const plainTextBuffer = await decrypt(encryptedText, password);
console.log(plainTextBuffer);

Wallet

Generate and restore wallet

import keychain, { decrypt } from '@stacks/keychain';
import { ChainID } from '@stacks/transactions';
import { Buffer } from '@stacks/common';

const password = 'password';
const generated = await keychain.Wallet.generate(password, ChainID.Testnet);

const encryptedBackupPhrase = generated.encryptedBackupPhrase;

const plainTextBuffer = await decrypt(Buffer.from(encryptedBackupPhrase, 'hex'), password);

const backupPhrase = plainTextBuffer.toString();

const restored = await keychain.Wallet.restore(password, backupPhrase, ChainID.Mainnet);

console.log(restored.identityPublicKeychain === generated.identityPublicKeychain);
// true

Get profile from auth response

import keychain from '@stacks/keychain';
import { ChainID } from '@stacks/transactions';
import { getPublicKeyFromPrivate, makeECPrivateKey } from '@stacks/encryption';
import { decodeToken } from 'jsontokens';

const password = 'password';
const generated = await keychain.Wallet.generate(password, ChainID.Testnet);
const [identity] = generated.identities;

const appDomain = 'https://banter.pub';
const gaiaUrl = 'https://hub.blockstack.org';
const transitPrivateKey = makeECPrivateKey();
const transitPublicKey = getPublicKeyFromPrivate(transitPrivateKey);

const authResponse = await identity.makeAuthResponse({
  appDomain,
  gaiaUrl,
  transitPublicKey,
  scopes: ['publish_data'],
});
const decoded = decodeToken(authResponse);
console.log(decoded);

Get a STX address

import keychain from '@stacks/keychain';
import { ChainID, TransactionVersion } from '@stacks/transactions';

const password = 'password';
const generated = await keychain.Wallet.generate(password, ChainID.Testnet);
const signer = generated.getSigner();
const mainnetAddress = signer.getSTXAddress(TransactionVersion.Mainnet);
console.log(mainnetAddress);

const testnetAddress = signer.getSTXAddress(TransactionVersion.Testnet);
console.log(testnetAddress);

Index

Type aliases

AllowedKeyEntropyBits

AllowedKeyEntropyBits: 128 | 256

Properties

default

default: { Wallet: typeof Wallet }

Type declaration

Variables

Const DEFAULT_PROFILE

DEFAULT_PROFILE: Profile = ...

Const derivationPaths

derivationPaths: { 1: string; 2147483648: string } = ...

Type declaration

  • 1: string
  • 2147483648: string

Const registrars

registrars: { id.blockstack: { apiUrl: string; registerUrl: string }; test-personal.id: { apiUrl: string; registerUrl: string } } = ...

Type declaration

  • id.blockstack: { apiUrl: string; registerUrl: string }
    • apiUrl: string
    • registerUrl: string
  • test-personal.id: { apiUrl: string; registerUrl: string }
    • apiUrl: string
    • registerUrl: string

Functions

assertIsTruthy

  • assertIsTruthy<T>(val: any): asserts val is NonNullable<T>
  • Type parameters

    • T

    Parameters

    • val: any

    Returns asserts val is NonNullable<T>

decrypt

  • decrypt(dataBuffer: Buffer | string, password: string): Promise<string>
  • Decrypt an encrypted mnemonic phrase with a password. Legacy triplesec encrypted payloads are also supported.

    Parameters

    • dataBuffer: Buffer | string
    • password: string

      Password for data

    Returns Promise<string>

    the raw mnemonic phrase

deriveIdentityKeyPair

  • deriveIdentityKeyPair(identityOwnerAddressNode: IdentityAddressOwnerNode): IdentityKeyPair
  • Parameters

    • identityOwnerAddressNode: IdentityAddressOwnerNode

    Returns IdentityKeyPair

deriveRootKeychainFromMnemonic

  • deriveRootKeychainFromMnemonic(plaintextMnemonic: string): Promise<BIP32Interface>
  • Parameters

    • plaintextMnemonic: string

    Returns Promise<BIP32Interface>

deriveStxAddressChain

  • deriveStxAddressChain(chain: ChainID): (rootNode: BIP32Interface) => { address: string; childKey: BIP32Interface; privateKey: string }
  • Parameters

    Returns (rootNode: BIP32Interface) => { address: string; childKey: BIP32Interface; privateKey: string }

      • (rootNode: BIP32Interface): { address: string; childKey: BIP32Interface; privateKey: string }
      • Parameters

        • rootNode: BIP32Interface

        Returns { address: string; childKey: BIP32Interface; privateKey: string }

        • address: string
        • childKey: BIP32Interface
        • privateKey: string

encrypt

  • encrypt(phrase: string, password: string): Promise<Buffer>
  • Encrypt a raw mnemonic phrase to be password protected

    Parameters

    • phrase: string

      Raw mnemonic phrase

    • password: string

      Password to encrypt mnemonic with

    Returns Promise<Buffer>

    The encrypted phrase

encryptMnemonicFormatted

  • encryptMnemonicFormatted(plaintextMnemonic: string, password: string): Promise<{ encryptedMnemonic: Buffer; encryptedMnemonicHex: string }>
  • Parameters

    • plaintextMnemonic: string
    • password: string

    Returns Promise<{ encryptedMnemonic: Buffer; encryptedMnemonicHex: string }>

Const fetchProfile

  • fetchProfile(__namedParameters: { gaiaUrl: string; identity: Identity }): Promise<null | Profile>
  • Parameters

    • __namedParameters: { gaiaUrl: string; identity: Identity }
      • gaiaUrl: string
      • identity: Identity

    Returns Promise<null | Profile>

generateEncryptedMnemonicRootKeychain

  • generateEncryptedMnemonicRootKeychain(password: string, entropy: AllowedKeyEntropyBits): Promise<{ encryptedMnemonicPhrase: string; rootNode: BIP32Interface }>
  • Parameters

    Returns Promise<{ encryptedMnemonicPhrase: string; rootNode: BIP32Interface }>

generateMnemonicRootKeychain

  • generateMnemonicRootKeychain(entropy: AllowedKeyEntropyBits): Promise<{ plaintextMnemonic: string; rootNode: BIP32Interface }>
  • Parameters

    Returns Promise<{ plaintextMnemonic: string; rootNode: BIP32Interface }>

getAddress

  • getAddress(node: BIP32Interface): string
  • Parameters

    • node: BIP32Interface

    Returns string

getBitcoinAddressNode

  • getBitcoinAddressNode(bitcoinKeychain: BIP32Interface, addressIndex?: number, chainType?: string): BIP32Interface
  • Parameters

    • bitcoinKeychain: BIP32Interface
    • addressIndex: number = 0
    • chainType: string = ...

    Returns BIP32Interface

getBitcoinPrivateKeychain

  • getBitcoinPrivateKeychain(rootNode: BIP32Interface): BIP32Interface
  • Parameters

    • rootNode: BIP32Interface

    Returns BIP32Interface

getBlockchainIdentities

  • getBlockchainIdentities(rootNode: BIP32Interface, identitiesToGenerate: number): Promise<{ bitcoinPublicKeychain: string; firstBitcoinAddress: string; identities: Identity[]; identityAddresses: string[]; identityKeypairs: IdentityKeyPair[]; identityPublicKeychain: string }>
  • Parameters

    • rootNode: BIP32Interface
    • identitiesToGenerate: number

    Returns Promise<{ bitcoinPublicKeychain: string; firstBitcoinAddress: string; identities: Identity[]; identityAddresses: string[]; identityKeypairs: IdentityKeyPair[]; identityPublicKeychain: string }>

getDerivationPath

  • getDerivationPath(chain: ChainID): string
  • Parameters

    Returns string

getIdentityOwnerAddressNode

  • getIdentityOwnerAddressNode(identityPrivateKeychain: BIP32Interface, identityIndex?: number): Promise<default>
  • Parameters

    • identityPrivateKeychain: BIP32Interface
    • identityIndex: number = 0

    Returns Promise<default>

getIdentityPrivateKeychain

  • getIdentityPrivateKeychain(rootNode: BIP32Interface): BIP32Interface
  • Parameters

    • rootNode: BIP32Interface

    Returns BIP32Interface

Const getProfileURLFromZoneFile

  • getProfileURLFromZoneFile(name: string): Promise<undefined | string>
  • Parameters

    • name: string

    Returns Promise<undefined | string>

Const makeIdentity

  • makeIdentity(rootNode: BIP32Interface, index: number): Promise<Identity>
  • Parameters

    • rootNode: BIP32Interface
    • index: number

    Returns Promise<Identity>

Const recursiveRestoreIdentities

  • recursiveRestoreIdentities(__namedParameters: RecursiveMakeIdentitiesOptions): Promise<Identity[]>
  • Restore identities by recursively making a new identity, and checking if it has a username.

    As soon as a username is not found for an identity, the recursion stops.

    Parameters

    • __namedParameters: RecursiveMakeIdentitiesOptions

    Returns Promise<Identity[]>

Const registerSubdomain

  • registerSubdomain(__namedParameters: RegisterParams): Promise<Identity>
  • Register a subdomain for a given identity

    Parameters

    • __namedParameters: RegisterParams

    Returns Promise<Identity>

Const signAndUploadProfile

  • signAndUploadProfile(__namedParameters: { gaiaHubConfig?: GaiaHubConfig; gaiaHubUrl: string; identity: Identity; profile: Profile }): Promise<void>
  • Parameters

    • __namedParameters: { gaiaHubConfig?: GaiaHubConfig; gaiaHubUrl: string; identity: Identity; profile: Profile }

    Returns Promise<void>

signProfileForUpload

  • Parameters

    Returns string

uploadProfile

  • uploadProfile(gaiaHubUrl: string, identity: Identity, signedProfileTokenData: string, gaiaHubConfig?: GaiaHubConfig): Promise<string>
  • Parameters

    • gaiaHubUrl: string
    • identity: Identity
    • signedProfileTokenData: string
    • Optional gaiaHubConfig: GaiaHubConfig

    Returns Promise<string>

Const validateSubdomain

  • Validate the format and availability of a subdomain. Will return an error of enum IdentityNameValidityError if an error is present. If no errors are found, will return null.

    Parameters

    • name: string

      the subdomain to be registered

    • subdomain: Subdomains = ...

      a valid Subdomains enum

    Returns Promise<null | IdentityNameValidityError>

Const validateSubdomainAvailability

  • validateSubdomainAvailability(name: string, subdomain?: Subdomains): Promise<any>
  • Parameters

    Returns Promise<any>

Const validateSubdomainFormat

  • Parameters

    • identityName: string

    Returns null | IdentityNameValidityError

Generated using TypeDoc