Bitcoin

リモートノードとのハンドシェイク

More than 1 year has passed since last update.
require "bitcoin"
require "eventmachine"

Bitcoin.network = :testnet3

class Connection < EM::Connection
  attr_reader :host, :port, :parser

  def initialize(host, port)
    @host = host
    @port = port
    @parser = Bitcoin::Protocol::Parser.new(self)
  end

  def post_init
    puts "connected."
    on_handshake_begin
  end

  def receive_data(data)
    parser.parse(data)
  end

  def on_handshake_begin
    puts "handshake begin."
    params = {
      block: 0,
      from: "127.0.0.1:18333",
      nonce: Bitcoin::Protocol::Uniq,
      to: "#{host}:#{port}",
      user_agent: "/bitcoin-ruby:#{Bitcoin::VERSION}/",
      version: 70015,
      time: Time.now.tv_sec
    }
    send_data(Bitcoin::Protocol.version_pkt(params))
  end

  def on_version(version)
    puts "receive version. Version:#{version.version}, UserAgent:#{version.user_agent}"
    send_data(Bitcoin::Protocol.verack_pkt)
  end

  def on_verack
    puts "receive verack. handshake complete."
  end

end

EM.run do
  EM.connect("localhost", 18333, Connection, "localhost", 18222)
end
$ ruby handshake.rb
connected.
handshake begin.
receive version. Version:70015, UserAgent:/Satoshi:0.15.99/
receive verack. handshake complete.