In the last few days the Bitcoin community suffered another wave of stolen coins due to a failure to correctly generate random numbers. The bug in the blockchain.info “My Wallet” web wallet was live only for a few hours, but that was enough time to compromise around 250 BTC (or around $90,000). Luckily they were mostly taken by a Robin Hood — people who scan the block chain for crypto failures and immediately steal any money exposed by them, so they can be returned to the legitimate owners later. My Wallet users got lucky and it looks like most of them will get their money back.

The underlying bug was a failure to initialise a variable to zero in an application level RNG. “My Wallet” is not written in C, as you might expect having read that statement. It’s written in Javascript, a supposedly modern scripting language. The variable rng_pptr is used as an index into an array, and when it was left uninitialised, we get this astonishing outcome:

var a = new Array();

var b;

a[b++] = 1;

a is now [] and no exception is thrown — the write to the array simply vanishes. Try it out in your browser console if you don’t believe me.

It’s not news that Javascript is full of surprising quirks, but this demonstration of how dangerous the language can be is still impressive. Perhaps only PHP with its notoriously broken == operator is in the same ball park.

Any reasonable language would not allow the above code to run at all: attempting to increment “undefined” should crash. A language that tries to be as dynamic as possible might cast it to zero and then yield one. But doing nothing is the worst of all possible choices.

There are two underlying problems here. One is the existence in My Wallet of this wrapper around the browser’s crypto RNG — no such wrapper should exist and My Wallet should refuse to run if the browser doesn’t support the necessary features. Doing anything else is incredibly risky.

The other is lack of type safety in the language. Type systems got a bad rap with a lot of programmers because languages with stronger type systems were often very verbose, or had other design choices that made them hard to use. Modern languages with modern type systems like Scala, Kotlin, C# and especially Haskell have changed this: they make heavy use of local type inference to cut down on tedious repetition, and can visually resemble languages like Javascript and Python. They have lots of functional constructs to cut down on verbosity yet further. And because the compilers run just in time, it means you can iterate very fast on changes. In short, the reasons for avoiding stricter languages are falling away over time and the benefits are getting larger.