Unit 4: Bitcoin Network, Payments, Clients and APIs

CSE436 — Blockchain 10 min read

I. Foundations of Bitcoin

Bitcoin is a decentralized electronic cash system introduced by Satoshi Nakamoto in 2008 and launched on 3 January 2009. It combines a peer-to-peer network, public-key cryptography, proof-of-work mining, and a replicated blockchain to transfer value without a central payment authority.

  • Native unit: Bitcoin is denoted by BTC; one bitcoin contains 100,000,000 satoshis, the smallest on-chain unit.
  • Ledger model: The blockchain records transactions as spent and newly created unspent transaction outputs, or UTXOs.
  • Ownership convention: Control is demonstrated by producing a valid digital signature with the private key authorized by an output’s locking script.
  • Consensus basis: Fully validating nodes independently enforce rules such as valid signatures, permitted block structure, and prevention of double-spending.
  • Proof of work: Miners repeatedly hash block headers to find a value below the network target; cumulative proof of work determines the accepted chain.
  • Supply policy: Block subsidies halve every 210,000 blocks, approximately every four years, and total issuance approaches 21 million BTC.
  • Pseudonymity: Addresses are identifiers rather than real names, but public transaction history can permit address clustering and other forms of analysis.
  • Irreversibility: Confirmed payments have no built-in chargeback mechanism; practical finality increases as further blocks are added.

II. Network Architecture and Protocol Development

A. The Bitcoin network

The Bitcoin network is a peer-to-peer system in which nodes relay, validate, and store transactions and blocks without relying on a central server.

  • Node discovery: A new node may obtain initial peer addresses from DNS seeds, then exchange further addresses through peer-to-peer messages.
  • Transaction propagation: A wallet submits a signed transaction to a node, which validates it and relays it to peers; accepted unconfirmed transactions normally enter each node’s mempool.
  • Node roles:
    • Full nodes: Validate blocks and transactions against all consensus rules.
    • Mining nodes: Construct candidate blocks and perform SHA-256 proof of work.
    • Light clients: Obtain limited blockchain information without independently storing and validating every block.
  • Block production: Difficulty is adjusted every 2,016 blocks to maintain an average interval close to ten minutes.
  • Confirmation: A transaction included in a block has one confirmation; each block built above it adds another and makes reorganization increasingly costly.
  • Network distinction: Mainnet carries real value, testnet uses valueless test coins, and regtest creates a private chain where blocks can be generated immediately.

B. Innovation in Bitcoin

Bitcoin’s central innovation is the integration of earlier technologies into a system that solves decentralized ordering and limits double-spending.

  • Combined mechanisms: Hash-linked blocks, proof of work, digital signatures, peer-to-peer communication, and economic incentives operate as one system.
  • Nakamoto consensus: Nodes follow the valid chain with the greatest cumulative proof of work rather than accepting a vote from identified participants.
  • Difficulty and issuance: Automatic difficulty adjustment separates block timing from changes in mining power, while halvings create predictable monetary issuance.
  • Programmable conditions: Bitcoin Script supports conditions such as signatures, hash locks, multisignature policies, and timelocks without being a general-purpose looping language.
  • Protocol improvement: Bitcoin Improvement Proposals, or BIPs, document proposed standards; BIP32 defines hierarchical deterministic wallets, while BIP39 describes mnemonic seed phrases.
  • Upgrade principle: Backward-compatible soft forks tighten validity rules; incompatible hard forks broaden or replace rules and risk dividing the network.

C. Advanced protocols

Advanced Bitcoin protocols combine signatures, scripts, timelocks, and off-chain communication to provide functions beyond ordinary single-signature payments.

  • Multisignature control: An (m)-of-(n) policy requires at least (m) authorized signatures from (n) keys; a 2-of-3 arrangement can divide control among three devices.
  • Lightning Network: Two parties lock bitcoin in an on-chain channel and exchange signed commitment transactions off-chain; only channel opening and closing normally require blockchain entries.
  • Hashed timelock contracts: HTLCs make payment conditional on revealing a secret before a deadline, enabling routed Lightning payments without trusting intermediate nodes.
  • Atomic swaps: Compatible hash locks and timelocks permit exchange across systems so that either both transfers complete or both parties recover their funds.
  • Taproot: Activated in November 2021, Taproot introduced Schnorr signatures and improved the privacy and efficiency of many complex spending policies.
  • Trade-offs: Off-chain protocols improve speed and scalability but require liquidity management, monitoring, backups, and careful handling of timeout conditions.

D. Bitcoin investment

Bitcoin investment involves exposure to a scarce digital asset whose market price is determined by global demand, liquidity, regulation, and perceived utility.

  • Return calculation: Ignoring fees, percentage return is:
TEXT
Return (%) = ((P₁ − P₀) / P₀) × 100

Here, (P₀) is the purchase price and (P₁) is the later sale or valuation price.

  • Volatility risk: BTC trades continuously and can experience large price movements within hours; historical appreciation does not guarantee future returns.
  • Custody risk: Exchange failure, phishing, malware, and loss of seed words can cause permanent loss even when the Bitcoin network remains secure.
  • Market exposure: Investors may hold bitcoin directly or use regulated exchange-traded products and company shares, each involving different ownership and counterparty structures.
  • Due diligence: Relevant factors include fees, legal jurisdiction, tax treatment, liquidity, custody arrangements, and whether withdrawals to a personal wallet are supported.
  • Risk discipline: Leverage magnifies both gains and losses and can trigger liquidation before a long-term price thesis is realized.

III. Ownership, Payments, and Exchange

A. Wallets

A Bitcoin wallet manages cryptographic keys and constructs transactions; the bitcoin itself remains represented by UTXOs on the blockchain.

  • Key relationship: A private key authorizes spending, while a derived public key or script participates in generating receiving addresses.
  • Deterministic wallets: A single seed can derive many keys through a hierarchical structure, making secure seed backup more practical than backing up every key separately.
  • Wallet categories:
    1. Hot wallets: Internet-connected desktop, mobile, or web wallets offer convenience but face greater malware and remote-attack exposure.
    2. Cold wallets: Hardware devices or securely isolated signers reduce online exposure but still require protected backups.
  • Custodial distinction: In a custodial wallet, a service controls the keys; in a non-custodial wallet, the user controls them and bears recovery responsibility.
  • Address hygiene: A fresh receiving address improves privacy, while address reuse makes transaction relationships easier to trace.
  • Backup security: Seed words must remain confidential, offline, and recoverable; anyone obtaining them can usually reconstruct the wallet.

B. Bitcoin payments

A Bitcoin payment consumes existing UTXOs and creates new outputs assigning specified amounts to new spending conditions.

  • Inputs and outputs: Inputs reference previous outputs and provide unlocking data; outputs state amounts in satoshis and locking scripts.
  • Change output: If selected inputs exceed the payment plus fee, the wallet normally returns the remainder to a newly generated change address.
  • Fee equation:
TEXT
Fee = Σ(inputs) − Σ(outputs)

All quantities are measured in satoshis; the fee is not a separate transaction output.

  • Fee market: Wallets commonly estimate fees in satoshis per virtual byte, written sat/vB; higher rates generally receive faster miner selection during congestion.
  • Payment flow: The payer verifies the address and amount, signs the transaction, broadcasts it, and monitors its transaction identifier and confirmation status.
  • Practical verification: A merchant may accept a low-value transaction before confirmation, but high-value transfers commonly wait for multiple confirmations.
  • Operational caution: Bitcoin addresses and networks must match; an on-chain address must not be treated as a Lightning invoice.

C. Buying and selling Bitcoin

Bitcoin can be exchanged through centralized platforms, peer-to-peer markets, brokers, or direct trades, each with different custody and settlement risks.

  • Centralized exchange: A customer deposits conventional currency, places a market or limit order, and may later withdraw BTC to an external address.
  • Order types:
    1. Market order: Executes against available orders immediately but may suffer slippage.
    2. Limit order: Executes only at the specified price or better but may remain unfilled.
  • Total cost: Relevant charges include trading commission, bid–ask spread, deposit costs, and blockchain withdrawal fees.
  • Identity requirements: Regulated services commonly apply know-your-customer and anti-money-laundering checks using identity and residence information.
  • Self-custody transfer: A small test withdrawal can verify the address and network before a larger transfer.
  • Selling process: BTC is deposited or delivered, sold through an order, and the resulting currency is withdrawn; taxable gains may arise according to local law.

IV. Bitcoin Clients, Command Line, and Software

A. Bitcoin client installation

A Bitcoin client connects to peers and may validate the complete blockchain, provide wallet functions, and expose command-line or programming interfaces.

  • Bitcoin Core: The reference implementation includes bitcoind, the background daemon; bitcoin-qt, the graphical client; and bitcoin-cli, the RPC command-line tool.
  • Secure acquisition: Installation files should come from the official project source, with published signatures or checksums verified before execution.
  • Storage modes: An archival node retains the full blockchain, while a pruned node validates all blocks but discards older block data beyond its configured storage target.
  • Synchronization: Initial block download verifies the chain from the genesis block onward and can require substantial bandwidth, storage, and processing time.
  • Configuration: bitcoin.conf can select options such as server=1, prune=, or regtest=1; RPC access should not be exposed openly to the internet.
  • Safe learning environment: Regtest avoids risking real funds and allows deterministic local block generation.

B. Experimenting further with bitcoin-cli

bitcoin-cli sends JSON-RPC requests to a running Bitcoin Core node and displays the returned structured data.

  • Network inspection:
BASH
bitcoin-cli -regtest getblockchaininfo
bitcoin-cli -regtest getnetworkinfo

These commands report chain state, block count, verification progress, software version, and peer-network information.

  • Wallet creation:
BASH
bitcoin-cli -regtest createwallet "lab"
ADDR=$(bitcoin-cli -regtest getnewaddress)

ADDR stores a newly generated regtest receiving address.

  • Block generation:
BASH
bitcoin-cli -regtest generatetoaddress 101 "$ADDR"
bitcoin-cli -regtest getbalance

Generating 101 blocks makes the earliest coinbase reward spendable because coinbase outputs require 100 confirmations.

  • Transaction inspection:
BASH
bitcoin-cli -regtest listunspent
bitcoin-cli -regtest getrawtransaction TXID true

TXID is the transaction identifier; the Boolean true requests decoded JSON.

  • Safety boundary: Command options, wallet names, and selected network must be checked before sending because mainnet commands can move real funds.

C. Bitcoin programming

Bitcoin programming usually means integrating software with a node through JSON-RPC, processing blockchain data, or constructing and signing transactions with suitable libraries.

  • RPC model: A program submits a method name and parameters to Bitcoin Core’s authenticated endpoint and receives a JSON result or error object.
  • Python example:
PYTHON
from bitcoinrpc.authproxy import AuthServiceProxy

rpc = AuthServiceProxy(
    "http://user:password@127.0.0.1:18443"
)
info = rpc.getblockchaininfo()
print(info["blocks"])

Port 18443 is the usual regtest RPC port; credentials must match the local secure configuration.

  • Common operations: Applications query blocks, inspect UTXOs, estimate fees, create addresses, and monitor transaction confirmations.
  • Transaction lifecycle: Software selects inputs, defines outputs, calculates change and fees, signs authorized inputs, validates the result, and broadcasts it.
  • Precision rule: Monetary calculations should use integer satoshis or exact decimal types rather than binary floating-point values.
  • Security separation: Watch-only systems can monitor addresses without private keys, while offline signers can authorize transactions without exposing keys to an internet-connected machine.
  • API caution: RPC interfaces are powerful administrative tools; authentication, localhost binding, least privilege, input validation, and error handling are essential.