# This code is quite straightforward, one exception being the inclusion of a random string from the receiving party, Bob, in this case,
# in the hash. This gives Bob assurance that Alice didn't precompute two hashes, "heads random string" and "tails another random string",
# with the same hash value. This is really paranoia in the extreme as modern hashes are collision-free to a very high degree of probability.

# The following Ruby program is an implementation of coin-flipping using a cryptographic hash:

#! /usr/bin/ruby

require 'digest/sha1'

MAX_S, CHARS, FIRST_ASCII = 55, 26, 97
alice_s, bob_s = '', ''

MAX_S.times { alice_s += (rand(CHARS) + FIRST_ASCII).chr}
puts "Alice's string is \"#{alice_s}\"."
MAX_S.times { bob_s += (rand(CHARS) + FIRST_ASCII).chr}
puts "\nBob's   string is \"#{bob_s}\"."
outcome = rand > 0.5 ? 'heads' : 'tails'
s_to_hash = outcome + ' ' + alice_s + ' ' + bob_s
hash_out = Digest::SHA1.hexdigest(s_to_hash)

puts <<EOS

Alice chooses #{outcome} and sends Bob the hash of "#{outcome} " + ' ' + her string + ' ' +
Bob's string = "#{hash_out}".
EOS

bob_guess = rand > 0.5 ? 'heads' : 'tails'
puts "\nBob chooses #{bob_guess}\n\n"

if bob_guess == outcome
  puts 'Bob wins'
else
  puts 'Alice wins'
  puts "Alice sends Bob her string so that he can do the hash and confirm her choice."
end

# End of Code
			 
# Test Ouput 1 (Alice wins):

# Alice's string is "wjiikfhekwqzxujfuhjthckfwmvvaxangyywzgompuvnkkcrhslocfy".

# Bob's   string is "fmaqrygggmujgeddvjmiiqavflbgpgdhoiczeavksyfidnkrjucpbhp".

# Alice chooses tails and sends Bob the hash of "tails" + her string + Bob's string = "aa011c720e95f2d4a60506e0ed274333bbf7af78"

# Bob chooses heads

# Alice wins
# Alice sends Bob her string so that he can do the hash and confirm her choice.

# Test Output 2 (Bob wins):

# Alice's string is "pbnhmccgedothljpqlkslzmryrosgvpvncbfciphrcoribrlqgcsodc".

# Bob's   string is "butvffyzoilxestbfbibnllhmpzczvnqtklhdoappoopnyzvdrlatqi".

# Alice chooses tails and sends Bob the hash of "tails" + her string + Bob's string = "cc0ddee134a12e5faa772db8c24818c2a1a67e99"

# Bob chooses tails

# Bob wins