<?xml version="1.0" encoding="utf-8"?>
        <?xml-stylesheet type="text/css" href="http://a1k0n.net/blah/styles/feed.css"?>
<rss version="2.0"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/"
 xmlns:admin="http://webns.net/mvcb/"
 xmlns:atom="http://www.w3.org/2005/Atom"
>
<channel>
<title>a1k0n</title>
<atom:link href="http://a1k0n.net/blah/rss.xml" rel="self" type="application/rss+xml" />
<link>http://a1k0n.net/blah</link>
<description>Andy Sloane's weblog</description>
<dc:language>en-us</dc:language>
<dc:creator>a1k0n</dc:creator>
<dc:date>2010-03-10T18:02:06-06:00</dc:date>
<admin:generatorAgent rdf:resource="http://nanoblogger.sourceforge.net" />

<item>
<link>http://a1k0n.net/blah/archives/2010/03/index.html#e2010-03-04T14_00_21.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2010/03/index.html#e2010-03-04T14_00_21.txt</guid>
<title>Google AI Challenge post-mortem</title>
<dc:date>2010-03-04T14:00:21-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[<p />I can't believe <a
  href="http://csclub.uwaterloo.ca/contest/rankings.php">I won</a>.

<p />I can't believe I won <i>decisively</i> at all.

<p />I've never won any programming contest before (although I did place in 3rd
in the <a href="http://julian.togelius.com/mariocompetition2009/">Mario AI
  contest</a> but there were only about 10 entrants).  Whenever I badly lose at
an <a href="http://icfpcontest.org/">ICFP contest</a> I'm always anxious to see
the post mortems of the people who did better than I did, and I imagine a lot
of people are curious as to how I won, exactly.  So here's my post-mortem.

<h3>Code</h3>

<p />Before we get into it, note that all of my code is <a
  href="http://github.com/a1k0n/tronbot/">on github here</a>.  The commit logs
might be a mildly entertaining read.

<h3>Phase 1: denial</h3>

<p />The first thing I did was attempt to ignore this contest as long as
possible, because month-long programming contests get me into a lot of trouble
at work and at home.  The contest was the Tron light cycle game.  I've played
variants of this game ever since I got one of <a
  href="http://www.handheldmuseum.com/Tomy/Tron.htm">these</a> when I was in
1st grade or so.  The most fun variant was my uncle's copy of <a
  href="http://www.youtube.com/watch?v=BK_a8xV3O6w">Snafu for the
  Intellivision</a> which we played at my Grandma's house all day long.  I've
long wondered how to write a bot for it, because the AI on these usually isn't
very smart.

<h3>Phase 2: space-filling</h3>

<p />But I finally gave in on the 9th, downloaded a starter pack, and attempted
to make a simple semi-decent wall-hugging bot.  I quickly discovered a simple
useful heuristic: the best rule for efficiently filling space is to always
choose the move that removes the least number of edges from the graph.  In
other words, go towards the space with the most walls for neighbors.  But!
Avoid <a href="http://en.wikipedia.org/wiki/Cut_vertex">cut
  vertices</a> (AKA articulation points), and if you have to enter a cut vertex,
then always choose the largest space left over.  At this stage I wasn't
actually calculating articulation points; I just checked the 3x3 neighborhood
of the square and made a lookup table of neighbor configurations that
<i>might</i> be articulation points based on the 3x3 neighborhood.  This is
what the <tt><a
    href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L238">potential_articulation</a></tt>
function does in my code, and <tt><a
    href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/artictbl.h#L1">artictbl.h</a></tt>
is the lookup table.

<p />I was, however, computing the <a
href="http://en.wikipedia.org/wiki/Connected_component_(graph_theory)">connected
components</a> of the map.  This is a simple two-pass O(<i>NM</i>)
algorithm for <i>N</i> squares in the map and <i>M</i> different
components.  For each non-wall square in the map, traversed in raster
order, merge it with the component above it (if there is no wall
above) and do the same to its left (if there is no wall to the left).
If it connects two components, renumber based on the lowest index,
maintaining an equivalence lookup table on the side (equivalence
lookups are O(<i>M</i>) but really just linear scans of a tiny
vector).  Then scan again and fixup the equivalences.  This is what
the <tt><a
href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L243">Components</a></tt>
structure is for; it has this algorithm and simple sometimes-O(1),
sometimes-O(<i>NM</i>) update functions based on
<tt>potential_articulation</tt> above.

<h3>Phase 3: minimax</h3>

<p />I left it at that for the rest of the week and then Friday the 12th I was
inspired by various posts on the official contest forum to implement <a
  href="http://en.wikipedia.org/wiki/Minimax">minimax</a> with <a
  href="http://en.wikipedia.org/wiki/Alpha-beta_pruning">alpha-beta
  pruning</a>, which would let it look several moves ahead before deciding what
to do.  The problem with this approach is that you have to have some way of
estimating who is going to win and by how much, given any possible
configuration of walls and players.  If the players are separated by a wall,
then the one with the most open squares, for the most part, wins.  If they
aren't separated, then we need to somehow guess who will be able to wall in
whom into a smaller space.  To do that, I did what everyone else in the contest
who had read the forums was doing at this point: I used the so-called Voronoi
heuristic.

<p />The "Voronoi heuristic" works like this: for each spot on the map, find
whether player 1 can reach it before player 2 does or vice versa.  This creates
a <a
  href="http://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi diagram</a> with
just two points which sort of winds around all the obstacles.  The best way to
explain it is to show what it looks like during a game:

<center><img src="/blah/images/voronoi.gif" /></center>

<p />The light red area are all squares the red player can reach before the blue
player can.  Similarly for the light blue squares.  If they're white, they're
equidistant.  The heuristic value I used initially, and many other contestants
used, was to add up the number of squares on each side and subtract.

<p />Once the red player cuts the blue one off, they are no longer in the same
connected component and then gameplay evaluation switches to "endgame" or
"survival" mode, where you just try to outlast your opponent.  After this
point, the minimax value was 1000*(size of player 1's connected component -
size of player 2's connected component).  The factor of 1000 was just to reward
certainty in an endgame vs. heuristic positional value.  Note that this was
only used to <i>predict</i> an endgame situation.  After the bot actually
reached the endgame, it simply used the greedy wall-following heuristic
described above, and it performed admirably for doing no searching at all.

<h3>evaluation heuristic tweaking</h3>

<p />I next noticed that my bot would make some fairly random moves in the early
game, effectively cluttering its own space.  So I took a cue from my flood
filling heuristic and added a territory bonus for the number of open neighbors
each square in the territory had (effectively counting each "edge" twice).
This led to automatic wall-hugging behavior when all else was equal.

<p />After fixing a lot of bugs, and finally realizing that when time runs out on
a minimax search, you have to throw away the ply you're in the middle of
searching and use the best move from the previous ply, I had an extremely
average bot.  Due to the arbitrariness of the ranking up until the last week in
the contest, it briefly hit the #1 spot and then settled to a random spot on
the first page.  It was pretty hard to tell whether it was any good, but I was
losing some games, so I figured it must not be.

<h3>endgame tweaking</h3>

<p />The next realization was that my bot was doing a lot of stupid things in the
endgame.  So the next improvement was to do an iteratively-deepened search in
the endgame.  I exhaustively tried all possible moves, and at the bottom of the
search tree, ran my greedy heuristic to completion.  Whichever move sequence
"primed" the greedy evaluator the best wins.  This works great on the smallish
official contest maps.  It works terribly on very large random maps currently
in rotation on <a href="http://www.benzedrine.cx/tron/">dhartmei's server</a>,
but I didn't realize that until after the contest.

<h3>data mining</h3>

<p />I was out of ideas for a while and spent some time optimizing (I used
Dijkstra's to do the Voronoi computation and I sped it up by using what I call
a radix priority queue which is just a vector of stacks... see <a
  href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L382"><tt>dijkstra</tt></a>).
But it had been bothering me that my edge count/node count Voronoi heuristic
was pretty arbitrary, and wondered if I could do any kind of inference to
discover better ones.

<p />Well, hundreds of thousands of games had been played on the contest server
by this point, and they are extremely easy to download (the contest site's game
viewer does an AJAX request to get some simple-to-parse data for the game), so
I figured I'd try to do some data mining.  I wrote a <a
  href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/util/getgame.pl">quick
  perl hack</a> to grab games from the site and output them in a format that
Tron bots recognize.  Then I copied-and-pasted my code wholesale into
<tt>examine.cc</tt> and marked it up so it would read in a game back-to-front,
find the point at which the players enter separate components, guess what the
optimal number of moves they could have made from that point forward, and then
use the existing territory evaluation code on every turn before that and dump
out some statistics.  The goal was to discover a model that would predict,
given these territory statistics, what the difference in squares will
eventually be in the endgame.

<p />I started with an extremely simple linear model (and never really changed it
afterwards): the predicted difference in endgame moves is <i>K<sub>1</sub></i>
(<i>N<sub>1</sub></i> - <i>N<sub>2</sub></i>) + <i>K<sub>2</sub></i>
(<i>E<sub>1</sub></i> - <i>E<sub>2</sub></i>) where <i>N<sub>i</sub></i> is the
number of nodes in player <i>i</i>'s territory and <i>E<sub>i</sub></i> is the
number of edges (double-counted actually).

<p />Now, this model is pretty far from absolutely great, and only a little
predictive.  This is what the raw data looks like after analyzing 11691 of the
games the top-100 players (at the time) had played:

<p /><img src="/blah/images/nodes.png"><br>
<img src="/blah/images/edges.png">

<p />That's the difference of nodes/edges on the <i>x</i>-axis and the difference
of endgame moves on the <i>y</i>-axis.  So both nodes and edges by the Voronoi
metric are, of course, correlated.  I did a linear regression to find
approximate values for <i>K<sub>1</sub></i> (currently 0.055) and
<i>K<sub>2</sub></i> (0.194) and multiplied through by 1000 to keep everything
integers.

<p />This definitely improved play in my own testing (I kept 14 different
versions of my bot throughout the contest so I could compare them.
Interestingly, no bot ever totally shut out a previous bot on all maps in my
tests; every bot has a weakness).  Once I had that, I was doing very well in
the leaderboard rankings.

<h3>applied graph theory</h3>

<p />Next I noticed <a
  href="http://csclub.uwaterloo.ca/contest/forums/viewtopic.php?f=8&t=319&start=10#p1568">dmj's
  "mostly useless" idea</a> on the official contest forums: Pretend the game is
played on a checkerboard.  Each player can only move from red to black and vice
versa.  Therefore, if a given space has a lot more "red" squares than "black"
squares, the surplus "red" squares will necessarily be wasted.  I switched out
all my space counting code to count up red and black spaces, and found a
tighter upper bound on the amount of space an ideal bot could fill.  This let
my endgame code stop searching when it had found a solution matching the upper
bound, and gave slightly more realistic territory evaluations.

<p />I had already started to think about what came to be called "chamber trees",
as <a
  href="http://csclub.uwaterloo.ca/contest/forums/viewtopic.php?f=8&t=319#p1484">pointed
  out by iouri in the same thread</a>: find all the articulation points on the
map and construct a graph of connected spaces.  I implemented the standard
O(<i>N</i>) algorithm for finding articulation points (<a
  href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L513"><tt>calc_articulations</tt></a>,
taken from <a
  href="http://www.eecs.wsu.edu/~holder/courses/CptS223/spr08/slides/graphapps.pdf">this
  presentation [pdf]</a>).  I messed around with this idea but nothing came to
fruition until just before the deadline.

<p />At around this point, I got extremely sick and spent all day Wednesday in
bed.  That day, <a
  href="http://www.benzedrine.cx/tron/">dhartmei's server</a> showed up, which
was a huge blessing.  I ran my bot on there in the background all Thursday
long, and it did very well on there too, which was a very reassuring thing.
But it was still losing a lot of games.

<p />So finally, after failing to get to sleep Thursday night thanks to coughing
and being unable to breathe through my nose, I was struck by an idea at around
3am.  This, it turns out, was probably the contest-winning idea, though I'm not
so sure that nobody else implemented it.  Anyway, take a look at this game (<a
  href="http://csclub.uwaterloo.ca/contest/visualizer.php?game_id=3878644">a1k0n_
  v. ecv257</a>):

<center><img src="/blah/images/example1.png" /></center>

<p />(The little circles are the articulation points found by the algorithm
above.) By the so-called Voronoi heuristic, blue has a lot more space than red
does.  But red is ultimately going to win this game, because the only space
that blue controls that matters here is the space that borders red.  Blue can
choose to cut off that space and fill in the two chambers on the right, or it
can choose to move into the left chamber and take its claim on what I call the
"battlefront": the border between blue space and red space.

<p />I had long ago come to the realization that a better evaluation
heuristic will always beat deeper minimax searches, because a deep
minimax search using a flawed evaluation heuristic is self-deluded
about what its opponent is actually going to do, and will occasionally
favor moves that lose to moves that win, simply because it can't tell
the difference.  Anything you can do to make your evaluation function
smarter will result in improved play in the long run.

<p />In this case, I decided to make my evaluation function aware of the above
condition: if the player is not in the chamber containing the "battlefront",
then make the choice I outlined above.  More formally, the new heuristic value
is the same as the old one, but <i>N<sub>i</sub></i> and <i>E<sub>i</sub></i>
are counted differently.  First, find all cut vertices <i>assuming the
  opponent's territory by the Voronoi metric is disconnected</i>.  Start a
depth-first search in the player's "chamber", count <i>N<sub>i</sub></i> and
<i>E<sub>i</sub></i> within the chamber, and list all the neighboring cut
vertices but do not traverse them (<a
  href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L547"><tt>_explore_space</tt></a>).
Now, explore space recursively for each adjacent cut vertex.  If child
<i>j</i>'s space is <i>not</i> a battlefront, then our potential value is the
sum of the current chamber size and child <i>j</i>'s value.  Otherwise, it
<i>is</i> a bottlefront, and we ignore the current chamber's size but add only
the number of steps it takes to enter the child chamber (I don't have a good
formal reason for this, it just seemed intuitively right).  After computing
this potential value for each child, we return the maximum of them as the
current chamber's value.

<p />Therefore the new code will handle the mutual exclusion of battlefront
chambers and other chambers, and force it to choose to either ignore the upper
left chamber or ignore the two chambers on the right.

<p />The idea was extremely roughly-formed when I implemented it (see <a
  href="http://github.com/a1k0n/tronbot/blob/a1k0nbot-2.18.2/cpp/MyTronBot.cc#L586"><tt>max_articulated_space</tt></a>),
but it did improve play markedly after throwing it together (again, it didn't
shut out the previous version of my bot totally but it won 12-1 IIRC).

<p />I also had the idea of negatively counting the space we ignore on a
battlefront, as we are effectively handing that space to our opponent.  Never
got a chance to try it, though.  Might be a nice improvement.

<p />So that was it.  I submitted that Friday around noon, and was subsequently
afraid to touch it.  (My wife and son and I left for Wisconsin Dells right
afterwards, where I couldn't help but check rankings on my cellphone and keep
up on the forums the whole time, which didn't go over well)  The bot is still
running on <a href="http://www.benzedrine.cx/tron/">dhartmei's server</a>, and
still loses many games as a result of miscounting the opponent's space in the
endgame, since my endgame evaluation wasn't very good.  But it was good enough
for the contest.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2009/12/index.html#e2009-12-08T15_48_13.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2009/12/index.html#e2009-12-08T15_48_13.txt</guid>
<title>Super high-tech BlackBerry charger</title>
<dc:date>2009-12-08T15:48:13-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[I got a BlackBerry 8350i from ebay to use with a <a
href="http://boostmobile.com">Boost Mobile</a> prepaid plan.  Boost (as
prepaid plans are in general) is much, much cheaper than the
alternatives when you don't talk on the phone a lot.  And (slow)
unlimited wireless internet is only 35 cents a day which works out to
a little over $10/month.
<br /><br />
But anyway, my used BlackBerry turned out to have a broken USB port.
It was mounted entirely with cold solder joints and fell right off
like it wasn't even soldered on when I first tried to charge it up.
<br /><br />
Most people would avail themselves of the return policy, but I'm not
most people.
<br /><br />
I needed to get updated firmware to get SMS and GPS to work, so I <a
href="http://www.flickr.com/photos/asloane/4164714965/">soldered some
wires on</a>, clipped them to a USB cable, and that worked flawlessly,
to my surprise.
<br /><br />
That let me charge it up, too.  So then I had a phone with a full
charge, upgraded firmware, working everything, except it does me no
good just sitting on my desk tethered to a bunch of flimsy wires.  I
clipped off all the wires and ordered a replacement USB port as well
as a cradle charger, and all was well until the battery died.  Which
it pretty much did the next day.
<br /><br />
So last night I came up with this:
<br /><br />
<img src="/blah/images/hackberry1.jpg">
<br /><br />
<img src="/blah/images/hackberry2.jpg">
<br /><br />
<img src="/blah/images/hackberry3.jpg">
<br /><br />
Two nails driven through a block of wood connected to USB +5V and
ground.  Works like a charm.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2009/11/index.html#e2009-11-17T18_08_18.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2009/11/index.html#e2009-11-17T18_08_18.txt</guid>
<title>Hacker challenge part 2 solution</title>
<dc:date>2009-11-17T18:08:18-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[Because I am lazy and easily sidetracked, the promised update to
the "Hacker challenge" (<a
href="http://a1k0n.net/blah/archives/2009/03/index.html#e2009-03-31T18_50_59.txt">part
1</a>, <a
href="http://a1k0n.net/blah/archives/2009/04/index.html#e2009-04-03T21_36_15.txt">part
2</a>) is now over seven months late.  So I might as well post the
solution to part 2, which was solved by three individuals on
<a
href="http://www.reddit.com/r/programming/comments/89vma/hacker_challenge_part_2_solution_to_part_1_and_a/">
reddit (bobdole, c0dep0et, and xahtep)</a>.
<br /><br />
Part 2 used <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">DSA</a>,
which was fairly obvious; as before I made no effort to hide it.  Instead of
decrypting to a particular value, it verifies a message signature hash of
12345678 with various "random per-message values" or <a
  href="http://en.wikipedia.org/wiki/Cryptographic_nonce">nonces</a>.
<br /><br />
The parameters for the algorithm were encoded in 32-bit chunks.  The nice
thing about DSA is that you can use huge <i>p</i> and <i>y</i> values (see
Wikipedia for the terminology) without making the license key any bigger;
unfortunately that doesn't buy you a lot, because the underlying group order is
only <i>q</i>, so that's how big the search space theoretically is -- it
doesn't increase security, it just makes it marginally slower to factor.
<br /><br />
So I chose <i>p</i>, <i>y</i>, and <i>g</i> to be on the order of 384 bits,
but <i>q</i> and <i>x</i> are only on the order of 64 bits.  In fact <i>p</i>
is just a 64-bit number shifted left 320 bits and then incremented.
<br /><br />
The security of DSA derives from the difficulty of determining <i>x</i> from
<i>y = g<sup>x</sup></i> mod <i>p</i>, which is known as the <a
href="http://en.wikipedia.org/wiki/Discrete_logarithm">discrete logarithm
problem</a>, which is harder than factoring primes.
<br /><br />
So after you reconstruct the parameters from the hexadecimal encoding you find:
<br /><br />
<i>p</i> = 12026070341127085754893097835098576041235013569186796331<br />
441953314639277634647572425804266039236571162321832835547137<br />
<i>g</i> = 54659936461116297034410364232325768273521088000551606899<br />
39983550682370032756410525809260221877924847568552733696072<br />
<i>y</i> = 27434965696578515868290246727046666462183462061939529180<br />
41150093730722092239431092724025892380242699544101134561292<br />
<br /><br />
You can plug these numbers into a <a
  href="http://www.alpertron.com.ar/DILOG.HTM">discrete log solver</a> and find
<i>x</i> (it will also deduce <i>q</i> as the subgroup size after a few
seconds).  This takes about three hours on my MacBook Pro, IIRC.
<br /><br />
Once you have <i>x</i> the challenge collapses into reimplementing
DSA (with a small twist: <i>s</i> is inverted in the generator, not in
the validator; I can't see any reason this would affect security and
it makes the validator simpler):
<br /><br />
<li />let <i>H</i> = 12345678 (the supposed message hash)
<li />choose a nonce <i>k</i>
<li />compute <i>r</i> = (<i>g<sup>k</sup></i> mod <i>p</i>) mod <i>q</i>
<li />compute <i>k</i><sup>-1</sup> (mod <i>q</i>) using the modular multiplicative inverse (<tt>mpz_invert</tt> with <a href="http://gmplib.org/">GMP</a>)
<li />compute <i>s</i> = (<i>k</i><sup>-1</sup>(<i>H</i> + <i>x r</i>)) mod <i>q</i>
<li />let <i>w</i> = <i>s</i><sup>-1</sup> (mod <i>q</i>)
<li />combine (<i>r,w</i>) into <i>K</i> = <i>r q</i> + <i>w</i>
<li />convert <i>K</i> into a base32-ish key string
<br /><br />
I think this scheme is actually pretty good, as it's non-trivial to solve,
but it's still crackable with the newest discrete log solver methods.  It did
confound some dedicated redditors for a couple days, at least, with all the
details laid bare.
<br /><br />
The obvious next step is to move on to elliptic curve cryptography, and that
is the reason this post is so late.  When I started writing the first hacker
challenge I was completely ignorant of ECC.  Immediately after writing the
previous post, I bought a book on the subject, and while I understand the
basics now I still don't understand it well enough to write a toy
implementation suitable for a "Hacker Challenge".  So I will leave
that for another day, or perhaps for another person.
<br /><br />
Source code for the DSA private key generator and license generator:
<li /><a href="http://a1k0n.net/code/keydecode2.cpp.txt">keydecode2.cpp</a> - the challenge code from the last post (for reference)
<li /><a href="http://a1k0n.net/code/bn.h.txt">bn.h</a> - quick and dirty bignum template
<li /><a href="http://a1k0n.net/code/dl_genpriv.c.txt">dl_genpriv.c</a> - discrete log private/public key pair generator
<li /><a href="http://a1k0n.net/code/dsa_genlic.c.txt">dsa_genlic.c</a> - license generator (key parameters hardcoded)]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2009/04/index.html#e2009-04-03T21_36_15.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2009/04/index.html#e2009-04-03T21_36_15.txt</guid>
<title>Hacker challenge part 2</title>
<dc:date>2009-04-03T21:36:15-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[Well, I guess I'm not quitting my day job to become a cryptographer
any time soon.
<br /><br />
As was instantly ascertained on reddit, the key algorithm in my "<a
href="http://a1k0n.net/blah/archives/2009/03/31/index.html#e2009-03-31T18_50_59.txt">Hacker
Challenge</a>" is <a href="http://en.wikipedia.org/wiki/RSA">RSA</a>.
I was hoping that it would take at least an hour to crack the private
key, but alas, I had severely underestimated the time that modern
elliptic-curve and number field sieve integer factorizers would take.
It factored in under a second, which means the key would have to be
many orders of magnitude larger to offer any kind of security.
<br /><br />
So within an hour a factorization of <i>n</i> was <a
href="http://www.reddit.com/r/programming/comments/890yf/hacker_challenge_can_you_make_a_key_generator/c08l4rh">posted
to reddit by c0dep0et</a>.  Even so, <a
href="http://www.reddit.com/r/programming/comments/890yf/hacker_challenge_can_you_make_a_key_generator/c08l4mg">LoneStar309
pointed out an embarassing implementation mistake</a> which
significantly weakened it (given a valid key, you could generate
several other valid encodings of the same key); I patched this, as I
mentioned in my update.  And then <a
  href="http://www.reddit.com/r/programming/comments/890yf/hacker_challenge_can_you_make_a_key_generator/c08l9k1">teraflop
  demonstrated posession of a working keygen</a> a couple hours later.
<br /><br />
I wanted the key generator challenge to be possible, and it
definitely wasn't trivial, but it was still far easier than I had
hoped.  Still, I couldn't be happier with the result, and I would like
to thank my fellow programming.redditors for a great discussion.
<br /><br />
For those who haven't studied how RSA works in sufficient detail to go
from a factored <i>n</i> to a key generator, go take a moment to read
up on Wikipedia.  Basically the public and private keys, <i>e</i> and
<i>d</i>, are <a
  href="http://en.wikipedia.org/wiki/Modular_multiplicative_inverse">multiplicative
  inverses</a> mod <i>&phi;(n)</i> where <i>&phi;(n)</i> is <a
  href="http://en.wikipedia.org/wiki/Euler's_totient_function">Euler's
  totient function</a>.  In the case of <i>n</i>=<i>pq</i> where
<i>p</i> and <i>q</i> are prime, <i>&phi;(n)</i> = (<i>p</i> -
1)(<i>q</i> - 1).  So you use the <a
  href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">extended
  euclidean algorithm</a> to find <i>e</i> from <i>d</i> and
<i>&phi;(n)</i>.  If you're using <a href="http://gmplib.org/">GMP</a>
(I am), you can just call <tt>mpz_invert</tt> to do that.
<br /><br />
Once you've recovered <i>e</i> from <i>d</i>, you just RSA-encrypt the
message <i>m</i> = 12345678 + <tt>check_mod</tt>*<i>N</i> where
<i>N</i> is the key number of your choosing and 12345678 is a
<a
  href="http://en.wikipedia.org/wiki/Nothing_up_my_sleeve_number">"nothing
  up my sleeve" number</a> I chose for validating a decryption.
The ciphertext is thus <i>m</i><sup><i>e</i></sup> (mod <i>n</i>),
calculated using <a
  href="http://en.wikipedia.org/wiki/Exponentiation_by_squaring">exponentiation
  by squaring</a>, mod <i>n</i> at each step (which is what
<tt>expmod</tt> does in <tt>bn.h</tt>), and then you do the reverse of
<tt>decode</tt> to turn the number into a string.
<br /><br />
The code I used for generating RSA private key pairs is <a
  href="/code/rsa_genpriv.c.txt">rsa_genpriv.c</a> and for generating
license keys is <a href="/code/rsa_genlic.c.txt">rsa_genlic.c</a>.
These require <a href="http://gmplib.org/">libgmp</a>; the job is just
too big for poor little <tt>bn.h</tt>.
<br /><br />
(All my code here is MIT-licensed, by the way, so feel free to
steal it for your own purposes.  By all means, use it instead of some
silly easy-to-duplicate hashing scheme for your application...)
<br /><br />
So, will RSA-based license schemes work?  Not with such a short key
length.  Can we just make the key length longer?  Well, that depends.
Your ciphertext is always going to be a number between 2 and <i>n</i>,
if <i>n</i> is 512 bits then so is your ciphertext.  1024 bits is
probably the smallest reasonably secure size you'd want to use for
RSA, which is 205 characters in the A-Y,1-9 code I'm using.  So if
your users are pasting keys out of an email, that's probably fine, but
if they're typing it in by hand off of a CD case, forget it.
<br /><br />
Also, this scheme, though cryptographically weak, has some points
in its favor.  If a theoretical cracker disassembles the code, he
absolutely <b>must</b> understand RSA at some level, extract <i>n</i>,
and factor it in order to create a key generator.  I probably wouldn't
have the patience to do it if the least bit of obfuscation were used
in conjunction.  It's totally self-contained (so you don't have to
link in libcrypto or libopenssl or libgmp), so it's pretty much a
drop-in replacement for whatever hashing scheme that most software
tends to use.
<br /><br />
And, though the backbone of the challenge was quickly broken, only
one person demonstrated a keygen.  I guess one is all it takes.
<br /><br />
Can we do better?  Yes, I think we can do much better.  RSA's
security derives from the difficulty of the integer factorization
problem.  There are two other commonly used classes of asymmetric key
cryptosystems based on harder problems: discrete logarithm and
elliptic curve discrete logarithm.  Each provides more "strengh" per
bit of key than the last.
<br /><br />
<a href="http://www.reddit.com/r/programming/comments/890yf/hacker_challenge_can_you_make_a_key_generator/c08l6dl">james_block
  brings up some good points</a> along these lines.  It may not be
possible to create a software license scheme with both short license
codes and enough security to withstand a large, coordinated effort to
break it.  But it's far better to use a license key scheme that could
be broken with a large effort than one that will definitely be broken
with a small effort, when the former is an easy drop-in replacement
for the latter.  Truly uncrackable (in the cryptographic sense)
security will require longer keys and users who paste keys out of
emails.
<br /><br />
So here is challenge #2.  I've used another common algorithm which
is no longer encumbered by a patent.  The ciphertext is still slightly
less than 125 bits.  It is not impossible to crack by any means, but
it is much harder (in terms of CPU time necessary) than the previous
one.  And there's always the possibility that I screwed something up
and left a big back door in it, which is a good reason for proposing
the challenge in the first place.
<br /><br />
The code:
<br /><a href="/code/keydecode2.cpp.txt">keydecode2.cpp</a> - challenge #2 decoder
<br /><a href="/code/bn.h.txt">bn.h</a> - quick and dirty bignums (updated from
last time)
<br /><br />
I plan on issuing one further challenge next week, and there's a
good chance that this one will be broken before then if it receives
the same level of attention as the first one did.
<br /><br />
<a
href="http://www.reddit.com/r/programming/comments/89vma/hacker_challenge_part_2_solution_to_part_1_and_a/">Here</a>
is the reddit thread for part 2.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2009/03/index.html#e2009-03-31T18_50_59.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2009/03/index.html#e2009-03-31T18_50_59.txt</guid>
<title>Hacker challenge: Can you make a keygen?</title>
<dc:date>2009-03-31T18:50:59-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[I like to reverse-engineer things, and I like number theory.  These
hobbies happen to intersect in the art of reverse-engineering software
license keys.
<br /><br />
I won't lie: I've cracked programs.  I've created key generators for
programs.  But I also never distribute them.  I do it for the
challenge, not for the program.
<br /><br />
But from a warez d00d perspective, it is infinitely preferable if you
can create a key generator instead of cracking, because then you can
typically get further software updates, and things are just easier for
everyone. 
<br /><br />
It is sometimes shockingly easy to create a key generator.  Often a
program that checks a license key is structured like this:  
<br /><br />
<pre>
  licensestr = get_license_key_modal_dialog()
  validlicensestr = make_valid_license(licensestr);
  if(licensestr == validlicensestr) { ... }
</pre>
  
So now all I have to do is extract your make_valid_license code, feed
it random garbage, and I have a key generator for your program.  One
time I just replaced the call to strcmp() with puts() in a program and
turned it into its own key generator.
<br /><br />
Other key generators cycle through a hash of some sort (the hash is
sometimes srand() / rand()) and ensure some check digits, or whatever.
Any way you slice it, it's security through obscurity: you're giving
the end user the code, and if end user can read and understand that
code, they can break it.
<br /><br />
It doesn't have to be this way.  I have created a self-contained
license key decoder, and I'm distributing the source code to it.  In
my next post, I will reveal all the details and how to create keys for
it.  For now, I want to see whether anyone can break it without having
the "official" key generator.  If so, there's a flaw in my reasoning.
It uses a well-known, public-domain algorithm; that's all I'm going to
say for now.
<br /><br />
The code is here:
<br /><br />
<a href="/code/keydecode.cpp.txt">keydecode.cpp</a> - key decoder
<br /><br />
<a href="/code/bn.h.txt">bn.h</a> - quick and dirty bignums
<br /><br />
(The web host I'm using has the wrong MIME types on .cpp and .h, so they're
.txts - sorry)
<br /><br />
I would like to open up a <a
href="http://www.reddit.com/r/programming/comments/890yf/hacker_challenge_can_you_make_a_key_generator/">discussion
on reddit</a>.  Undoubtedly many people there will recognize the
algorithm and maybe poke holes in what I'm doing.
<br /><br />
<b>Update</b>: "maybe poke holes in what I'm doing".  Ha.  More like
drive a cement mixer through it in minutes.  I was pleasantly
surprised to find that this reached #1 on the programming subreddit.
LoneStar309 found a gaping hole which I patched, and tharkban also
found a bug in the final if statement, also fixed.  It's fair game to
make keys that way for the challenge I proposed, I suppose, but I
wanted to see whether the idea would work, not necessarily my poor
implementation of it.  Turns out: no, it won't, and unsurprisingly
it's been done before.  Part 2 coming later.
<br /><br />
<b>Update 2</b>: <a
href="http://a1k0n.net/blah/archives/2009/04/03/index.html#e2009-04-03T21_36_15.txt">Hacker
challenge part 2</a> has been posted.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2007/10/index.html#e2007-10-12T14_39_12.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2007/10/index.html#e2007-10-12T14_39_12.txt</guid>
<title>Vendetta Online source code</title>
<dc:date>2007-10-12T14:39:12-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>
<dc:subject> Vendetta, Obfuscated C</dc:subject>
<description><![CDATA[By request: <a href="http://a1k0n.net/code/vosource.c.txt">Vendetta
Online's source code</a>.
<br /><br />
(Updated 3/9/2010: I added a usleep in there, cause it runs way too
fast)
<br /><br />
(From <a
href="http://www.vendetta-online.com/x/msgboard/2/14902?page=2">this
thread</a>, referencing an inside joke from a <a
href="http://www.vendetta-online.com/x/msgboard/1/2807#38314">much
earlier thread</a>, but the message ordering got all mixed up at some
point when I had to reindex the message IDs in the database (sigh)).]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2007/10/index.html#e2007-10-09T23_03_25.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2007/10/index.html#e2007-10-09T23_03_25.txt</guid>
<title>Updates!</title>
<dc:date>2007-10-09T23:03:25-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>
<dc:subject> Personal</dc:subject>
<description><![CDATA[I sure don't update this blog very often.  So, let's see...
<br /><br />
Since I've posted last:
<br /><br />
John has replaced fear.incarnate.net, our long-standing webserver,
with a new box.  This one has 750gig mirrored disks, whereas the old
one was constantly running out of space.  Of course, since they're
John's disks, one of them died already.  (Vendetta's DB server's hot
spare disk was DOA, and fear's two mirrored disks have died at the
same time in the past, and then there was the Micropolis disk
debacle.. in short, John has the worst luck with hard disks)
Apparently the warranty on them is good until 2012, so that's good.
<br /><br />
Nanoblogger has been upgraded, and as a result my site got a little
facelift.  Woo.  It's.. uglier, I think.
<br /><br />
I found out that my wife's coworker Jen's husband <a
href="http://www.damonpayne.com/">Damon</a> works at CarSpot.com,
where <a href="http://superpants.com">Nick Purvis</a> worked until
recently.  I think Nick was a cofounder.  Jen and Damon live right
down the street from us; the first time I met them was at their
wedding.  Small world, I guess.
<br /><br />
I also want to point out, belatedly, that I made it to 26th on the <a
href="http://www.icfpcontest.org/submits/scoreboard">ICFP 2007
contest</a>, and with Ray's help our combined Guild Software effort
made it to 22nd.  I didn't get to spend much time at all on this
contest as I was busy that weekend, but I'm pleased with how well we
did given the effort.  (A sort of post-mortem is <a
href="http://programming.reddit.com/info/28xdp/comments/c28zc7">here</a>).
<br /><br />
Speaking of programming contests, Damon's site reminded me of <a
href="http://projecteuler.net">Project Euler</a>.  It's pretty fun,
highly recommended.  (see <a
href="http://projecteuler.net/index.php?section=profile&profile=3464">my
profile</a> - but you must be logged in for that).  
<br /><br />
I was also in the ~200s ranking (nothing to write home about) on the
<a href="http://netflixprize.com">Netflix Prize</a> back in March but
I've fallen even lower (607 as of this writing - now that's
embarassing) since then.  I used a maximum-likelihood singular value
decomposition approach except with a conjugate gradient optimizer
(L-BFGS, to be specific, a quasi-Newton method), which is a hell of a
lot more efficient than any gradient descent method with learning
rates that a lot of other people are using.  But I didn't devote all
that much CPU time to it, and I need to do a fair amount of
preprocessing of the data to be more competitive.  Seems a lot of
people are getting a handle on this very interesting problem.  
<br /><br />
The Netflix challenge been very educational for me as I've been able
to put a lot of stuff I learned from <a
href="http://www.inference.phy.cam.ac.uk/mackay/itila/book.html">David
MacKay's excellent book</a> into context.  If I come back to the
problem I'll probably try Hamiltonian Monte Carlo or Gibbs sampling in
order to get more than one sample to marginalize over.
<br /><br />
Also, watch for the IOCCC 2006 results announcement in November...
<br /><br />
If one of the two people who actually read this blog would like
elaboration on any topic I would be happy to oblige.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2007/08/index.html#e2007-08-24T15_40_49.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2007/08/index.html#e2007-08-24T15_40_49.txt</guid>
<title>Another short C program.</title>
<dc:date>2007-08-24T15:40:49-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>
<dc:subject> Obfuscated C</dc:subject>
<description><![CDATA[<pre>
b[2080];main(j){for(;;){printf("\x1b[H");for(j=1;j&lt;2080;j++)b[j]=j&lt;
2000?(b[j+79]+b[j+80]+b[j]+b[j-1]+b[j+81])/5:rand()%4?0:512,j&lt;1840?
putchar((j%80)==79?'\n':" .:*#$H@"[b[j]&gt;&gt;5]):0;usleep(20000);}}
</pre>
<br /><br />
update: fixed a crashing bug.  It has other issues with uninitialized
data, though.]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2007/07/index.html#e2007-07-12T17_26_38.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2007/07/index.html#e2007-07-12T17_26_38.txt</guid>
<title>the end.</title>
<dc:date>2007-07-12T17:26:38-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>

<description><![CDATA[Lingering narrative concepts and furtive simplistic montage are the
harbingers of the new semiotics!
<br /><br />
But language as a patriarchal construct of insipid teledildonics
obscures the struggle for representational power and ideology!
<br /><br />
No.  (No no no no no no no no)  Noooo!  We project prefrontally the
supersocietal oppression of convergent transaction with art.
<br /><br />
Speak to me now, bad kangaroo<br />
Speak to me now, bad kangaroo<br />
Speak to me now!
<br /><br />
<object width="425" height="350"> <param name="movie"
value="http://www.youtube.com/v/oY-TRd9VujA"> </param> <embed
src="http://www.youtube.com/v/oY-TRd9VujA"
type="application/x-shockwave-flash" width="425" height="350">
</embed> </object>]]></description>

</item>
<item>
<link>http://a1k0n.net/blah/archives/2006/09/index.html#e2006-09-20T19_10_14.txt</link>
<guid isPermaLink="true">http://a1k0n.net/blah/archives/2006/09/index.html#e2006-09-20T19_10_14.txt</guid>
<title>Building on the donut: here's an old-school CG cliche</title>
<dc:date>2006-09-20T19:10:14-06:00</dc:date>
<dc:creator>a1k0n</dc:creator>
<dc:subject> Obfuscated C</dc:subject>
<description><![CDATA[<pre>
_,x,y,o       ,N;char       b[1840]       ;p(n,c)
{for(;n       --;x++)       c==10?y       +=80,x=
o-1:x&gt;=       0?80&gt;x?       c!='~'?       b[y+x]=
c:0:0:0       ;}c(q,l       ,r,o,v)       char*l,
       *r;{for       (;q&gt;=0;       )q=("A"       "YLrZ^"
       "w^?EX"           "novne"     "bYV"       "dO}LE"
       "{yWlw"      "Jl_Ja|[ur]zovpu"   ""       "i]e|y"
       "ao_Be"   "osmIg}r]]r]m|wkZU}{O}"         "xys]]\
x|ya|y"        "sm||{uel}|r{yIcsm||ya[{uE"  "{qY\
w|gGor"      "VrVWioriI}Qac{{BIY[sXjjsVW]aM"  "T\
tXjjss"     "sV_OUkRUlSiorVXp_qOM&gt;E{BadB"[_/6  ]-
62&gt;&gt;_++    %6&amp;1?r[q]:l[q])-o;return q;}E(a){for (
       o= x=a,y=0,_=0;1095&gt;_;)a= " &lt;.,`'/)(\n-"  "\\_~"[
       c  (12,"!%*/')#3"  ""     "+-6,8","\"(.$" "01245"
       " &amp;79",46)+14],  p(""       "#$%&amp;'()0:439 "[ c(10
       , "&amp;(*#,./1345" ,"')"       "+%-$02\"! ", 44)+12]
-34,a);  }main(k){float     A=0,B= 0,i,j,z[1840];
puts(""  "\x1b[2J");;;      for(;; ){float e=sin
(A), n=  sin(B),g=cos(      A),m=  cos(B);for(k=
0;1840&gt;   k;k++)y=-10-k/    80   ,o=41+(k%80-40
       )* 1.3/y+n,N=A-100.0/y,b[k]=".#"[o+N&amp;1],  z[k]=0;
       E(  80-(int)(9*B)%250);for(j=0;6.28&gt;j;j   +=0.07)
       for  (i=0;6.28&gt;i;i+=0.02){float c=sin(    i),  d=
       cos(  j),f=sin(j),h=d+2,D=15/(c*h*e+f     *g+5),l
=cos(i)        ,t=c*h*g-f*e;x=40+2*D*(l*h*  m-t*n
),y=12+       D  *(l*h*n+t*m),o=x+80*y,N  =8*((f*
e-c*d*g       )*m   -c*d*e-f*g-l*d*n)     ;if(D&gt;z
[o])z[o       ]=D,b[     o]=" ."          ".,,-+"
       "+=#$@"       [N&gt;0?N:       0];;;;}       printf(
       "%c[H",       27);for       (k=1;18       *100+41
       &gt;k;k++)       putchar       (k%80?b       [k]:10)
       ;;;;A+=       0.053;;       B+=0.03       ;;;;;}}
</pre>
(again, compile it with -lm, and it needs ANSI-ish terminal emulation)]]></description>

</item>
</channel>
</rss>
