DEV Community

Andreas Tzionis
Andreas Tzionis

Posted on

How Bitcoin (really) works?

1. Discovering seed nodes

Bitcoin nodes discover other nodes from a few hardcoded DNS servers.

discover seed nodes

Script: https://github.com/liveduo/bitcoin-scripts/blob/main/1-discover-nodes.js*

*33 lines of code (no npm dependencies)

2. Connecting to a node

Bitcoin messages are sent over TCP and contain a payload and some metadata (type, length and checksum).

connect to node

The first messages sent are "version" and "verack" messages are used to establish a connection. Then, "ping" / "pong" messages are sent periodically to signal the connection is still active.

establishing a connection

Script: https://github.com/liveduo/bitcoin-scripts/blob/main/2-connect-node.js*

*90 lines of code (no npm dependencies)

3. Creating an address

Bitcoin addresses are derived from private keys (or seed phrases). Mainnet and testnet addresses have different formats (for most address types).

create a bitcoin address

Script: https://github.com/liveduo/bitcoin-scripts/blob/main/3-create-address.js*

*67 lines of code (depends on bs58 and secp256k1 npm packages)

4. Creating a transaction

Transactions contain inputs and outputs. Inputs validate the owner of the transaction and outputs indicate where the coins should go.

create a bitcoin tx

Script: https://github.com/liveduo/bitcoin-scripts/blob/main/4-create-tx.js*

*65 lines of code (no npm dependencies)

5. Broadcasting a transaction

Node advertise block and tx hashes with "inv" messages. Interested nodes ask for the data with "getdata" messages and receive them as "tx" or "block" messages.

broadcast bitcoin tx

Script: https://github.com/liveduo/bitcoin-scripts/blob/main/5-broadcast-tx.js*

*163 lines of code (no npm dependencies)

What's next

Find more details on:
https://www.tzionis.com/bitcoin-protocol-in-45-minutes

PS: There are embedded Repl.it scripts that you can run right within the blog post so you don't have to setting up anything locally

Top comments (0)