#coding:utf-8
require 'em-websocket'
require 'net/http'
require 'uri'
require 'json'
class BitcoinRPC
def initialize(service_url)
@uri = URI.parse(service_url)
end
def method_missing(name, *args)
post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
resp = JSON.parse( http_post_request(post_body) )
resp['result']
end
def http_post_request(post_body)
http = Net::HTTP.new(@uri.host, @uri.port)
request = Net::HTTP::Post.new(@uri.request_uri)
request.basic_auth @uri.user, @uri.password
request.content_type = 'application/json'
request.body = post_body
http.request(request).body
end
class JSONRPCError < RuntimeError; end
end
h = BitcoinRPC.new('http://***:***@***:***')
Process.daemon(nochdir=true) if ARGV[0] == "-D"
connections = Array.new
$ws = nil
$lasts = (h.getbalance("stock")).to_s
nxt = rand(15..25)
thr = Thread.new do
while $ws == nil
sleep(1)
end
while true
sleep(nxt)
hash = Hash.new
nxt = rand(25..35)
win = $win
$win = nil
if win == nil then
s = "no one won ... new game"
$ws.each { |con|
con.send( s )
}
next
end
s = "winner is ... " + win
$ws.each { |con|
con.send( s )
}
s = win + " get 0.01MONA .... new game"
h.sendfrom( "stock" , win , 0.01 )
$ws.each { |con|
con.send( s )
}
end
end
hash = Hash.new
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 51234) do |ws|
ws.onopen {
ip = (Socket.unpack_sockaddr_in(ws.get_peername))[1]
puts "user " + ip + " come"
connections.push(ws) unless connections.index(ws)
$ws = connections
}
ws.onmessage { |msg|
t = h.validateaddress( msg )
ip = (Socket.unpack_sockaddr_in(ws.get_peername))[1]
if t["isvalid"] == true && ( hash.has_key?(ip) == false || hash[ip] + 4 < Time.now.to_i ) then
hash[ip] = Time.now.to_i
$win = msg
ws.send( "current = " + $win )
connections.each {|con|
con.send( "current = " + $win ) unless con == ws
}
end
}
ws.onclose { puts "" }
end