CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-bsv

JavaScript library for Bitcoin SV (BSV) blockchain development with cryptographic primitives, transaction handling, and protocol implementations

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

BSV JavaScript Library

A complete Bitcoin SV implementation in JavaScript providing protocols, standards, cryptography, and utilities for building Bitcoin SV applications.

Installation

npm install bsv

Quick Start

ES6 Module Imports

import { Address, PrivKey, PubKey, Tx, TxBuilder } from 'bsv'

// Generate a new private key and address
const privKey = PrivKey.fromRandom()
const address = Address.fromPrivKey(privKey)
console.log(address.toString())

CommonJS Imports

const bsv = require('bsv')

// Generate a new private key and address
const privKey = bsv.PrivKey.fromRandom()
const address = bsv.Address.fromPrivKey(privKey)
console.log(address.toString())

Package Information

// Library metadata
const version: string       // Current library version
const deps: {               // External dependencies
  aes: object              // AES encryption
  bnjs: object             // Big number arithmetic
  bs58: object             // Base58 encoding
  elliptic: object         // Elliptic curve cryptography
  hashjs: object           // Hash functions
  pbkdf2compat: object     // PBKDF2 implementation
  Buffer: Function         // Node.js Buffer constructor
}

Architecture Overview

The BSV library is organized into several functional areas:

Core Bitcoin Components

  • Address: Bitcoin addresses for sending and receiving payments
  • Transaction (Tx): Bitcoin transaction creation and manipulation
  • Script: Bitcoin Script language implementation
  • TxBuilder: High-level transaction construction and signing

Cryptographic Primitives

  • PrivKey/PubKey: Private and public key management
  • ECDSA: Digital signature algorithms
  • Hash: Cryptographic hash functions (SHA-256, RIPEMD-160, etc.)
  • Signature: Digital signature representation and validation

Hierarchical Deterministic Wallets

  • Bip32: HD wallet implementation (BIP32)
  • Bip39: Mnemonic seed phrase generation (BIP39)

Advanced Features

  • Encryption: AES, ECIES encryption schemes
  • Script Execution: Bitcoin Script interpreter
  • Workers: Background computation support

Network Configuration

// Network variants available for most classes
const Mainnet = {
  Address: Address.Mainnet,
  PrivKey: PrivKey.Mainnet,
  Bip32: Bip32.Mainnet,
  // ... all classes with mainnet configuration
}

const Testnet = {
  Address: Address.Testnet,
  PrivKey: PrivKey.Testnet,
  Bip32: Bip32.Testnet,
  // ... all classes with testnet configuration
}

Basic Usage Examples

Creating and Using Addresses

// Generate random address
const address = Address.fromRandom()

// Create address from private key
const privKey = PrivKey.fromRandom()
const address = Address.fromPrivKey(privKey)

// Create address from public key
const pubKey = PubKey.fromPrivKey(privKey)
const address = Address.fromPubKey(pubKey)

// Parse address from string
const address = Address.fromString('1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2')

// Validate address
const isValid = Address.isValid('1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2')

Building Transactions

// Create transaction builder
const txBuilder = new TxBuilder()

// Set fee rate and change address
txBuilder.setFeePerKbNum(500)
txBuilder.setChangeAddress(changeAddress)

// Add inputs (unspent outputs)
txBuilder.inputFromPubKeyHash(txHashBuf, txOutNum, txOut, pubKey)

// Add outputs
txBuilder.outputToAddress(valueBn, toAddress)

// Build and sign transaction
const tx = txBuilder.build()
const keyPairs = [keyPair1, keyPair2]
txBuilder.sign(keyPairs)

Working with Scripts

// Create P2PKH script (pay-to-public-key-hash)
const script = Script.fromPubKeyHash(pubKeyHashBuf)

// Create OP_RETURN data script
const dataScript = Script.fromOpReturnData(dataBuf)

// Parse script from ASM string
const script = Script.fromAsmString('OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG')

// Check script types
const isPubKeyHash = script.isPubKeyHashOut()
const isOpReturn = script.isOpReturn()

Capabilities

Core Bitcoin Functionality

Essential Bitcoin operations including addresses, transactions, and scripts.

// Address operations
const address = Address.fromPubKey(pubKey)
const script = address.toTxOutScript()

// Transaction creation
const tx = new Tx()
tx.addTxIn(txHashBuf, txOutNum, script, nSequence)
tx.addTxOut(valueBn, script)

// Script operations
const script = Script.fromPubKeyHash(hashBuf)
const isValid = script.isPubKeyHashOut()

Cryptography

Low-level cryptographic operations for digital signatures and key management.

// ECDSA signing and verification
const sig = Ecdsa.sign(hashBuf, keyPair)
const verified = Ecdsa.verify(hashBuf, sig, pubKey)

// Hash functions
const hash = Hash.sha256(dataBuf)
const doubleHash = Hash.sha256Sha256(dataBuf)
const addressHash = Hash.sha256Ripemd160(dataBuf)

HD Wallets

Hierarchical deterministic wallets supporting BIP32 and BIP39 standards with language-specific implementations.

// Generate HD wallet from seed
const bip32 = Bip32.fromSeed(seedBuf)
const childKey = bip32.derive("m/44'/0'/0'/0/0")

// Generate mnemonic phrase
const bip39 = Bip39.fromRandom(128)
const mnemonic = bip39.toString()
const seed = bip39.toSeed('passphrase')

// Language-specific BIP-39 implementations
class Bip39En extends Bip39 {
  constructor(mnemonic?: string, seed?: Buffer)
}

class Bip39Jp extends Bip39 {
  constructor(mnemonic?: string, seed?: Buffer)
}

// Word lists for different languages
const en: string[]       // English word list (2048 words)
const jp: string[]       // Japanese word list (2048 words)

Transaction Building

High-level transaction construction with automatic fee calculation and change handling.

// High-level transaction building
const txBuilder = new TxBuilder()
txBuilder.inputFromPubKeyHash(txHashBuf, txOutNum, txOut, pubKey)
txBuilder.outputToAddress(valueBn, address)
const tx = txBuilder.build()

Encryption

Advanced encryption schemes including AES and ECIES for secure data transmission.

// ECIES encryption
const encrypted = Ecies.bitcoreEncrypt(messageBuf, toPubKey, fromKeyPair)
const decrypted = Ecies.bitcoreDecrypt(encryptedBuf, toPrivKey)

// AES encryption
const encrypted = Aescbc.encrypt(dataBuf, keyBuf, ivBuf)
const decrypted = Aescbc.decrypt(encryptedBuf, keyBuf, ivBuf)

Utilities

Base classes, encoding utilities, and supporting infrastructure.

// Base58 encoding
const encoded = Base58.encode(dataBuf)
const decoded = Base58.decode(encodedString)

// Big number operations
const bn = Bn.fromBuffer(buf)
const result = bn.add(otherBn)

// Buffer operations
const br = new Br(buffer)
const data = br.readUInt32LE()

P2P Network Protocol

Bitcoin peer-to-peer network protocol components for node communication and blockchain operations.

// Network message handling
class Msg extends Struct {
  constructor(magicNum: number, cmdbuf: Buffer, datasize: number, checksumbuf: Buffer, dataBuf: Buffer)
  setCmd(cmdname: string): Msg
  getCmd(): string
  static checksum(dataBuf: Buffer): Buffer
  static asyncChecksum(dataBuf: Buffer): Promise<Buffer>
}

// Network version negotiation
class Version extends Struct {
  constructor(
    versionBytesNum?: number,
    servicesBuf?: Buffer,
    timeBn?: Bn,
    addrRecvServicesBuf?: Buffer,
    addrRecvIpAddrBuf?: Buffer,
    addrRecvPort?: number,
    addrTransServicesBuf?: Buffer,
    addrTransIpAddrBuf?: Buffer,
    addrTransPort?: number,
    nonceBuf?: Buffer,
    userAgentVi?: VarInt,
    userAgentBuf?: Buffer,
    startHeightNum?: number,
    relay?: boolean
  )
}

// Inventory messages for transaction and block announcements
class Inv extends Struct {
  constructor(typeNum: number, hashBuf: Buffer)
  isTx(): boolean
  isBlock(): boolean
  isFilteredBlock(): boolean
  static MSG_TX: number         // Value: 1
  static MSG_BLOCK: number      // Value: 2
  static MSG_FILTERED_BLOCK: number  // Value: 3
}

// Merkle tree operations for blockchain verification
class Merkle extends Struct {
  constructor(hashBuf?: Buffer, buf?: Buffer, merkle1?: Merkle, merkle2?: Merkle)
  hash(): Buffer
  fromBuffers(bufs: Buffer[]): Merkle
  static fromBuffers(bufs: Buffer[]): Merkle
}

// Hash caching for signature verification performance
class HashCache extends Struct {
  constructor(prevoutsHashBuf?: Buffer, sequenceHashBuf?: Buffer, outputsHashBuf?: Buffer)
  fromBuffer(buf: Buffer): HashCache
  toBuffer(): Buffer
  fromJSON(json: object): HashCache
  toJSON(): object
}

// Configuration management for network and environment settings
class Config {
  constructor(values: object)
  get(key: string): any
}

class ConfigBuilder {
  constructor()
  build(): Config
  addValue(key: string, value: any): ConfigBuilder
  addValueWithDefault(key: string, value: any, defaultValue: any): ConfigBuilder
}

// Network constants for mainnet and testnet
const Constants: {
  Mainnet: NetworkConstants
  Testnet: NetworkConstants
  Default: NetworkConstants
}

// Bitcoin Script operation codes
class OpCode extends Struct {
  constructor(num?: number, str?: string)
  toNumber(): number
  toString(): string
  static fromNumber(num: number): OpCode
  static fromString(str: string): OpCode
  // Common opcodes like OP_RETURN, OP_DUP, OP_HASH160, etc.
}

// Base class for all BSV data structures
class Struct {
  constructor(obj?: object)
  fromObject(obj: object): Struct
  fromBuffer(buf: Buffer): Struct
  toBuffer(): Buffer
  fromJSON(json: object): Struct
  toJSON(): object
}

Error Handling

All classes include comprehensive validation and throw descriptive errors for:

  • Invalid input parameters
  • Malformed data structures
  • Network mismatches
  • Cryptographic validation failures
  • Unsupported operations
try {
  const address = Address.fromString('invalid-address')
} catch (error) {
  console.error('Invalid address format:', error.message)
}

Async Operations

Most cryptographic operations support async variants for non-blocking computation:

// Async address generation
const address = await Address.asyncFromPrivKey(privKey)

// Async transaction signing
const sig = await tx.asyncSign(keyPair, nHashType, nIn, subScript, valueBn)

// Async hash computation
const hash = await Hash.asyncSha256(dataBuf)

Environment Support

The library works in both Node.js and browser environments with proper polyfills and bundling.

// Environment detection
const isBrowser = bsv.browser      // true in browser
const env = bsv.env               // process.env object

Install with Tessl CLI

npx tessl i tessl/npm-bsv

docs

core-bitcoin.md

cryptography.md

encryption.md

hd-wallets.md

index.md

transaction-building.md

utilities.md

tile.json