Skip to content

Commit

Permalink
Extract web.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
oguzbilgic committed Dec 1, 2018
1 parent 31c41e7 commit f652e0f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 33 deletions.
36 changes: 3 additions & 33 deletions main.rb
Original file line number Diff line number Diff line change
@@ -1,43 +1,13 @@
require 'sinatra'
require "sinatra/json"
require 'httparty'

require "./web.rb"
require "./block.rb"
require "./blockchain.rb"

$blockchain = Blockchain.new
$nodes = []
PORT = 4000+rand(1000)

class Web < Sinatra::Base
configure do
set :port, PORT
set :quiet, true
set :logging, false
end

post '/connect' do
puts "Node connected: #{params['ip']}"
$nodes << params['ip']
end

post '/relay' do
block = Block.from_json_str(request.body.read)
$blockchain.add_relayed_block block
puts "Received: #{block}"
end

get '/blocks' do
json $blockchain.last.to_hash
end

get '/blocks/:index' do
index = params['index'].to_i

return status 404 if index > $blockchain.last.index

json $blockchain.block_at(index).to_hash
end
end

# Web Thread
Thread.new {
Expand All @@ -51,7 +21,7 @@ class Web < Sinatra::Base
puts "Seed node: #{ARGV[0]}"

# Connect to seed node
HTTParty.post "#{ARGV[0]}/connect", body: { ip: "http://localhost:#{PORT}" }
HTTParty.post "#{ARGV[0]}/connect", body: { ip: "http://localhost:#{$port}" }

loop do
index = $blockchain.last.index.to_i + 1
Expand Down
33 changes: 33 additions & 0 deletions web.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# TODO Don't depend on global variables $blockchain, $nodes and $PORT
$port = 4000+rand(1000)

class Web < Sinatra::Base
configure do
set :port, $port
set :quiet, true
set :logging, false
end

post '/connect' do
puts "Node connected: #{params['ip']}"
$nodes << params['ip']
end

post '/relay' do
block = Block.from_json_str(request.body.read)
$blockchain.add_relayed_block block
puts "Received: #{block}"
end

get '/blocks' do
json $blockchain.last.to_hash
end

get '/blocks/:index' do
index = params['index'].to_i

return status 404 if index > $blockchain.last.index

json $blockchain.block_at(index).to_hash
end
end

0 comments on commit f652e0f

Please sign in to comment.