We are currently working on implementing an spv-node for the Bitcoin protocol in Scala. One of the most obvious things you want to do with Bitcoin is a receive a payment, there are numerous ways to do this, but one of the simplest ways in my opinion is modeling it with a finite state machine.

From wikipedia:

A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), or simply a state machine, is a mathematical model of computation used to design both computer programs and sequential logic circuits. It is conceived as an abstract machine that can be in one of a finite number of states.

If we think abstractly about a payment over the bitcoin network, a payment we are receiving from another user on the network has a certain set of states. We can model these various states with a finite state machine fairly easily, when one state is complete we transition to another state. Scala has a very useful library called Akka, which we are using for the networking on bitcoin network. Inside of Akka, there is support for finite state machines here using the `become` construct.

In bitcoin-s’ payment actor, we use this to transition from various states inside of the actor. For instance, when a payment is made to an address we request the full transaction using the GetData message on the bitcoin network. Once we receive the full transaction, we verify that an output on that transaction paid to our address.

There are 6 states that our payment actor goes through when confirming a payment on the bitcoin network

1.) Creates a bloom filter, sends the bloom filter to a node on the network

2.) Nodes matches the bloom filter, sends a txid that matched the filter back to us via an inventory message

3.) We request the full transaction using a get data message.

4.) We verify the transaction given to us has an output that matches the address we expected a payment to.

5.) When another block is announced on the network, we send a merkle block message to our peer on the network to see if the transaction was included in that block.

6.) Verify that the transaction is included in the block with the information given by the merkle block message according to BIP37.

This is really useful to to manage the various states that a bitcoin payment can be in. We have used finite state machines in other places, for instance our PeerMessageHandler, which handles all of the logic for connecting to a peer on bitcoin network.

Feel free to follow along with the on going development happening on bitcoin-s-core or bitcoin-s-spv-node

Also, feel free to follow me, or my company, SuredBits, on twitter. We have some big news coming later this week