Skip to content

Instantly share code, notes, and snippets.

@throughnothing
Created February 23, 2015 08:24
Show Gist options
  • Select an option

  • Save throughnothing/c261f0beafd74f7968d5 to your computer and use it in GitHub Desktop.

Select an option

Save throughnothing/c261f0beafd74f7968d5 to your computer and use it in GitHub Desktop.
SPV Method from Breadwalet

Breadwallet SPV

https://github.com/voisine/breadwallet/blob/4c169e4496e868a98230002978f16b8ad8d5b0ce/BreadWallet/BRPeer.m#L342-L368

The standard blockchain download protocol works as follows (for SPV mode):

  • local peer sends getblocks
  • remote peer reponds with inv containing up to 500 block hashes
  • local peer sends getdata with the block hashes
  • remote peer responds with multiple merkleblock and tx messages
  • remote peer sends inv containg 1 hash, of the most recent block
  • local peer sends getdata with the most recent block hash
  • remote peer responds with merkleblock
  • if local peer can't connect the most recent block to the chain (because it started more than 500 blocks behind), go back to first step and repeat until entire chain is downloaded

We modify this sequence to improve sync performance and handle adding bip32 addresses to the bloom filter as needed:

  • local peer sends getheaders
  • remote peer responds with up to 2000 headers
  • local peer immediately sends getheaders again and then processes the headers
  • previous two steps repeat until a header within a week of earliestKeyTime is reached (further headers are ignored)
  • local peer sends getblocks
  • remote peer responds with inv containing up to 500 block hashes
  • local peer sends getdata with the block hashes
  • if there were 500 hashes, local peer sends getblocks again without waiting for remote peer
  • remote peer responds with multiple merkleblock and tx messages, followed by inv containing up to 500 block hashes
  • previous two steps repeat until an inv with fewer than 500 block hashes is received
  • local peer sends just getdata for the final set of fewer than 500 block hashes
  • remote peer responds with multiple merkleblock and tx messages
  • if at any point tx messages consume enough wallet addresses to drop below the bip32 chain gap limit, more addresses are generated and local peer sends filterload with an updated bloom filter
  • after filterload is sent, getdata is sent to re-request recent blocks that may contain new tx matching the filter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment