-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
94721c9
commit d246af5
Showing
3 changed files
with
49 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters