Sites like bittleships and luckycoin casino make it look so easy to deposit/spend/earn/withdrawl bitcoin, and I was wondering if someone would help me set that up.
It's pretty easy to do if you run your own bitcoind. You use the bitcoind JSON RPC to detect player deposits, and all other transactions are just INSERTs into your database. Then, a SQL query like this can give you the player's balance:
SELECT SUM(AMOUNT) FROM TXNS WHERE UID=[user's id];
Combine this with client-side polling, and voila!
SUM(AMOUNT) will quickly slow down your site if you plan to have millions of users. A simpler strategy is to do a small incremental computation with each transaction and record the new total balance with each transaction. That way you just need a simple SELECT to get the balance.
Keeping running balances without checking them frequently against sums is
not safe when building a site that deals with real money. What if your application or your database goes down in the middle of an update? Moreover, timestamps can and do change on bitcoin transactions after they've shown up in a wallet. You can't just look at the last timestamp and take all the transactions that happened in it, or you'll end up polling the same transactions twice and adding them to the user's running database sum. So for data consistency you'd then need to compare the TXID against all TXIDs you've processed before, which is a much slower operation than a simple SUM of the user's transactions compared to that user's wallet account balance.
We use (basically) the SUM(AMOUNT) strategy. If you're worried about speed when you have a million users, partition your transactional database by user IDs, or shard it over multiple instances. If you're running bitcoind, you should be running it on a separate dedicated machine anyway, and it's doubtful you'll have a very efficient system if you're running one instance with a million wallets anyway. So have a db over there on each bitcoind machine that does the summing for a particular group of users (100k would probably be an upward reasonable limit), and then opens a socket to send the results to your game server. SUM() on a primary key is plenty fast over millions of rows even without partitioning.
Also bear in mind that if you ever find yourself running a successful Bitcoin casino with millions of users, you will probably have plenty of spare cash for server upgrades. Writing NoSQL or non-ACID code that trusts your application layer to never miss or repeat a single real-money transaction will create its own scaling problems and is very, very unsafe.