#!/usr/bin/perl use DB_File; use CGI; my $COINLIFETIME = 30; my %coins_db; my $cgi = CGI->new(); my $requestedcoinid = $cgi->param('coinid'); my $requestedaction = $cgi->param('action'); my $coinsindb=0; my $flippedcoinsindb=0; sub alert { print "ERROR: @_[0]\n"; } sub printcoin { print ""; print ""; print "http://$ENV{HTTP_HOST}/@_[0]"; print ""; print ""; } sub printresult { if ( @_[0] == 0 ) { print "Heads"; } else { print "Tails"; } } if (-e "var/coins.db") { tie (%coins_db, DB_File, "var/coins.db") || die ("Cannot open var/coins.db"); } else { tie (%coins_db, DB_File, "var/coins.db", O_CREAT|O_RDWR, 0640) || die ("Cannot create or open var/coins.db"); } foreach my $key ( keys %coins_db ) { @value = split(/,/, $coins_db{$key}); if ( time-$value[0] > $COINLIFETIME*(60*60*24) ) { delete $coins_db{$key}; } $coinsindb++; if ( ($#value + 1) == 3 ) { $flippedcoinsindb++; } } print "Content-type: text/html\n\n"; print ""; print ""; print "flipacoin.org - The Internet's first coinflipping service."; print ""; print ""; if ( ! ($requestedcoinid =~ /\A[a-z0-9]*\z/) ) { alert("You sent me an invalid coin!"); exit; } if ( ! ($requestedaction =~ /\A[a-z]*\z/) ) { alert("You sent me an invalid action!"); exit; } print "During the last $COINLIFETIME days $flippedcoinsindb/$coinsindb coins were flipped/created. | "; print "

flipacoin.org - The Internet's first coinflipping service.

"; if ( length($requestedcoinid) == 0 && $requestedaction eq "" ) { print "
[Create a coin]"; print " to make a decision."; } elsif ( length($requestedcoinid) == 0 && $requestedaction eq "create" ) { my @chars = ("a".."z", "0".."9"); my $newcoinid; $newcoinid .= $chars[rand @chars] for 1..13; while ( exists $coins_db{$newcoinid} ) { $newcoinid = ""; $newcoinid .= $chars[rand @chars] for 1..13; } $coins_db{$newcoinid} = time; print "Created a new coin "; printcoin($newcoinid); print " for you.
"; print "
"; print "Send the coin to the other party and tell them to flip it to make a decision."; } elsif ( length($requestedcoinid) > 0 ) { if ( ! exists $coins_db{$requestedcoinid} ) { alert("The coinid $requestedcoinid does not exist!"); exit; } my @coininfo = split(/,/, $coins_db{$requestedcoinid}); my $coininfosize = $#coininfo + 1; printcoin($requestedcoinid); print "
"; print "
";
    print "Creation time: " . localtime($coininfo[0]);
    print "
"; if ( $coininfosize == 1 && $requestedaction eq "" ) { print "Status: Not yet flipped "; print ""; print "[flip it]"; print ""; } elsif ( $coininfosize == 1 && $requestedaction eq "flip" ) { $result = int(rand(2)); $coins_db{$requestedcoinid} = $coins_db{$requestedcoinid} . "," . time . "," . $result; print "Status: Just flipped"; print "
"; print "Result: "; printresult($result); } elsif ( $coininfosize == 3 ) { print "Status: Flipped @ " . localtime($coininfo[1]); print "
"; print "Result: "; printresult($coininfo[2]); } print "
"; } print ""; print ""; untie(%coins_db); exit;