RSS Feed

Monthly Archives: December 2014

GCC compiler “bug” broke my Haxe code

Posted on

In hxBitcoin I have this utility function:

    Unsigned greater than comparison.

    Returns `true` if `a > b` when both `a` and `b` are
    interpreted as unsigned integers; `false` otherwise.
public static inline function u32gtu32(a : Int, b : Int) : Bool
    return (a + -2147483648) > (b + -2147483648); // unsigned comparison, see "Hacker's Delight" p. 25.

This nifty little trick is from the most excellent book Hacker’s Delight by Henry S. Warren, Jr.

The function worked great, until I ran my unit tests on Linux. u32gtu32(-2147483648, 2147483647) should return true, but it was returning false. A look at the generated C++ offered nothing obvious:

bool FunInteger_obj::u32gtu32( int a,int b){
    return ((a + (int)-2147483648) > (b + (int)-2147483648));

To make a long story short, I crafted this simple standalone test:

#include "stdio.h"
extern "C" int main(int argc, char ** argv)
    int a = -2147483648;
    int b = 2147483647;
    bool compare = (a + (int)(-2147483648)) > (b + (int)(-2147483648));
    printf("result = %d\n", compare ? 1 : 0);
    return 0;

Now this is where it gets fun and interesting!

$ g++ -O2 test.cpp && ./a.out
result = 0
$ g++ -O0 test.cpp && ./a.out
result = 1

Huh? Sure smells like a compiler optimization bug, doesn’t it?

Turns out this is a feature. For optimization purposes, by default GCC assumes there will be no overflow with integer arithmetic (see this).

There are a number of possible remedies, many of which are unappealing for various reasons (for example, adding -fwrapv or -fno-strict-overflow to the compiler options for Linux builds, or passing a special flag to the Haxe build and implementing the u32gtu32 function differently when necessary).

But this simple fix was just the thing — replace the addition with exclusive-or in the original function:

public static inline function u32gtu32(a : Int, b : Int) : Bool
    return (a ^ -2147483648) > (b ^ -2147483648); // unsigned comparison, see "Hacker's Delight" p. 25.

As a result of this experience, I also added some “run-time tests” — quick tests that are executed at run time even in a distribution release. The reason being that, from the end-user’s perspective, hxBitcoin is a pure Haxe library. The fact that on some platforms it is generated into C++ and compiled automatically by the Haxe/hxcpp framework is an implementation detail. A library user who installs hxBitcoin via haxelib likely will not run the full suite of unit tests. But the validity of the results, as I discovered, can depend greatly on the particulars of the compiler used. (Previously the same code exhibited no issues when compiled as C++ on Windows, OSX, and iOS.) The particular issue I encountered here would cause subtle, silent issues for the end-user without the presence of at least some minimal run-time validation.

Announcing hxBitcoin, the Bitcoin and crypto library for Haxe

Posted on

hxBitcoin is a new open source Bitcoin and cryptocurrency support library in the Haxe language.

The initial release has these features:

  • BIP0038 (encrypted private keys), WIF, private & public keys, addresses, Base58
  • scrypt, AES, SHA-1, SHA-256, RIPEMD160
  • Elliptic curve arithmetic, secp256k1 & NIST curves
  • Modular arithmetic (Fp), Arbitrary-size (big) integer, Unicode 7.0

and supports iOS, Windows, OSX, Flash, and NekoVM targets (additional targets are easy, just ask).

It’s a clean, simple API in pure Haxe with no additional or external dependencies.

Built in Haxe, hxBitcoin has extensive reach to enable applications on desktop, mobile, web, and server platforms, targeting C++, Java, JS, PHP, AS3 and more with a single code base.

It’s also backed by an extensive test suite of over 22,000 individual tests and vectors to validate correct behavior on all supported platforms.

To start using, simply install the library via haxelib:

haxelib install hxBitcoin

Here’s an example of how to decrypt a BIP0038 private key:

import com.fundoware.engine.bitcoin.FunBitcoinContext;
import com.fundoware.engine.bitcoin.FunBitcoinEncryptedPrivateKey;
import com.fundoware.engine.bitcoin.FunBitcoinPrivateKey;

var context = new FunBitcoinContext();
var encryptedKey = FunBitcoinEncryptedPrivateKey.fromString(
    context, "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg");
var decryptedKey = encryptedKey.decryptString("TestingOneTwoThree");
trace("private key (WIF) = " + decryptedKey.toWIF());
var address = decryptedKey.toAddress();
trace("address = " + address);

Project website:

Project on GitHub:

Feature requests are welcome!

How to use Bitcoin Key to create offline private keys

Posted on

The Bitcoin Key app (discussed here) takes the place of rolling dice when creating offline private keys. This is a tutorial of how to use it to create your offline keys.

The process is a bit involved, whether you use dice or the app. So why go to the trouble? Because when done right, keys generated in this way are never exposed to an online computer, and therefore not susceptible to online hacking or digital theft.

When you use an offline computer and print your keys for cold storage, then the problem of security for your keys is limited to securing the physical piece of paper on which your keys are printed, which can be much more manageable than trying to secure an online computer system.

You will need… Read the rest of this entry

Bitcoin Key app: Better than rolling dice?

Posted on

Bitcoin Key app for iOSAs a result of the apparently poor numerical distribution observed rolling my hex dice (see this earlier post), I was inspired to create an app to take the place of hex dice for the purpose of creating off-line Bitcoin private keys.

Bitcoin Key is now in the iOS App Store.

(At present it’s available only in the U.S., until I can figure out if it’s exempt from U.S. export regulations.)

The app generates a never-ending stream of random hexadecimal digits. The timer in the top-left corner counts down to the next digit, with a new one every two seconds. The previous digit is also shown here.

Move your finger around the screen to add your own randomness.

To create a Bitcoin private key, simply jot down (or enter into your offline computer running a live CD) 64 of the randomly-generated hexadecimal digits.

Worried that the app is recording every single digit produced and sending it somewhere? It’s not. You’re welcome to watch the wi-fi or your home network with a packet sniffer. Besides, even if it was, the collector of the data would have know way of knowing which of the endless stream of digits you’re actually writing down. Heck, maybe you’re only using every 2nd or 3rd digit produced.

Bitcoin Key uses ANSI X9.31 cryptographically secure random number generation via 256-bit AES in counter mode. The 256-bit key that’s fed into the AES comes from the system’s entropy source (SecRandomCopyBytes on iOS). The RNG is re-keyed from system entropy every minute (the timer in the top-right corner).

AES takes a 128-bit block as input. ANSI X9.31 specifies that this is to be a monotonically increasing value for secure random number generation. For this value, Bitcoin Key uses the system’s high-resolution timer (mach_absolute_time on iOS) as the upper 64 bits, and the user entropy value as the lower 64 bits.

The user entropy value is computed as follows: any time finger motion on the screen is sensed, the x,y coordinates of the finger are multiplied together, and the result is then added to the user entropy value.

Is it better than rolling dice? It depends on how you define “better.” Bitcoin Key includes a stats page that shows you a count of how many times each digit has appeared. I personally find that it has more even distribution compared to the hexadecimal dice I used previously.

And, at $0.99, Bitcoin Key is certainly cheaper than the dice I purchased. Although admittedly, hexadecimal dice have a certain charming appeal, and are a great conversation piece. 🙂