Categories:
Tags:
Last year I wanted to build up my Python skills and dive deep into Bitcoin. I decided to build a Bitcoin wallet from scratch. I had already read and followed along with the exercises in Programming Bitcoin, so a wallet prototype seemed like a good next step.
The wallet is a CLI application that allows you to generate a mnemonic seed phrase for a new HD wallet (more on what that is below), restore an existing HD wallet from a seed phrase, store and manage a list of contacts’ bitcoin addresses, and send bitcoin to your contacts. The wallet uses testnet by default, but you can switch to mainnet by setting the mode flag to prod
.
Let me take a few examples to show some of the core functions. The core entity that manages the user’s bitcoin private keys is the WalletManager
class. Probably the first thing you’ll want to do is generate a new wallet, so there’s a function to do that:
The generate
function generates a new seed phrase, initializes the HD wallet with the seed, and saves the seed to a file. The seed can be encrypted with a password if desired.
One of the amazing things about bitcoin is how portable it is - you just need to memorize 12 words and you can bring your bitcoin anywhere in your head with you. If you already have a seed phrase, you can load that into the wallet using the WalletManager.recover()
function:
You might notice a reference to “BIP”s in the comments. BIP-39 is a Bitcoin Improvement Proposal that defines a standard for mnemonic codes for generating deterministic keys. The wallet uses a BIP-39 compliant library to generate and recover seed phrases.
BIP-32 defines a standard for hierarchical, deterministic wallets. Basically this means that you can use one key (the root key) to derive others in a tree-like structure. BIP-32 specifies which levels of the tree are used for different purposes, such as for different cryptocurrencies or for different accounts within a wallet. Using BIP-32, the wallet can generate a new address for each transaction without needing to back up the wallet each time.