@cryptforge/blockchain-btc
v0.2.1
Published
Bitcoin blockchain adapter for CryptForge SDK
Maintainers
Readme
@cryptforge/blockchain-btc
Bitcoin blockchain adapter for the CryptForge SDK. Provides BIP44-compliant key derivation, address generation, and transaction signing for Bitcoin.
Installation
npm install @cryptforge/blockchain-btc @cryptforge/auth @cryptforge/core
# or
pnpm add @cryptforge/blockchain-btc @cryptforge/auth @cryptforge/core
# or
yarn add @cryptforge/blockchain-btc @cryptforge/auth @cryptforge/coreQuick Start
import { createAuthClient } from '@cryptforge/auth';
import { BitcoinAdapter } from '@cryptforge/blockchain-btc';
// Create auth client and register Bitcoin adapter
const auth = createAuthClient();
auth.registerAdapter('bitcoin', new BitcoinAdapter());
// Generate mnemonic
const mnemonic = auth.generateMnemonic({ wordCount: 12 });
// Create identity with Bitcoin
const { identity, keys } = await auth.createIdentity({
mnemonic,
password: 'secure-password',
label: 'My Bitcoin Wallet',
chainId: 'bitcoin',
});
console.log('Bitcoin Address:', keys.address);
// Example: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNaFeatures
- ✅ BIP44 Derivation - Standard Bitcoin derivation path:
m/44'/0'/0'/0/0 - ✅ P2PKH Addresses - Pay-to-Public-Key-Hash address generation
- ✅ Message Signing - Sign messages with Bitcoin keys
- ✅ Transaction Signing - Sign Bitcoin transactions (UTXO-based)
- ✅ HD Wallet Support - Hierarchical Deterministic wallet key derivation
- ✅ Multiple Addresses - Generate multiple addresses from a single seed
- ✅ Type-Safe - Full TypeScript support
Usage
With @cryptforge/auth (Recommended)
The recommended way to use this adapter is through @cryptforge/auth:
import { createAuthClient } from '@cryptforge/auth';
import { BitcoinAdapter } from '@cryptforge/blockchain-btc';
const auth = createAuthClient();
auth.registerAdapter('bitcoin', new BitcoinAdapter());
// Unlock wallet
await auth.unlock({
password: 'your-password',
chainId: 'bitcoin',
});
// Get current Bitcoin address
const address = auth.currentAddress;
console.log('Address:', address);
// Get multiple addresses
const addresses = await auth.getAddresses('bitcoin', 0, 5);
console.log('First 5 addresses:', addresses);Sign Message
// Unlock wallet first
await auth.unlock({
password: 'your-password',
chainId: 'bitcoin',
});
// Sign a message
const { signature, address, publicKey } = await auth.signMessage({
message: 'Hello Bitcoin!',
});
console.log('Signature:', signature);
console.log('Signed by:', address);
// Verify signature
const isValid = await auth.verifySignature(
'Hello Bitcoin!',
signature,
publicKey
);
console.log('Signature valid:', isValid);Sign Transaction
// Unlock wallet first
await auth.unlock({
password: 'your-password',
chainId: 'bitcoin',
});
// Sign a Bitcoin transaction
const { signedTransaction, signature } = await auth.signTransaction({
transaction: {
inputs: [
{
txid: 'previous_transaction_id',
index: 0,
// ... other input fields
},
],
outputs: [
{
address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
amount: '100000', // satoshis
},
],
},
});
console.log('Signed Transaction:', signedTransaction);Generate Multiple Addresses
// Get addresses at specific indices
const addresses = await auth.getAddresses('bitcoin', 0, 10);
addresses.forEach((addr) => {
console.log(`Index ${addr.index}: ${addr.address}`);
console.log(`Path: ${addr.path}`);
});
// Output:
// Index 0: 1A1zP1eP5... Path: m/44'/0'/0'/0/0
// Index 1: 1BvBMSEYs... Path: m/44'/0'/0'/0/1
// ...Direct Adapter Usage (Advanced)
For advanced use cases, you can use the adapter directly:
import { BitcoinAdapter } from '@cryptforge/blockchain-btc';
const adapter = new BitcoinAdapter();
// Derive keys from mnemonic
const keys = await adapter.deriveKeys(
'your twelve word mnemonic phrase here that you backed up safely'
);
console.log('Address:', keys.address);
console.log('Public Key:', keys.publicKeyHex);
console.log('Derivation Path:', keys.path);
// Get address at specific index
const { address, publicKey, path } = await adapter.getAddressAtIndex(
'your twelve word mnemonic phrase here that you backed up safely',
5
);
// Sign message
const { signature } = await adapter.signMessage(
keys.privateKey,
'Hello Bitcoin!'
);API Reference
BitcoinAdapter
Properties
chainData: ChainData- Chain metadataname: "Bitcoin"symbol: "BTC"cmc_id: 1(CoinMarketCap ID)decimals: 8
Methods
deriveKeys(mnemonic: string): Promise<KeyData>
Derives Bitcoin keys from a BIP39 mnemonic using path m/44'/0'/0'/0/0.
const keys = await adapter.deriveKeys(mnemonic);deriveKeysAtIndex(mnemonic: string, index: number): Promise<KeyData>
Derives keys at a specific address index.
const keys = await adapter.deriveKeysAtIndex(mnemonic, 5);
// Path: m/44'/0'/0'/0/5deriveKeysAtPath(mnemonic: string, path: string): Promise<KeyData>
Derives keys at a custom BIP44 path.
const keys = await adapter.deriveKeysAtPath(mnemonic, "m/44'/0'/1'/0/0");getAddressAtIndex(mnemonic: string, index: number): Promise<{ address, publicKey, path }>
Gets address information at a specific index without returning private keys.
const { address, publicKey, path } = await adapter.getAddressAtIndex(
mnemonic,
0
);getAddresses(mnemonic: string, startIndex: number, count: number): Promise<Array<{ address, path, index }>>
Gets multiple addresses starting from an index.
const addresses = await adapter.getAddresses(mnemonic, 0, 10);signMessage(privateKey: Uint8Array, message: string | Uint8Array): Promise<{ signature }>
Signs a message using Bitcoin's double SHA-256 hash.
const { signature } = await adapter.signMessage(
keys.privateKey,
'Hello Bitcoin!'
);signTransaction(privateKey: Uint8Array, transaction: any): Promise<{ signedTransaction, signature }>
Signs a Bitcoin transaction. Requires UTXO-based transaction structure.
const { signedTransaction, signature } = await adapter.signTransaction(
keys.privateKey,
{
inputs: [{ txid: '...', index: 0 }],
outputs: [{ address: '...', amount: '100000' }],
}
);verifySignature(message: string | Uint8Array, signature: string, publicKey: string): Promise<boolean>
Verifies a message signature.
const isValid = await adapter.verifySignature(message, signature, publicKey);KeyData Type
interface KeyData {
mnemonic: string; // BIP39 mnemonic phrase
seed: Uint8Array; // BIP39 seed (512 bits)
privateKey: Uint8Array; // Private key bytes
privateKeyHex: string; // Private key as hex string
publicKey: Uint8Array; // Compressed public key (33 bytes)
publicKeyHex: string; // Public key as hex string
address: string; // Bitcoin P2PKH address
path: string; // BIP44 derivation path
}Address Types
This adapter currently supports P2PKH (Pay-to-Public-Key-Hash) addresses only. P2PKH addresses:
- Start with
1(mainnet) orm/n(testnet) - Are the most common legacy Bitcoin address type
- Use base58check encoding
- Example:
1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
Future versions may support:
- P2SH (Pay-to-Script-Hash) - addresses starting with
3 - P2WPKH (SegWit) - addresses starting with
bc1q - P2TR (Taproot) - addresses starting with
bc1p
Dependencies
This package uses modern, audited Bitcoin libraries:
@scure/bip32- BIP32 HD wallet key derivation@scure/bip39- BIP39 mnemonic generation and validation@scure/btc-signer- Bitcoin transaction signing@noble/hashes- Cryptographic hash functions (SHA-256)@noble/secp256k1- secp256k1 elliptic curve cryptography
All dependencies are minimal, audited, and widely trusted in the Bitcoin ecosystem.
Limitations
Not Yet Implemented
The following features are not yet implemented but are planned for future releases:
- Balance Queries -
getNativeBalance(),getTokenBalances() - Transaction History -
getTransactions(),getTokenTransfers() - Transaction Broadcasting -
sendNativeToken(),sendToken() - Transaction Status -
getTransactionStatus()
For these features, please use:
- Block explorer APIs (Blockstream, Blockchain.com, etc.)
- Bitcoin RPC providers
- Bitcoin wallet SDKs
UTXO Management
Bitcoin uses a UTXO (Unspent Transaction Output) model, which is more complex than account-based models (like Ethereum). When building a transaction, you need to:
- Select appropriate UTXOs (inputs)
- Calculate transaction fees
- Handle change outputs
- Manage different address types
Consider using specialized Bitcoin libraries or services for production applications.
Browser Compatibility
This package is 100% browser-compatible:
- ✅ Chrome, Firefox, Safari, Edge
- ✅ Node.js (v16+)
- ✅ Electron (main and renderer)
- ✅ React Native
- ✅ Web Workers
Uses only browser-safe cryptography with no Node.js dependencies.
Examples
See working examples in:
examples/vue-electron-example/src/AuthTest.vue- Complete integration with @cryptforge/auth
License
MIT
