Blockchain project #5: A fistful of Satoshis

A story of gambling, synchronicity, randomness and cowboys

Thomas Vanderstraeten
10 min readMar 7, 2018
Do you have what it takes to fight Billy the Kid in a duel?

Welcome to the brave Western world with AfistfulofSatoshis! Blockchain project #5 definitely has taken a bit more time than expected, partly due to an intense product go-live at Seraphin, my other tech passion besides Blockchain.

The game concept

After an artistic venture, workshop experiments, Ethereum code snippets and strange cryptocurrency quotes, I felt that my next project should be much more action-oriented and exploring deep inside Blockchain’s peculiar properties. That’s how I came up with the concept of A fistful of Satoshis — A Blockchain-based Western shooting game. The concept of the game itself is very simple, in 3 steps:

  1. Fight a duel with a cowboy dude in a Western street, until you kill the guy (need to hit him 5 times despite the fact you’ve been drinking whisky!)
  2. After you’ve scored the hits, go to the Sheriff to basically get to know whether it’s Billy the Kid you killed, or some poor innocent cowboy. The trick is that it costs you 0.5 (test) ETH to ask this to the Sheriff
  3. Get the answer from the Sheriff: if you were wrong, you loose your money (go to jail), if you were right, get the money from all people that lost before you!

This is thus basically a gambling game within a nifty Western universe introduction. This simple setup allows to explore 2 interesting aspects of the Blockchain: how it deals with synchronicity and randomness. The following learnings are probably a good read, if you are considering serious Blockchain development.

Money games on the Blockchain are provably fair

It’s all fair and transparent on the Blockchain!

Before diving into the specifics of the game, let’s just contemplate some of the advantages brought by running money games on Blockchain smart contracts vs on traditional client-server applications:

  • Blockchain indistinctly handles both payments and game interactions, because they’re all considered transactions (payments are transactions carrying value, whereas game interactions are transactions calling smart contract functions) — this makes it extremely easy to build games manipulating money, whereas with traditional currencies you typically need to integrate your game with a payments solution provider (Stripe, BrainTree, Paypal…), something that comes with cost and complexity
  • Similarly, you don’t need to open a specific (escrow) bank account to keep the players money safe during the game: the smart contract handles this for you, by storing financial value along with the other variables that define the state of the game
  • By choosing the Blockchain as the back-end and infrastructure for running your game, you ensure that you’re using the same layer as that of other industry players, that all continuously bring refinements to make the technology more secure — with no need to constantly apply patches like it might be case with web frameworks for examples
  • But most of all, you allow your money game to be provably fair: this means that all players can audit your code at all times because it is transparently available for review on the public ledger. For example, this would prevent a Blockchain-based casino from cheating against players in a dice game or from advantaging certain poker players with hidden code snippets.

This and other reasons is what has given rise to a series of Blockchain-based online gambling ventures, such as FunFair for example. Keep in mind however that the field is still quite nascent: I wouldn’t bet all my crypto on one of their Blackjack tables yet!

Synchronicity on the Blockchain is hard

Back to our Western adventure. The context of a shooting game is a great occasion to explore real-time events handling on the Blockchain. Indeed, in shooters you expect things to go very fast, when a few millisecond can be what differentiates a headshot from a miss. Ideally, we would like to have the following in our game:

  • Every time you shoot, you lose ammunition and this gets recorded instantaneously on the Blockchain in an immutable way (so you can’t cheat on your ammo)
  • Every time you hit the enemy, he loses a bit of health and this gets recorded as well, directly
  • When you kill the enemy, you get a reward / a blame, and the alive / death state of the enemy gets instantaneously broadcast to all other players

However you might have noticed that playing the game here is fairly async: first you shoot and kill the cowboy, then only when you’re done do you start interacting with the Blockchain. That’s because real-time handling conflicts with some design principles of Blockchain.

Blockchain events are rhythmed by the transactions validation process

Blockchain’s beating heart is mining and it’s asynchronous by design

The reason why we can’t interact and get feedback instantaneously with the Blockchain is because all transactions (interactions) are by design in a pending state until they’ve been picked up by a miner for validation. Only after this validation can a transaction be confirmed and thus safely be relied upon by the network.

On the Ethereum Blockchain, block validation occurs every ~17 seconds. This is well below the ~10 minutes it takes for BitCoin, but well above the few milliseconds required for a game to be considered ‘real-time’.

It might be tempting to think that it suffices to decrease latency (by a combination of reducing block size and decreasing mining difficulty) to get a near real-time Blockchain. However, as this and this articles from the excellent Vitalik Buterin show, shorter block times come with higher risks of centralisation and increased networking complexity.

This is in part due to the fact that, as block time decreases, the ratio of time required to broadcast a new block to the network vs. the time required for mining increases. For example, it took in 2013 an average of 12.6 seconds for a Bitcoin block to be broadcast to the network. This is only 2% of the time for a 10 minutes validation time, but 75% of the time for a 17 seconds validation time. This ratio introduces complex dynamics in the first-found-first-paid mining challenge that network nodes are playing.

Anyway, transaction time and fees hurt real-time micro-transactions

Now let’s imagine we still could perform near-to-real-time transactions. Within the context of our game, we would for example broadcast a transaction about the ammo level each time we shoot with a machine gun (an event such as “MinusOneBullet”) — so-called micro-transactions.

But then we’re confronted with two of other Blockchain’s current limitations preventing such transactions:

  • The current Ethereum transactions throughput is ~15 TPS (transactions per second)
  • The average fee is per transaction is ~0.73 USD
Ethereum transactions fees evolution: see the peak before the crash ?

See it for yourself on BitInfoCharts, for example. Now imagine a gamer firing an M-16 at a frequency of 950 rounds per minute, or 15 rounds per second, in a more modern game such as Call Of Duty. It becomes too obvious that Blockchain currently cannot scale to handle such a high rate of transactions (we would need the current network throughput just for one gamer!), and gamers probably aren’t ready to foot the corresponding bill (which corresponds more or less to the real cost per bullet at a shooting range…).

Off-chain payments channels for real-time scalable interactions

Fortunately, Blockchain developers did not sit idle waiting for a Western game to start trying to solve the synchronicity, throughput and fees issues. The most promising solutions rely on off-chain payment channels. The most well-known are the Lightning Network on BitCoin, and Raiden on Ethereum.

Off-chain payment channels certainly bring interesting stuff around the table

The underlying principle of these off-chain payment channels is actually rather simple:

  • Open an escrow account (backed by a smart contract) where you lock a certain amount of value on the Blockchain, say, 1 ETH.
  • Open a ‘payment channel’ between you and the actor you want to interact with, say, the gaming company. Concretely, this means giving the company access to the funds you’ve locked, by means of multi-signatures transactions (both you and the company need to sign).
  • Now that the company knows you’ve locked 1 ETH and they can claim these funds, you can start buying things from them for up to this amount. Concretely, this would mean playing their game and firing, say, a few bullets at a cost of 0.01 ETH. Or, taking another example, watching exclusive video content at a cost of 0.005 ETH / minute.
  • During the time you’re playing, no interactions with the Blockchain occurs, but all these micro-transactions (bullets fired, seconds watched) are recorded by the gaming company.
  • When you’re done playing, all the micro-transactions are bundled together and the total amount of in- and outgoing value is computed. This bundling is then sent as a single transaction on the Blockchain in an asynchronous way, and at a much cheaper cost since fees are paid only once for the whole bundle.

The whole idea thus relies on the assumption that you can safely build a set of transactions entirely out of the Blockchain, to validate it only once you’re done exchanging value between actors. The downside is of course that you loose the ability to publicly inspect all transactions, since aggregation destroys their details. Payment channels certainly are an interesting development to follow!

Randomness is not welcome on the Blockchain

By now I hope you’ll have understood why this game works asynchronously. Another interesting stuff is yet to come, with regards to the gambling part. Fundamentally, gambling is about randomness. But randomness on the Blockchain is much harder than it might seem at first! Indeed, the very idea of Blockchain is that it should be possible for everyone to verify all transactions, and this should better be deterministic if all should arrive at the same end result. But some tricks do exist to generate randomness, not all equally safe.

If only things were that easy…

Relying on the computing environment for randomness is dangerous

If you’ve tried to develop random stuff on the (Ethereum) Blockchain yourself, you certainly did come across the following tricks to generate (pseudo-)random numbers:

  • Relying on timestamps (i.e., the time at which a function is executed)
  • Relying on block height (i.e., the sequence number of the block in the chain)
  • Other funky stuff like block hashes, nonces etc.

The big issue with these tricks is that they take the computing environment as a source of randomness. Why is this bad ? For the simple reason that all computations on the Blockchain are ultimately performed by miners within the siloed environment of the EVM, the Ethereum Virtual Machine. And it’s only too easy for a miner to manipulate this environment, by e.g. modifying the machine time, choosing to include or exclude a transaction from a given block (so that the block height is ‘manipulated’), and so on.

This probably isn’t too big of an issue if your Blockchain application is low-profile and won’t catch malicious miners attention. But as soon as you start generating significant volume, transactions interacting with your app can become the target of manipulations.

Miners could get nasty and crazy if the see they can manipulate your randomness!

Note interestingly that even in the absence of manipulation, the timestamps of different miners might differ too. Transactions might be executed in a certain order by miner A and not by miner B. If your game is a simple coin flip relying on timestamp being even (heads) or odd (tails), you might very well get a heads at miner A and tails at miner B during the EVM execution — really like parallel realities! If you need a heads to win you game, you’d better hope that miner A is the one that wins the mining challenge and lets the whole network know you won.

Current solutions: crowdsourcing and Oraclize

As you can imagine, our Sheriff in A fistful of Satoshis does not rely on the computing environment for randomness. We rather leverage an Oracle (something I’ll discuss in Blockchain project #6).

An Oracle, really?

In a nutshell, an Oracle is a trusted external source of data that the Blockchain can query to get a specific input. Oraclize is probably the most used and most developer-friendly solution out there for Ethereum. The folks at Oraclize have developed a specific API endpoint to get a ‘trusted-certified-guaranteed’ random number. This is the one used in the Western game.

Another solution (not used here given the scale of the game) is to leverage inputs from the crowd to generate randomness. This is the objective pursued by the RanDAO. The underlying principles are fairly complex and require a 3-step process of hashes submissions by participants to the smart contract.

Until these services have been wrapped within simple abstractions, it will certainly remain difficult to embed randomness within Blockchain apps.

The source code behind A fistful of Satoshis

Last but not least after this (extremely) long read: here the full source code of the smart contract behind the game. Below is also the key part regarding randomness: this is the callback function that Oraclize uses for passing its random result to the smart contract.

Also note that this smart contract uses a withdrawal pattern for the winner to take out their funds, instead of sending funds proactively once the winner is found. This is indeed much more secure.

Conclusion: so many learnings!

Thanks a lot for reading if you arrived at this point. I do hope that you learned as much as I did with this weird Western adventure. Stay tuned for Blockchain project #6!

--

--