diff --git a/main.rb b/main.rb index bc3ca6c..bce119f 100644 --- a/main.rb +++ b/main.rb @@ -5,9 +5,10 @@ require "./web.rb" require "./block.rb" require "./blockchain.rb" +require "./network.rb" $blockchain = Blockchain.new -$nodes = [] +$network = Network.new $blockchain, "http://localhost:#{$port}", ARGV[0] # Web Thread Thread.new { @@ -16,35 +17,10 @@ } # Download blocks from the seed node -if ARGV[0] - $nodes << ARGV[0] - puts "Seed node: #{ARGV[0]}" - - # Connect to seed node - HTTParty.post "#{ARGV[0]}/connect", body: { ip: "http://localhost:#{$port}" } - - loop do - index = $blockchain.last.index.to_i + 1 - response = HTTParty.get("#{ARGV[0]}/blocks/#{index.to_s}") - - break if response.code != 200 - - $blockchain << Block.from_json_str(response.body) - # TODO use add_relayed_block instead - puts "Downloaded #{$blockchain.last}" - end - - puts "Finished downloading the chain" -end +$network.download_chain $blockchain.on_solve do |block| - $nodes.each do |node| - begin - HTTParty.post "#{node}/relay", body: block.to_hash.to_json - rescue - #remove node? - end - end + $network.broadcast_block block end $blockchain.work! diff --git a/network.rb b/network.rb new file mode 100644 index 0000000..e559849 --- /dev/null +++ b/network.rb @@ -0,0 +1,43 @@ +class Network + def initialize blockchain, our_ip, node = nil + @blockchain = blockchain + @our_ip = our_ip + @nodes = node ? [node] : [] + end + + def add_node node + @nodes << node + end + + def broadcast_block block + @nodes.each do |node| + begin + HTTParty.post "#{node}/relay", body: block.to_hash.to_json + rescue + #remove node? + end + end + end + + def download_chain + return if @nodes.empty? + + puts "Seed node: #{@nodes.first}" + + # Connect to seed node + HTTParty.post "#{@nodes.first}/connect", body: { ip: @our_ip } + + loop do + index = @blockchain.last.index.to_i + 1 + response = HTTParty.get("#{@nodes.first}/blocks/#{index.to_s}") + + break if response.code != 200 + + @blockchain << Block.from_json_str(response.body) + # TODO use add_relayed_block instead + puts "Downloaded #{@blockchain.last}" + end + + puts "Finished downloading the chain" + end +end diff --git a/web.rb b/web.rb index 1b6b225..1909e1b 100644 --- a/web.rb +++ b/web.rb @@ -1,4 +1,4 @@ -# TODO Don't depend on global variables $blockchain, $nodes and $PORT +# TODO Don't depend on global variables $blockchain, $netwoek and $PORT $port = 4000+rand(1000) class Web < Sinatra::Base @@ -10,7 +10,7 @@ class Web < Sinatra::Base post '/connect' do puts "Node connected: #{params['ip']}" - $nodes << params['ip'] + $network.add_node params['ip'] end post '/relay' do