Files
sharp-coin/lib/em-bitcoin.rb
Nick Thomas d90b5585ef in-place commit: state machine was a silly idea
Replace with the outline of a simpler scheme. We should be able to
read messages from the wire now, and we will act on messages via a
passed-in instance.

Next is to implement send_version and send_verack; and the receive
equivalents in BitcoinServer. Then we can build a test rig to have
a play.

Once that's tested, we can implement a simple message and start on
the actor - which will be the first non-trivial bit of sharp-coin
proper. We'll be adding features and validations to em-bitcoin &
btc_wire_proto as sharp-coin begin to depend on them for correct
behaviour, and not before.
2011-06-09 22:05:03 +01:00

198 lines
6.2 KiB
Ruby

require 'eventmachine'
require 'stringio'
require 'btc_wire_proto'
module EventMachine
module Protocols
# Implements the TCP protocol that Bitcoin peers speak to each other. This
# module is mixed into both incoming and outgoing connections.
#
#
#
# Here is a list of states:
# send_ver, recv_ver, verify_ver
# send_verack, recv_verack
# wait, finish
#
# Documentation is here: https://en.bitcoin.it/wiki/Network
#
# @author Nick Thomas <nick@lupine.me.uk>
module BitcoinPeer
# Raised in case of any weird semantics / invalid syntax
class ProtocolError < StandardError
end
PE = ProtocolError
# The list of methods a valid actor will respond to.
ACTOR_METHODS = [
:log, # log(:level, message) - self-evident
:connection=, # Called with +self+ to allow actor interaction
:ready! # Called when the connection is ready to be used
]
def log(level, data)
@actor.log(level, data)
end
protected
def init_state!
@data = ""
@ready = nil
@actor.connection = self # Tell the actor about the connection
end
# Checks the current actor object to see if it is valid or not.
#
# The actor encapsulates the logic of the application using em-bitcoin. We
# call various methods on it when we receive events from the wire that the
# application may find interesting, such as receiving a new block or
# transaction. In response to these events, or independently, the actor
# can interact with us via its 'connection' attribute to, for instance,
# send a block or a transaction. It is likely to want to save received
# data somewhere so it can be interacted with later.
#
# @return[Array[true|false, msg]] Whether the actor is valid, and an
# optional message specifying why it's invalid, if it is.
def valid_actor?
return [false, "Actor not set"] if @actor.nil?
ACTOR_METHODS.each do |m|
return [false, "Actor doesn't implement all #{m}"] unless
@actor.respond_to?(m)
end
true
end
# The peer has given us data. Here, we split the data into packets and
# hand them off to +receive_packet+
# @param[String] str String containing the data passed in
def receive_data(str)
@data << str
log(:debug, "Received #{str.size}b. Buffer now #{@data.length}b")
finished = false
while !finished
begin
packet = BtcWireProto::Message.read(@data)
@data.slice!(0, packet.num_bytes - 1) # Remove data from buffer
if packet.cmd_sym
m = "receive_#{packet.cmd_sym}"
if self.respond_to?(m)
log(:info, "Received #{packet.cmd_sym}")
send(m, packet)
else
raise NotImplementedError.new("#{m} not implemented")
end
else
log(:warn, "Received packet with no command, discarding it")
log(:debug, packet)
end
rescue EOFError
finished = true
end
end
log(:debug, "Leaving receive_data with #{@data.length} bytes in buffer")
end
# receive_version and receive_verack implementations differ in client &
# server, so are implemented there.
# Send a 'version' message to the peer.
def send_version
# TODO
end
# Send a 'verack' message to the peer
def send_verack
# TODO
end
end
# EventMachine protocol class that handles an *outgoing* connection to
# another bitcoin peer. Common functionality (p2p!) is held in BitcoinPeer.
#
# Initiation: send version.
# receive verack, receive version (any order) or conn close
# send verack or conn close
#
# @author Nick Thomas <nick@lupine.me.uk>
class BitcoinClient < EM::Connection
include BitcoinPeer
# @param[Object] actor See the BitcoinPeer#valid_actor?
def initialize(actor)
super
@actor = actor
result, msg = valid_actor?
raise ArgumentError.new("Invalid actor: #{msg}") unless result
init_state!
end
def post_init
end
# As soon as the TCP connection is up, we send a version message.
def connection_completed
send_version
@ready = :version_sent
end
# We receive this in response to our version message. We don't need to do
# anything with it though.
def receive_verack(p)
raise PE.new("Received verack inappropriately") unless
@ready == :version_sent
log(:info, "Peer accepted our version message")
end
# The peer sends this after it's received our version. We check that we
# can communicate with the specified version and either return a verack,
# or close the connection.
def receive_version(p)
raise PE.new("Received version inappropriately") unless
@ready == :version_sent
log(:info, "Peer tells us its version is #{p.payload.version}")
send_verack
@ready = true
@actor.ready!
end
end
# EventMachine protocol class that handles an *incoming* connection from
# another bitcoin peer. Common functionality (p2p!) is held in BitcoinPeer
#
# Servers wait for the client to initiate the connection by sending a
# version message.
#
# @author Nick Thomas <nick@lupine.me.uk>
class BitcoinServer < EM::Connection
include BitcoinPeer
# @param[Object] actor See the BitcoinPeer#valid_actor? method
def initialize(actor)
super
@actor = actor
result, msg = valid_actor?
raise ArgumentError.new("Invalid actor: #{msg}") unless result
init_state!
end
# We should receive this as the very first message on the wire
def receive_version(p)
# TODO
end
# We should only receive this after sending our own version
def receive_verack(p)
# TODO
end
end
end
end