Self-Hosted Crypto Billing: xpubs, Keys, and Why They Matter
Running a business that accepts cryptocurrency usually forces you into a corner. You either hand your funds over to a custodial processor like BitPay or Coinbase Commerce, paying fees and risking account freezes, or you struggle with the technical headache of managing thousands of wallet addresses manually. There is a middle ground that gives you total control without the operational nightmare: self-hosted crypto billing built on Hierarchical Deterministic (HD) wallets.
The secret sauce isn't magic; it's cryptography. Specifically, it relies on extended public keys, commonly known as xpubs. These keys allow your billing software to generate an infinite number of unique payment addresses for every single invoice, while your actual private keys-the ones that spend the money-stay locked away in a hardware wallet or offline device. This separation is what makes self-custody scalable for merchants.
What Are Extended Public Keys and HD Wallets?
To understand why xpubs matter, you first need to look at how Bitcoin addresses used to work. Before 2013, if you wanted to send money to someone, they gave you one address. If you wanted to receive money again, you had to give them another address, which required generating and backing up a new private key. For a merchant processing hundreds of transactions a day, this was impossible. You couldn't back up millions of keys.
That changed with BIP32, a standard introduced by Pieter Wuille and others in 2013. BIP32 created the concept of Hierarchical Deterministic (HD) wallets. Instead of random keys, HD wallets use a single master seed (usually 12 to 24 words) to generate a tree of keys. From this root, you can derive billions of child keys deterministically.
In this system, there are two types of extended keys:
- Extended Private Key (xprv): Contains the private key and a chain code. It can generate both private and public keys. This is the master key that controls spending.
- Extended Public Key (xpub): Contains the public key and the same chain code. It can only generate public keys (addresses). It cannot sign transactions or spend funds.
This asymmetry is crucial. Because an xpub can generate addresses but not spend them, you can safely share it with third-party services or your own server without giving them access to your funds. The xprv stays offline, ensuring that even if your server gets hacked, the attacker sees your balance but can't steal your coins.
How Self-Hosted Billing Uses xpubs
When you set up a self-hosted billing stack, such as BTCPay Server, you don't upload your private keys to the server. Instead, you import your xpub. The software uses this xpub to perform a mathematical operation called derivation.
Every time you create a new invoice, the server takes the xpub and applies an index number (e.g., m/84'/0'/0/0 for the first address, m/84'/0'/0/1 for the second). It calculates a new public address in milliseconds. This process happens entirely on the server, requiring no interaction with your hardware wallet.
Here is the workflow in practice:
- Invoice Creation: A customer clicks "Buy." Your server uses the xpub to generate a fresh Bitcoin address.
- Payment Detection: Your server runs a full node or connects to an Electrum server. It watches the blockchain for any transaction sent to that specific address.
- Fulfillment: When the payment appears, the server matches it to the invoice ID and marks the order as paid. It then triggers a webhook to your website to unlock the product or service.
- Sweeping: Later, you connect your hardware wallet (which holds the xprv) to a wallet interface. Because the wallet knows the same derivation path, it discovers all those incoming UTXOs (Unspent Transaction Outputs) and allows you to move them to cold storage.
This architecture supports high-volume operations. Merchants can issue tens of thousands of invoices per hour on modest hardware because address generation is just a fast elliptic curve multiplication, far less intensive than validating blocks.
Privacy Risks: The Double-Edged Sword
While xpubs secure your funds from hackers, they leak your financial history to anyone who possesses them. An xpub reveals every address derived from it, along with their balances and transaction timestamps. If you share your xpub with a billing provider, an accounting tool, and a portfolio tracker, all three entities can see your entire cash flow for that account.
This clustering undermines Bitcoin's privacy model, which recommends using a new address for every transaction to prevent linkability. In a self-hosted setup, you are intentionally linking all your merchant transactions under one public key.
To mitigate this, follow these best practices:
- Use Separate Accounts: Do not use your personal savings xpub for billing. Derive a separate account index (e.g., m/84'/0'/1' for billing) so your commercial activity is isolated from your personal holdings.
- Rotate xpubs Periodically: If you suspect your xpub has been exposed to untrusted parties, stop using it. Generate a new xpub from a different account index and update your billing configuration. Old addresses will remain unused, breaking the cluster.
- Avoid Reuse Across Integrations: Don't paste the same xpub into multiple third-party analytics dashboards unless you trust them completely. Each integration should ideally get its own dedicated account xpub.
Remember, the xpub itself doesn't identify you by name, but on-chain analysis firms can often link addresses to real-world identities through KYC exchanges or IP leaks. Treat your xpub as sensitive data, not just a public string.
Derivation Paths and Address Types
Not all xpubs are created equal. The prefix of your extended key indicates the type of address it generates and the derivation path it follows. Using the wrong type will cause your billing software to generate addresses that your hardware wallet doesn't recognize, leading to "lost" payments that are actually stuck in an unrecognized format.
| Prefix | Address Type | BIP Standard | Derivation Path Example |
|---|---|---|---|
| xpub | Legacy (P2PKH) | BIP44 | m/44'/0'/0' |
| ypub | Nested SegWit (P2SH-P2WPKH) | BIP49 | m/49'/0'/0' |
| zpub | Native SegWit (Bech32) | BIP84 | m/84'/0'/0' |
| vpub | Taproot (Bech32m) | BIP86 | m/86'/0'/0' |
Most modern merchants should use zpub (BIP84) for Bitcoin because Native SegWit offers lower transaction fees and better privacy than Legacy or Nested SegWit. Taproot (vpub) is becoming more common but requires newer wallet support. Always verify that your hardware wallet and billing software agree on the derivation path before sending real funds.
Multisig and Collaborative Custody
For businesses holding significant revenue, single-signature wallets pose a risk. If your hardware wallet is lost or stolen, you lose everything. Multisignature (multisig) wallets require multiple keys to authorize a transaction, such as a 2-of-3 setup where any two of three cosigners can approve a spend.
In a multisig context, xpubs become even more critical. To reconstruct a multisig wallet or monitor its balance, you need the xpubs of all cosigners. You combine these xpubs into a descriptor that defines the wallet structure. For example, a descriptor might look like `wsh(multi(2, xpub1..., xpub2..., xpub3...))`.
When integrating multisig with self-hosted billing:
- Backup All xpubs: Losing one xpub in a multisig setup can make it difficult to discover addresses without brute-forcing derivation paths. Store copies of all cosigner xpubs securely.
- Separate Signing from Watching: Your billing server only needs the combined xpubs to watch for incoming payments. The signing devices remain offline. This ensures that even if the server is compromised, the attacker cannot move funds without the private keys from the hardware wallets.
This setup provides robust security for treasuries. You can automate invoice generation and payment detection while maintaining strict control over outgoing transactions through manual approval on hardware devices.
Comparison: Self-Hosted vs. Custodial Processors
Why go through the trouble of setting up a server and managing xpubs when you could just sign up for a SaaS processor? The trade-offs come down to control, cost, and censorship resistance.
| Feature | Self-Hosted (e.g., BTCPay) | Custodial (e.g., BitPay, Coinbase) |
|---|---|---|
| Processing Fees | 0% platform fee (only network gas) | ~1.0% per transaction |
| Custody | You hold the keys (Non-custodial) | Processor holds the keys |
| Censorship Resistance | High (No central authority can freeze accounts) | Low (Processor can block payments or freeze assets) |
| Setup Complexity | High (Requires server admin skills) | Low (Sign up and go) |
| KYC Requirements | None (You are the operator) | Strict (Business verification required) |
Custodial processors offer convenience and fiat settlement options, but they introduce counterparty risk. If the processor goes bankrupt or decides to de-platform your business, your funds may be inaccessible. Self-hosted billing eliminates this risk. Your funds live directly on the blockchain, accessible via your xprv regardless of what happens to your server.
However, self-hosting demands technical competence. You need to manage a Linux server, configure Docker containers, maintain a full node or reliable Electrum connection, and handle TLS certificates. For solo founders and indie hackers comfortable with command-line tools, this is a manageable trade-off for the sake of sovereignty and lower costs.
Practical Implementation Steps
If you decide to build a self-hosted billing system, here is a realistic roadmap:
- Choose Your Stack: Start with established open-source solutions like BTCPay Server. It handles the complex parts of invoice management, webhook delivery, and multi-currency support.
- Set Up Infrastructure: Deploy a VPS with at least 4GB RAM and 500GB+ SSD storage for the blockchain database. Use Docker Compose for easy installation and updates.
- Generate Your xpub: On your hardware wallet (Ledger or Trezor), navigate to the export section. Choose the correct derivation path (e.g., BIP84 for zpub). Copy the extended public key carefully.
- Configure the Watch-Only Wallet: Import the xpub into your billing software. Set the gap limit to at least 20-100 addresses to ensure the system detects payments even if some addresses are skipped.
- Test Thoroughly: Send small test transactions to verify that the billing system detects payments and triggers webhooks correctly. Ensure your hardware wallet recognizes the received UTXOs.
- Implement Monitoring: Set up alerts for failed invoices or server downtime. Regularly backup your server configuration and verify your xpub backups.
For those looking for a more streamlined approach without managing infrastructure, modern gateways like TxNod offer a hybrid solution. They allow you to connect your Ledger or Trezor via WebHID or WebUSB, keeping your private keys local while handling payment detection and webhook notifications on their end. This reduces the operational burden of running a full node while maintaining non-custodial control over your funds.
Conclusion
Extended public keys are the backbone of scalable, self-sovereign crypto commerce. They bridge the gap between the need for automated, high-volume invoice generation and the requirement for secure, offline key storage. By understanding how xpubs work, respecting their privacy implications, and choosing the right derivation paths, merchants can build resilient billing systems that resist censorship and eliminate custodial risk.
Whether you run a full BTCPay Server stack or use a lightweight gateway that leverages your hardware wallet, the principle remains the same: keep your private keys offline, expose only your public keys, and let the blockchain do the heavy lifting.
Can someone steal my Bitcoin if they have my xpub?
No. An xpub (extended public key) can only generate receiving addresses. It cannot sign transactions or spend funds. To steal Bitcoin, an attacker would need your xprv (extended private key) or seed phrase, which should never leave your hardware wallet or offline storage.
What is the difference between xpub, ypub, and zpub?
These prefixes indicate the type of Bitcoin address generated. xpub is for Legacy addresses (higher fees), ypub is for Nested SegWit, and zpub is for Native SegWit (lower fees, recommended). vpub is used for Taproot addresses. Using the wrong type can lead to compatibility issues with wallets.
Do I need to run a full Bitcoin node for self-hosted billing?
Ideally, yes, for maximum privacy and reliability. However, many self-hosted setups like BTCPay Server can connect to external Electrum servers or other block explorers to detect payments. This reduces hardware requirements but introduces a slight dependency on third-party services.
Is self-hosted billing harder to set up than using BitPay?
Yes, initially. Self-hosting requires server administration skills, knowledge of Docker, and understanding of HD wallet derivation paths. Custodial services like BitPay offer plug-and-play dashboards. However, self-hosting saves long-term fees and removes counterparty risk.
How does an xpub help with privacy?
An xpub allows you to generate a unique address for every single transaction. This prevents address reuse, making it harder for observers to link multiple payments to the same entity. However, sharing the xpub itself reveals the entire history of that account, so it should be shared sparingly.