Skip to content

Commit

Permalink
Extract network.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
oguzbilgic committed Dec 1, 2018
1 parent 94721c9 commit d246af5
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 30 deletions.
32 changes: 4 additions & 28 deletions main.rb
Expand Up @@ -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 {
Expand All @@ -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!
43 changes: 43 additions & 0 deletions 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
4 changes: 2 additions & 2 deletions 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
Expand All @@ -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
Expand Down

0 comments on commit d246af5

Please sign in to comment.