Website title

Computing: The Details
Lex's blog of curious computer-related shenanigans.

Blog post

A Privacy Perserving Postcode Lookup Tool

Published: 2025-06-27 Updated: 2026-01-13

This blog post is also available as a video series! Watch it on YouTube: Part 1 | Part 2 | Part 3

Part of a series of posts: Next in series >

Let’s talk about store locators.

You’ve probably used a website that has a store locator. For example, there’s a chain of supermarkets in the UK called The Coop. On their website is a store locator. You can type in a postcode and it will list a selection of your closest Coop shops.

Screenshots of store locator pages. From left to right: The Cooperative, Tesco, B&Q

If you have a look at the network tab in the developer tools when you use it, you will see that the postcode is sent to some web server. Before I’ve even typed the whole thing it’s made an API request to get a list of possible postcodes that I might be interested in. When I select a postcode from the list, it then sends that to a different API endpoint. That one returns a list of shops that I might be interested in, which is then presented to me on the page. I also get a map view, which potentially has other problem, but I’m not super interested in that at the moment.

The Coop site uses Google maps to provide this service. If you type your postcode in to this page then it sends that postcode to Google. You were never asked if you were happy for Google to know what postcodes you’re interested in.

Tesco offers the same thing. They use Mapbox APIs. Again, the postcode is sent to a different web server to the one that the main website came from, so your postcode searches are leaking beyond the one website that you’re using.

Plenty of other websites do exactly the same thing. B&Q is a chain of hardware and home improvement stores. They go a step further and guess your location based on your IP address. In most cases this is going to be a good guess. They’re probably using some API to do that too. But if you have a look at what they do with a postcode then you'll see they use another similar API from Woosmap. They then make an API request to a site called kingfisher.com to find the nearest stores. Kingfisher is the company that runs B&Q along with similar stores under different brands.

All these big chains are totally happy to ask for your postcode, and then send it off to some other web service you’ve maybe never heard of, or worse: Google, and use that to locate your nearest stores for your convenience.

There are companies that make money from buying and selling information like “This person, who you can identify by this web tracking cookie, likely lives near this postcode.” They build profiles of web users as they browse across many different websites, adding information to your profile as they learn new things.

If all they did with this data was target adverts, then that might not be concerning, but maybe your life insurance company is buying that data and deciding that you’ve been looking up your nearest Fast Food Chain a little too often. You’re a greater heart-attack risk than most. Looks like you’re gonna have to pay more for your life insurance.

I’m not saying that they’re all doing this. But when you consider that this is possible, it’s better to prevent that data being collected in the first place. A little aside: this is why the EU created a law that forbids websites from placing tracking cookies in your browser without consent. Lots of website operators decided that the appropriate way to comply with this law was to put intrusive and confusing popups on the page that make it easy to give consent, and not always as easy to deny consent. But today’s video is not really about that.

There’s lots of examples of websites that have these store locator features, but I’ve never seen one that is designed for privacy. I would love to come across a website with a store locator that verifiably did not let my postcode escape from my web browser in to some random web service. This means that the postcode can’t be allowed to get out of my web browser at all.

I would love this so much, in fact, that I decided to make it happen. I did it not just to prove that it is possible, but to provide the resulting tool for free to anyone that wants it.

UK Postcodes - What you need to know

There’s currently almost 1.8 million active postcodes in the UK. Each one holds a small number of addresses. Sometimes a postcode has a single address inside it. Sometimes a postcode maps to an entire street with tens of addresses.

Postcodes are deliberately constructed such that no house name or number is duplicated within a single postcode. This means that, technically, if you send a letter to 10, SW1A2AA, that will be delivered to the UK Government headquarters. You don’t need to write “Downing Street” on your letter. You don’t need to write “Westminster” or “London” on it either. The postcode and door number is sufficient.

It’s still a good idea to include those details when you send a letter or package. They provide some redundancy.

Every UK postcode is made up of two parts. The first part is called the Outward code, the second part is the Inward code.

-----------------------------------------
| Postcode | Outward code | Inward code |
-----------------------------------------
| B11RS    | B1           | 1RS         |
| B111RS   | B11          | 1RS         |
| SW1A2AA  | SW1A         | 2AA         |
-----------------------------------------

The inward code is the simplest part. It is always 3 characters long. The first of these is a digit, then the last two characters are letters. These tend to be allocated sequentially, but not with much consistency. They start at 0AA, and continue with 0AB, and onwards until 9ZZ. They aren’t always all used. For example, for the Outward code of AB12, the lowest currently active Inward code is 3AA. There’s some small gaps here and there until it reaches AB12 5YX, and then a sudden jump to AB12 9AL.

The Outward code is everything except the last three characters. This code can be 2, 3, or 4 characters long. For example: B1 is the 2-characters Outward code for an area in the centre of Birmingham. B11 is a different area of Birmingham, and is 3 characters long. We’ve already seen a 4-character Outward code SW1A.

That Birmingham example is interesting though. It shows something that makes it tricky to parse a postcode. B1 1RS is a postcode for a shopping area in the centre of Birmingham. B11 1RS is a very similar postcode that is nearby, but it’s in a residential area of Birmingham. If you write these without the space between the Outward and Inward codes, as many people often do, then they both start with B11. Any system that parses a postcode should therefore not assume that a postcode that starts with a known Outward code is, in fact, located in that Outward code. Instead it should separate the Inward code first, since that’s always 3 characters long, and then parse what remains as an Outward code.

Two postcodes plotted on a map. B11RS and B111RS. They are 2.2km apart.

Okay, I think we understand enough to make something that works, so let’s get in to engineering a privacy preserving store locator system.

The way we’re gonna make this privacy-preserving is by avoiding sending any specific postcode over the internet to lookup its coordinates. This means that we need the browser to do all of the computation about the distance to each store from the postcode. Once the page is loaded, it should be possible to completely disconnect from the internet, and still use the store locator.

That means we need some way to know the GPS coordinates of every UK postcode without doing a lookup via a web service.

Getting the data

The key thing that we need is a complete mapping of UK postcodes to GPS coordinates. The Royal Mail has a complete mapping of postcodes to addresses. And they let you access most of it on their website. Strangely enough, when I tried looking for 10 Downing Street, it wouldn't tell me that the postode for it is SW1A 2AA.

Anyway, this database is called Postcode Address File (PAF). If I want a copy of it then I need to buy a license that costs thousands of pounds and needs to be regularly renewed.

The Royal Mail has monetised their postcode and address database!

Fortunately, there is a public body in the UK called the Office for National Statistics (ONS), who maintains an open database of all postcodes and the GPS coordinates of their approximate centres (where appropriate).

Since they're a public body, everything they do is open to the public. And they don't even make you do a Freedom of Information (FOI) request to get it!

The ONS provides a download that’s updated every few months with all the UK postcodes and their GPS coordinates.

If you thought it was going to be the Ordnance Survey (OS), that was a good guess. OS does provide a similar data set called Code-Point. In fact the ONS data set is actually based on the OS data set, but the OS version doesn’t include GPS coordinates, instead it provides UK National Grid coordinates.

The National Grid is the grid system that OS uses on their maps. (Not to be confused with the National Grid, which is the UK’s electricity distribution infrastructure.) The conversion from National Grid coordinates to GPS coordinates is not required if I use the ONS data set, so that’s why I chose that one.

I should clarify: the GPS coordinates are approximate. A postcode isn’t really a single point, it’s an area. It can be quite a big area. The Royal Mail even explicitly warns us about this on their website. Regardless, any point in that area is going to be a useful approximation for locating your nearest store.

The hard part (making it work)

Okay we have the data, can we just write some javascript that fetches that file ready to use offline, and when a user types in a postcode, it looks up the coordinates and then calculates the distance to each store?

No, not that easily anyway.

This file is 1.4GB! That’s enough to wipe out someone’s entire mobile data allowance in a single page load! That’s too big!

It contains a lot of fields we don’t care about. Let’s get rid of all fields except for the postcode, longitude, and latitude. As we do that, we can also discard any postcodes that have been terminated, and any that don’t have coordinates associated with them.

The file is now 48MB. That’s better, but it would still take about 5 seconds to download that over my home internet connection. It doesn’t sound like a lot for one user, but I want this to scale well. I don’t want to add a lot of additional load to the server, or consume excessive bandwidth. There’s also energy to consider too. I think it’s often overlooked, but coding for minimal energy usage is valuable.

Let’s take a closer look at how postcodes work. Earlier I explained how a postcode is an Outward code and an Inward code. If I want to optimise how I store them, I’m going to need to think about them as data. Below is a table of possible values for each position in the code

Position |  1  |  2  |  3  |  4  |  5  |  6  |  7  |
----------------------------------------------------
         | A-Z | A-Z | A-Z | A-Z |     | A-Z | A-Z |
Options  |     | 0-9 | 0-9 | 0-9 | 0-9 |     |     |
         |     |     |blank|blank|     |     |     |
----------------------------------------------------
example  |  S  |  W  |  1  |  A  |  2  |  A  |  A  |
----------------------------------------------------
# opts   | 26  | 36  | 37  | 37  | 10  | 26  | 26  |
----------------------------------------------------

The Outward code always starts with a letter. The second character is either a letter or number, the third might not exist at all, but if it does, then it is a letter or a number. The fourth also might not exist, but can be a letter or a number.

To make parsing easier, you can always store postcodes in a fixed width format that is 7 characters long. You start with the Outward code. You then add 0, 1, or 2 space characters as padding, and finally add the Inward code.

Given this pattern, the first character has 26 possible values. The second has 36. The third has 37, if using the space-padding approach. The fourth has 37. The Inward code’s three characters have 10, 26, and 26 possible values respectively.

Now a hint of information theory. How many bits do we need?

26 × 36 × 37 × 37 × 10 × 26 × 26 = 8,662,155,840

log₂(8,662,155,840) ≈ 33.01

The total number of possible postcodes is about 8.6 Billion. That’s a super inconvenient number actually! This means you can’t quite store a postcode as a 32 bit integer. Even 33 bits is not enough, you need 34, but only just.

So far I haven’t made any assumptions based on which postcodes are actually in use, and I want to keep it that way. 8.6 Billion is the most postcodes we could have with this system. I want to avoid adding in any assumptions that reduce this space, so that this system continues to work in the future as more postcodes are added.

We’re gonna have to get creative about how to represent postcodes.

Making a better storage format

Let’s ditch the CSV format, and go for a raw binary representation. If I store each postcode as a number, then I can do that in 5 bytes. I need at least 34 bits, which is 40 bits if you round up to the next multiple of 8. 40 bits is 5 bytes, hence needing 5 bytes to store a postcode.

Given that the postcodes normally take up 7 bytes, this is a reduction of about 30%

While I’m doing that, I should also reduce the coordinates to a numerical representation too. Each one takes up about 9 characters in string form. A 64 bit floating point number would certainly be precise enough for a GPS coordinate, that costs 8 bytes. That’s not a big saving over the 9 bytes they were before. Perhaps we could use 32 bit floats, that way we need 4 bytes per number, that’s a lot better than 9! This is a reduction of 44%.

Overall, including the commas and newlines and whatnot, the postcode and coordinates in string form in a CSV file took 28 bytes per entry. With a packed numerical representation, which does not need the commas and newlines, this is reduced to 13 bytes per entry. This is less than half the initial size.

There’s a much better way to do this though.

Consider how a lookup works in this file:

The user has typed in a postcode, and wants to know if it is in the file. The search program needs to find that postcode in the file. The obvious simple algorithm to do this is to start at the beginning of the file, read the first postcode, see if it matches the typed postcode, and if not move on to the next entry in the file. Eventually you will hit either: the entry for the postcode you want, or the end of the file.

Scanning the entire file like this takes a significant amount of time. For the CSV version it’s about 740ms on average for a successful lookup. Sometimes it takes longer, sometimes it’s faster. It depends where in the file you find the postcode.

Another potential improvement we could make to the list of postcodes would be to reduce the amount of repetition in it. There’s a lot of postcodes that start with AB right at the start of the file. What if I had some way to insert information in to the file like “postcodes from this point on start with AB, only the last 5 characters are stored”. In that case I could remove the “AB” prefix, and save a little space.

One last idea to explore: A postcode does not define a point, it defines an area. The coordinates provided for a postcode are an approximate centre for the postcode area. Lossy compression is a category of compression where the data you get out of the decompression algorithm is not exactly the same as what you put in to the compression algorithm. The decompressed value is an approximation of the original value. Sometimes this is unacceptable, like when compressing text, such as the subtitles on this video perhaps. Sometimes this is acceptable, such as when compressing a photograph. If each pixel is almost the same colour as the original, you probably won’t notice, nor will you care. In the case of our coordinates, the values are approximate anyway, so perhaps some lossy compression is okay.

So here we have a few thoughts to guide the creation of a file format and algorithms for storing and looking up postcodes:

  • Lookup time should be minimised.
  • Prefix repetition could be avoided.
  • Lossy compression of coordinates could be okay.

Let's take a look at that design now.

The Format and Algorithms in Detail

As the encoder program reads list of postcodes in to memory, and parses the coordinates for each one, it keeps track of the bounding box that surrounds all the postcodes. The program then pretends this is a square. It’s not actually a square, it's also not a rectangle, it’s actually a part of the surface of a spheroid, but the maths we’re doing doesn’t actually care too much about the shape since we're just going to do a transform that we are going to undo to get the original coordinates back later. It’s just a set of coordinates, we can visualise it as a square

A map of the UK showing some of the GPS coordinates for postcodes (each is a red triangle). The set of postcodes shown includes the etreme north, east, south, and west postcodes. A green bounding box is drawn around all the red triangles.

So now we have longitude and latitude values for the edges of our conceptual square as 64 bit floating point values. These values go directly in to the file, right at the start.

Next, the encoder iterates over the postcodes, and for each one it splits the code into two parts. The first is the two character prefix, and second is everything else. Previously I said that you need 34 bits to store the postcode as a number. With the prefix removed, that reduces dramatically, to 24 bits. This is great because it fits very efficiently in three bytes.

Postcodes with two-character prefix removed

Position |  1  |  2  |  3  |  4  |  5  |  6  |  7  |
----------------------------------------------------
                     | A-Z | A-Z |     | A-Z | A-Z |
Options              | 0-9 | 0-9 | 0-9 |     |     |
                     |blank|blank|     |     |     |
----------------------------------------------------
# opts   |  1  |  1  | 37  | 37  | 10  | 26  | 26  |
----------------------------------------------------

⌈log₂(37 × 37 × 10 × 26 × 26)⌉ = 24 bits = 3 bytes

The coordinates are then compressed with a lossy compression system. Below is the formula used to compress the latitude coordinate. The minimum latitude from the bounding box calculation is subtracted from the postcode’s latitude coordinate. This calculates the distance in to the box from the bottom edge. This is then divided by the height of the box. This results in a value in the range 0 to 1. This is then scaled up by multiplying by 65535, and rounding to the nearest integer. This results in a 16 bit number that represents a latitude in the bounding box.

The formula described above, and a visual representation of how it maps the spheroid section to a square.

The longitude is processed in a similar way, and now I can store the latitude and longitude in four bytes. This means that each postcode and coordinate entry is 7 bytes long, but doesn’t have the prefix included. This is another good improvement over the 13 bytes per postcode from before, and it’s only a quarter of the size of each entry in the CSV file.

Table showing packed postcode format, as specified above.

The encoder processes all the postcodes like this and keeps a list of all of them. While it does this, it also keeps track of the prefixes in a table. The postcode table is sorted, so all of the postcodes with the same two character prefix will appear together. As it scans the list, any time a new prefix is encountered, it will put an entry in the table to indicate how many postcodes there were before the first one with that prefix.

Once all the prefixes are added to the table, the total number of postcodes is added at the end of the table, and all of the prefixes that were not used also get values in the table. The value of each of these unused prefixes is the value of the next prefix after that one in the table.

Example Prefix Table:
A0-AA:      0
AB   :      0
AC-AK: 17,385
AL   : 17,385
AM-B0: 25,185
B1   : 25,185
B2   : 30,800
B3   : 36,202
B4   : 42,028
...
(Ranges of the same value are fully expanded in the real file,
they are abreviated here only to fit more entries in the example)

Now the encoder writes the table values in to the file, and then all of the packed postcodes in order. And that’s it! The file is ready to go!

This file is about 12MB. That’s 25% of the minimised CSV file size. But how do we use this file?

Let’s have a look at the lookup algorithm next.

The first step of this algorithm is to make sure the postcode is correctly formatted. Some people will deliberately put a space in their postcode, between the Outward and Inward codes. Some people will try to put such a space in and get it in the wrong place. Some people use no spaces at all. Some people will use upper case, others will use lower case. Rather than require the user to type the postcode in the correct format, the algorithm just does this for them.

Formatting a postcode is fairly easy. First make sure all the letters are upper case, remove all the spaces that the user put in there, and then insert spaces between the Outward and Inward codes until you have a 7 character string. Since the Inward code is always 3 characters, it’s easy to find where to insert the spaces.

Of course, some postcodes are too malformed to recover them. If you miss some of the code, or include an invalid character, this step will cause an error.

Initial user input:       "b 11 rs"
-----------------------------------
1. Upper case all chars:  "B 11 RS"
2. Remove all spaces:     "B11RS"
3. Insert correct spaces: "B1  1RS"
-----------------------------------
Well formed output:       "B1  1RS"

Now we split the postcode up to get the two character prefix and the rest. We turn the prefix in to a number, and separately encode the rest of the postcode as a number just like the encoder did when it created the file. Now we can parse the file. It starts with the bounding box coordinates, which are easy enough to read. Then we use the prefix number to look up where to start scanning for the postcode in question. Because of the way that this part of the file was constructed, we can be sure that the next number in the table after this one represents the furthest we would ever need to scan to find a postcode with this prefix, so we make a note of that too.

Postcode: "B1  1RS"
Prefix:   "B1"
Suffix:   "  1RS"

Numbers from prefix lookup table:
Lookup start point: 25,185
Lookup end point  : 30,800

Now we multiply these numbers by 7, since that’s the length of each postcode, and now we know the byte offsets in to the file where we should start and stop scanning. Calculating the distance to the end of the table, and adding the start offset allows us to know where to seek to, skipping lots of postcodes that have other prefixes.

Now we just need to grab each postcode in sequence, and compare it to the number we calculated at the start. If the postcode doesn’t exist, then we will hit the end of the search range. If it does exist, then we will find a match, and can then reverse the calculation done on the coordinates to compress them.

The coordinates can’t be retrieved exactly, because there was some rounding involved in calculating them, and possibly some floating point errors too, but the results are typically within a few metres of the actual values. Certainly precise enough for something as approximate as a postcode.

This lookup process is able to skip over lots of postcodes without even reading them, this makes it much faster than a lookup in the CSV file. The average lookup time is reduced from 740ms to only 3.3ms. This is a huge saving! Three quarters of a second is long enough to notice, but a few milliseconds is barely perceptible. This is certainly fast enough.

Notice that this speed up is much more than you’d expect just from the file being shorter, so clearly the structure and lookup algorithm had a big impact too.

Remember those three things from earlier: Lookup time should be minimised. Prefix repetition could be avoided. Lossy compression of coordinates could be okay.

Designing with these in mind produced a much smaller and faster solution, but I’m not done yet!

We have to go deeper go smaller!

That lookup time is excellent! In fact, it’s so good, that I think it would be acceptable to trade off a little bit of lookup time for an even smaller file size. 12MB is still a bit too big to expect a casual user to be okay with.

So here’s another thing to consider: The postcodes are sorted, and they come in densely packed clusters. There’s big gaps between the clusters, but within each cluster it’s easy to predict what postcode is going to come next.

This encoding scheme is what I’m calling the delta encoding. Some of the values in the file are not stored in absolute numbers, they are instead stored as a delta on top of the previous value in the file.

Previously a postcode was a fixed 7 byte structure, now it’s going to vary in length. The postcode is normally 3 bytes, and the coordinates are normally 4 bytes. If the coordinates are close enough to the previous ones, then I could instead store a pair of 8 bit signed integers that are added to the previous coordinates to get the next coordinates. The postcodes are sorted, so I never need to go backwards, so for the postcode delta I can store an unsigned number. I decided to limit this number to 6 bits, which will make sense soon, giving the delta a range of 1 to 64.

Now the structure has four different formats. The first byte determines which format is used. Bits 7 and 6 of the first byte are flags that indicate which fields are delta encoded. If bit 7 is set, then the postcode is delta encoded. If bit 6 is set then the coordinates are delta encoded. So the worst case scenario is when neither is delta encoded. The first byte just has the value 0, and then the next 7 bytes are the postcode and coordinates in the same format as before. This takes up 8 bytes, so it’s actually slightly worse than before, but that’s fine because the next three cases are far more common.

If the postcode is delta encoded, then the delta to the next postcode is stored in the last 6 bits of the first byte. The coordinates then appear immediately after this. If the coordinates are not delta encoded then this case is only 5 bytes in total.

Perhaps only the coordinates are delta encoded, in which case it’s 6 bytes in total.

Finally, the best case is when both of them are delta-encoded, for this case I only need 3 bytes to store the entire entry. It turns out that 91.9% of all the postcodes can be encoded in the 3 byte format, and only about 0.37% of them need to be stored in the fully expanded format.

Table showing packed postcode format, as specified above.

This saves a lot of space! The new data file is only 5.5MB.

This encoding scheme is much more complicated, and so the lookup time does suffer a little bit. The lookup algorithm needs to be modified to handle the delta encoding. It needs to keep track of the previous postcode and coordinates as it scans the file. It needs to parse the structure to figure out how to update its internal state, and to know how far to move the cursor onwards.

Previously it was always moving by 7 bytes, now it might be 3, 5, 6, or 8.

So how big is the effect? Well the average lookup time with this method is about 6.6ms. Despite the file being less than half the size it was before, the lookup time has doubled! That’s unfortunate, but it is still really fast. It’s still in the barely perceptible range. Looking at the graph we can see that both of these formats handily beat the CSV format.

A bar graph comparing the size of the files for the various packing methods. For CSV, Packed, and Delta packed respectively, the sizes are 48MB, 12MB, and 5.5MB A bar graph comparing the average lookup time of the files for the various packing methods. For CSV, Packed, and Delta packed respectively, the average lookup times are 740ms, 3.3ms, and 6.6ms

Getting speed gains has been much easier than getting space gains, but I’m happy with the delta encoding scheme’s size and speed.

A Fun Demo

So, getting back to the problem I wanted to solve, let’s have a look at a little demo that uses this system to do a privacy preserving locator tool.

See a demo for yourself

If you open that page and then open the developer tools window of your browser (normally F12), then you can see the magic happen. Clear everything from the network requests tab after loading the page but before enabling the search tool. (Since it needs to download a file that is slightly abnormally big for a website, I thought it best to make sure the user is aware that they’re about to download it.)

Clicking the button, you can see that the file download shows up in the network requests tab. And now the search tool is enabled. At this point, you could totally disconnect from the internet, and this would still work. Type in a postcode, press search, and you'll see a list of all the Automobile Association Call Boxes sorted by their distance to that postcode. Notice that no additional network requests were made, the lookup happened offline.

In a real world scenario, I might expect one additional network request to occur when the search tool loads, to load the list of locations, but that can also happen before the user ever types a postcode, and still preserve privacy and allow offline use. In this demo the list is trivially small and is loaded as part of the script on the main web page.

I’m just some person on the internet with almost zero clout, so I’m not really expecting any big corporation’s website to start using this any time soon. But if you happen to be someone who makes technical decisions for such a website, I would love to be able to say I’ve convinced you to switch to this approach.

I’ve only just finished making this work in my demo, so there’s some practical considerations that I still need to figure out for large scale deployments. If you have useful ideas or feedback regarding that, then please let me know by submitting an issue.

The code is open source and currently hosted on Codeberg. You can also find it on Github.

Closing thoughts

Before I go, I want to leave you with some thoughts about privacy and technology. Big tech companies that provide web based services have big incentives to sell your personal data. This isn’t something that is inherent in technology. I hope that what I’ve shown here has demonstrated that effectively.

Technology can be applied in ways that preserve privacy if the people creating that technology endeavour to make it that way. Big tech companies generally don’t do that.

I hope I’ve also demonstrated that it’s worth being frugal with energy and data. Spending that extra effort to minimise the size of a file means that the file can be delivered much quicker and with less energy. Spending the time to minimise the computation required to process it also reduces the energy used.

Sometimes it’s a small effect, but it could multiply up to something much bigger.

Maybe I’ve inspired some of you to apply a similar ethos to the way you write code. That’d be nice.

Part of a series of posts: Next in series >

Blog post

Why does my car think that 38 - 2 = 34?

Published: 2025-06-01

This blog post is also available in video form! Watch it on YouTube

I can't explain this bug. It makes no sense to me. 38 minus 2 is not 34. It is 36. Obviously!

Suppose I have a computer program which has one variable called A. The program waits for an input of either "up" or "down", and then adds two to A or subtracts two from A and uses that as the new value for A.

Let's say A starts at 20. I give it the "up" input, and now A is 22. I give it the "up" input again, and now A is 24. I give it the "up" input 8 more times, and A goes through 26, 28, 30, 32, 34, 36, 38, and ends up on 40. This is all fine.

But if I then started giving it the "down" input repeatedly from A=40, and the sequence of values of A started 40, 38, 34, then you'd be surprised. You'd be thinking "hmm, this program is clearly broken. It is faulty. There is a bug here!"

Suppose you keep testing the program as far as you are able to. You go up and down the full range of numbers that the program can handle. There's no other cases where it jumps by 4 instead of by 2. It's always a step of 2, unless you go down from 38, in which case it steps by 4 and lands on 34.

I know what you're thinking. You're thinking that surely nobody has ever written software that has this bug. How could anyone possibly put a bug like that in to such a simple program?

Surely this isn't a bug that exists in the wild.

Finding this bug in the wild

The last time I owned a car, it was because I got it for free from a friend of mine. He had crashed his Smart Roadster in to the back of another car, didn't want to repair it, and didn't really use it much any more anyway. So I got this heap of metal on wheels for no charge. The retractable roof no longer retracted, instead it just leaked. The CD player was faulty in various ways. Some parts fell of it sometimes. It was hopelessly impractical for a lot of tasks. But it was sometimes useful, and the engine ran perfectly fine, so I decided the squeeze the remaining life out of it. I did repair the bumper, get it past one MoT safety inspection, and make use of the car for a while after that, but strategically sold it to a car recycler just before the next MoT inspection was due.

(MoT stands for Ministry of Transport, a UK government agency that has since been renamed to the Department for Transport (DfT), but everyone still refers to the legally mandated annual vehicle safety inspections as "MoT tests")

A terrible old car (A red Smart Roadster with a smashed bumper and a filthy roof)

That car had a speed limiter feature. I used it every time I drove the car. It's really handy. Any time I see a speed limit sign, I set the car's speed limiter to that limit, and then I don't have to worry about how fast I'm going. The car won't let me break the speed limit.

The minimum speed setting is 20mph. So, you can use the control on the stalk to increase or decrease the speed limit. Each click "up" adds 2 to the limit, up to a maximum of 120 miles per hour. I never need to go beyond 70mph though, since that's the highest speed limit on UK roads. A click "down" normally subtracts 2 from the limit, down to a minimum of 20mph. However, as you're probably expecting from the intro, a click down from 38mph subtracts 4 from the limit, and puts you on 34mph.

Most of the UK speed limits are multiples of ten. During most of the city driving I do I will only encounter speed limits of 20mph and 30mph, but I do often also use 40mph roads, and then there's 50, 60, and 70mph roads when you get out of the city. Most of the time I encounter a change of speed limit, I need to do 5 clicks in some direction to get to the new speed limit. Most of the time I'm adding or subtracting 10.

Before I discovered this bug, when leaving a 40mph zone and entering a 30mph zone, I would do 5 "down" clicks. This always resulted in me ending up on 28mph. I would then be mildly confused by the slightly slower speed than I expected, look at the display, see that it said 28, and do one "up" click to correct it.

I thought this was no big deal, until I realised that I consistently have issues with going from 40mph to 30mph. At some point while I had the car parked on my driveway, I played with the controls and discovered that I was not imagining things. I was not just failing to use the controls correctly. It was not detecting more than one input for each click of the control. It consistently jumps from 38 to 34.

How do we explain this?

I'm the kind of person that really enjoys writing computer code. I started writing code as a hobby when I was very young, and spent my entire career working in tech writing code all day. I've spent a significant amount of my life writing code. I have never come across a bug like this before, and I have not yet encountered one since.

I don't have access to the source code for this system, and I decided not to extract the code from the car to reverse engineer the binary. As fun as that would be to do, it will be a lot of effort to disassemble the car to the point where I can even find the chip that the software for this is stored on. I didn't want to take my car apart that far just for this bug.

So, let's think of some hypothetical ways that this bug could happen. I'm going to use C code for demonstration purposes. Here's a really simple thing that the program could be doing:

int limit = 20;
int get_limit(){ return limit; }

// called on up click
void up(){
    limit += 2;
    if (limit > 120) limit = 120;
}

// called on down click
void down(){
    limit -= 2;
    if (limit < 20) limit = 20;
}

This code works perfectly. No issues. We have some really simple code here, and it works fine. So clearly we're missing something, because we don't have the buggy behaviour yet, which is what we expected.

This is the first thing that anyone would write if asked to implement this. So, given that it works just fine: how did this bug get in there? Who was it that got to this point and thought “I can do better than this” and proceeded to write some code that gets basic arithmetic so obviously wrong?

If I wanted to provide some explanation for this bug and did not care about how similar my example code is to the real code, I could modify the down function to look like this.

// called on down click
void down(){
    limit -= 2;
    if (limit == 36) limit = 34;
    if (limit < 20) limit = 20;
}

I add in an extra check that looks for the value 36, on the way down, and jumps to 34 instead.

This perfectly reproduces the behaviour that I've observed, but it is not at all satisfying as an explanation, because nobody would ever write that code. Any code that goes in to a car, and can interact with critical systems within the car, such as the accelerator, goes through a very strict process that aims to keep the quality of the code high.

I don't believe that source code like this would ever be allowed into a critical system on any car. The bug can't be as obvious as this. It must be something far more subtle.

So what is it? What is the subtle bug? Well, I have two ideas to explore, but I don't like either of them as a good explanation.

Bad explanation 1: Look up tables

Idea 1 is that they didn’t use arithmetic to determine the next value, but instead had a lookup table that was manually written and contained a mistake.

This one is more plausible than just having an extra check to deliberately skip 36, but I still don’t like it. It still feels unlikely.

Suppose for example that I still have my variable called “limit” and it still stores the limit in miles per hour. Now I have a lookup table that maps a speed limit value to the next value up, and another that maps a speed limit value to the next value down.

int limit = 20;
int get_limit(){ return limit; }

int uptable[] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    22,0,24,0,26,0,28,0,30,0,
    32,0,34,0,36,0,38,0,40,0,
    42,0,44,0,46,0,48,0,50,0,
    52,0,54,0,56,0,58,0,60,0,
    62,0,64,0,66,0,68,0,70,0,
    72,0,74,0,76,0,78,0,80,0,
    82,0,84,0,86,0,88,0,90,0,
    92,0,94,0,96,0,98,0,100,0,
    102,0,104,0,106,0,108,0,
    110,0,112,0,114,0,116,0,
    118,0,120,0,120
};

int downtable[] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    20,0,20,0,22,0,24,0,26,0,28,0,30,0,
    32,0,34,0,34,0,38,0,40,0,
    42,0,44,0,46,0,48,0,50,0,
    52,0,54,0,56,0,58,0,60,0,
    62,0,64,0,66,0,68,0,70,0,
    72,0,74,0,76,0,78,0,80,0,
    82,0,84,0,86,0,88,0,90,0,
    92,0,94,0,96,0,98,0,100,0,
    102,0,104,0,106,0,108,0,
    110,0,112,0,114,0,116,0,
    118,
};

void up(){ limit = uptable[limit]; }
void down(){ limit = downtable[limit]; }

Urgh! That looks awful! Each table needs to have a huge blank area at the start full of zeroes for all the values that are impossible to reach, and a placeholder value in between each number, since it always steps two at a time. I’ve just put 0 in these too.

Yes I could do some more address computations to avoid all those unused entries in the table, but that wouldn't be the worst sin of this code.

Why am I even suggesting this? Well it does have some interesting properties that might be what the car manufacturer wanted to have. The advantage of this approach is that each of the up and down functions is doing exactly the same thing every time, with no branching paths in either one. That is, there is no if statement any more. It always looks up the new value in the table and stores it.

You no longer need to test if you are at the end of the range. The lookup table for going up maps 120 mph to 120 mph, and the downwards one maps 20 mph to 20 mph. There’s no need for the checks at the extremes of the range any more, they are handled by the tables.

Why is this useful? Sometimes a predictable execution time is useful. Especially in cryptography. The only problem with this theory is that it makes no sense to save that tiny bit of time spent branching. There’s no doubt a whole bunch of other code running in between the button press and the table lookup anyway.

There’s no way this code is on the critical path. Especially when you consider that it also lets you hold down the button to skip through the steps repeatedly. That must require a whole bunch of logic and timing stuff. It’s not going to be a timing constraint.

I seriously doubt that’s the reason. I also can’t think of any better reason to do it like this, and that’s why I doubt that this is the case. It’s a little more satisfying than the very deliberate bug from earlier, because the bug is really subtle this time. You have to look carefully at the tables to see it, instead of just immediately seeing something suspicious. But I'm still not convinced

Bad explanation 2: Is it floats?

Idea 2 can be summarised as “some sequence of floating point rounding errors."

Okay, first of all. If you’re writing code for an embedded system, especially when it’s embedded in a car, you should really think carefully about if you really need floating point arithmetic before you actually use it.

Floating point rounding errors can cause nasty bugs. Embedded hardware often doesn’t even have floating point arithmetic units, and so it is implemented in software, which is much slower than hardware, and certainly much slower than integer arithmetic.

But let’s put that aside for a moment. Maybe they did use floating point. Maybe, because this is a German car, all of the software was written with the assumption that all the base units were in Kilometres, and then they added in support for places where the speeds and distances are measured in miles by having a conversion layer on top of the kilometres implementation.

Well, that raises some challenges, Suppose your underlying control software needs to have the speed limit specified in kilometers per hour and you don’t want to change that. You can’t just have the displayed number be converted to miles per hour, and leave the buttons to add and subtract 2 kph, because then you’d end up with an awful user experience far worse than this bug. Pressing up would add about 1.24 miles per hour. You need to also convert the up and down numbers.

So maybe you make the up and down buttons add and subtract about 3.22 kph, then you can keep the limit stored in kph, apply the translation only when you display the number, and the control system can stay the same. You’ll need to do some rounding to be sure everything works, but this could be okay.

Okay, but how much rounding is too much? Let’s try specifying everything to two decimal places, and rounding to the nearest integer whenever we display the limit. That works! How about we get even more approximate? Only one decimal place. That works too.

Okay how about everything is just the nearest integer, except for the conversion factor? That also works. You can be really approximate about this and it still works fine! It’s not a speed unit conversion problem.

But wait a minute, what’s going to happen if there is a rounding error? At these low numbers, the rounding errors are going to be incredibly small. We’re not even going to see an error big enough to cause a problem when rounding to the nearest integer. We’re not even seeing a scenario where we are off by one, how could this possibly lead to being off by two!?

Let’s be a little more systematic about this. If there is some rounding that leads to this problem, there must be a scale where one of the converted numbers rounds to 34, and the next one up rounds to 38. What would the step size need to be?

The lowest value that can round to 38 is 37.5. You can exactly represent 37.5 in a single precision float. The next float below that one would round down to 37. The greatest value that can round down to 34 is 34.99996185302734375, which is the next float value below 34.5, which would round to 35. The difference between these values, according to regular floating point arithmetic is precisely 3.000003814697265625, which is very slightly more than 3.

Well clearly that’s no use. If I was to use 3 as the step size, then I can get this sudden step from 38 to 34, but then if I go down again from there I get to 31, not 32. So certainly this isn’t what’s going on!

We need a step size that’s close to 2, and we need a rounding function that rounds to the nearest 2. We need it to round to correctly for all numbers in the range 20 to 120, except for the number one step below 38.

Turns out this is kinda possible! If you start at 20.82 and you make steps of 2.024, then by the time you get to the number that rounds to 34, you’re actually at about 34.988, and then you take one more step and you’re at about 37.012, and the closest multiple of 2 to that number is 38, so you’ve skipped over 36. The problem is that this happens in both directions. The real bug that I experienced only skipped 36 when heading down!

So you might be thinking that there’s some rounding on the stored value on each step, but then the bug would be inconsistent. In my experience it would always skip 36 on the way down regardless of what other up and down motion had happened before that. It would never skip 36 on the way up, even if I’d been up and down across that boundary many times. If it was an accumulation of rounding errors over time then I’d expect it to be less predictable than that.

I thought about doing an exhaustive search of all possible floating point rounding modes, all possible step sizes, and all possible conversion factors, to account for the underlying data maybe being in some strange units that’s neither mph nor kph. I even started to write some code for doing that, and then realised that the search space is way too big, and so I gave up.

And that’s where I’m at. I have no idea how to explain this bug. How could someone get this wrong? I don’t know.

If you are someone that worked on the speed limiter software for Smart cars in the early 2000s, and you know for sure why this bug happened, then please please please get in touch and tell me all about how that system works. I would love to know.

Sorry this rant doesn’t have a satisfying conclusion. I wish it did.

Blog post

Fitting a pride flag image in 241 bytes. A ZX Spectrum Sizecoding project.

Published: 2025-02-17

This blog post is also available as a video series! Watch it on YouTube: Part 1 | Part 2

I recently wrote some really tiny computer programs for an event called http://lovebyte.party/. It's an annual online-only demoparty.

In case you've not heard of a demoparty before: it's an event where programmers, musicians, and artists come together to show off things they've created.

Normally these creations are computer programs that render real-time animations, or visual effects, often accompanied by music or sound effects.

LoveByte specifically focuses on what you can do in that genre with a very limited program size. This is known as "size-coding" in the biz.

That appeals to me quite a bit, so I made a couple of entries. Here they are!

Progress pride flag rendered on a ZX Spectrum As the previous animation, but also with random sizes of bubbles

One of them is a rendering of the progress pride flag in 241 bytes, and the other is a rising bubble effect in 31 bytes. Both of these run on the Sinclair ZX Spectrum. The competitions are open to any platform, but I chose the ZX Spectrum.

There's nothing too special about them, but they're both good opportunities to talk about the ZX Spectrum and size-coding, two things I enjoy.

Progress Pride Flag in 241 bytes

This was my entry to the Tiny Executable Graphics Competition, where you need to create a program that produces a static image in 256 bytes or less.

At first this one might not seem impressive. It's just a static picture, right? Anyone could have drawn that!

Well, sure, but...

First of all, the size. The ZX Spectrum screen is 256 pixels wide, by 192 pixels tall, with a really thick border of a single colour all the way around. This flag image fills the whole frame buffer. If you stored this as a standard Windows Bitmap, with a colour depth of 8 bits per pixel, you'd need about 48kb of space just for the image data. The ZX Spectrum frame buffer is much smaller than that. There's only 48kb of RAM for the whole machine, so the ZX Spectrum plays some tricks to make the screen buffer smaller.

First of all, it only has 15 colours (well, technically 16, but bright black is the same as black). Furthermore, it only lets you have two distinct colours in each 8x8 cell of pixels, and you have to pick both of them from the "bright" colours, or both of them from the "dim" colours, you can't mix and match. So actually there's only 48 to 128 different colour combinations depending on how you feel about double-counting some of them.

The selection of colours available on the ZX Spectrum

The colours for a cell are stored in a byte known as the attribute byte. There is one attribute byte per cell. Unfortunately, that's not enough colours to make the progress pride flag. This is why I have to use dither patterns to simulate some of the colours that aren't directly available.

Examples of some dithered colour combinations

This works really well for the orange and purple stripes, and lets me get a nicer shade of blue for the blue stripe, but there isn't a good combination of colours for making a brown dither. I did the best I could, with a fairly sparse red dither on a black background. Each cell of 8 by 8 pixels is represented by one attribute byte for the colour combination and a 1 bit-per-pixel bitmap, so a cell only takes up 9 bytes in total. There's a grid of 32 by 24 of these cells, so the ZX Spectrum frame buffer format takes up about 7kb.

It's 6912 bytes, to be precise.

So if I stored this image as a raw ZX Spectrum frame, it would be 6912 bytes. The program that I wrote is only 241 bytes long, but generates the full 6912 bytes frame. That's a really good compression ratio. The program is about 3.5% of the size of the frame that it generates.

Let's visualise the drawing procedure with a split view of the frame buffer. I'll show the bitmap area with all attributes set the same way, and then show a pattern of dots with the attributes as they are in the buffer.D These two combine to make the full image. Here's what it looks like at the end:

The final render, and the raw bitmap and attribute visualisations

Let's have a look at how we got to that point. There's six steps to this drawing process, let's see them one by one

Step 1: Make it Yellow

The first step might appear strange at first. It clears the screen to a yellow colour, then it applies the dither pattern to the first eight lines of the screen. You can see the dither pattern in the bitmap, but the attributes are set so that every cell is yellow on yellow, so the screen still looks blank for now. If we look at the final image, it's actually only the orange, blue, and purple stripes that have this dither pattern on them. So why am I drawing the dither in so many places where I don't need it? And why am I not dithering some places that do need it? Well, that should become clear later on.

The screen turns yellow from top to bottom, left to right, one 8x8 pixel block at a time

The ZX Spectrum has some space in the RAM that is designated for custom characters that can be printed with the normal character printing routine found in the ROM. This dither pattern is just a custom character repeated over and over again. The code that puts it here is just a loop that prints that character 256 times.

The combination of the "load b" instruction and the "decrement and jump if not zero" instruction forms a very space-efficient loop. Only four bytes in total for the loop head and tail. The body is also fairly short. Only 3 bytes to load the A register with the number of the dither character, and then call the ROM's print char function. It might look like I've set the loop up to do zero iterations, but actually an initial loop counter of 0 means you'll get 256 iterations. That's the most we can do with a djnz loop, and it perfectly fills eight lines of the screen.

It took 8 bytes to clear the screen to yellow, so we've executed 15 bytes so far, and we have this.

Six coloured stripes are added from left to right, top to bottom

At this point, the particularly astute among you are wondering: "If this is the first thing the program did, then how is the custom character loaded already?".

An excellent question! I played a fun little trick that I will reveal later, when we get to the appropriate part of the program. I might be building that up a bit too much, it's kinda boring and obvious when you realise whats going on here, but I'm still gonna wait to explain it later.

Step 2: Adding Stripes

In this step, the attribute data for the thick horizontal stripes is added. There's a lot more going on in this step. It uses 43 bytes of program space to do it, and this includes a 6 byte array that contains attribute values in order. It does this one column at a time, starting at the 10th column and moving rightwards. There's an inner loop, which steps down in the Y direction, and an outer loop, that steps in the X direction. The inner loop steps to the next attribute value after every four steps with the current attribute.

Six coloured stripes are added from left to right, top to bottom

Now you can see the effect that is created by the dither pattern bitmap and the attribute data in combination. You can't see the dither pattern on the red stripe, because both the filled and unfilled pixels are set to display as red. The orange stripe has two different colours, yellow and red, and so the dither pattern is visible. The last three stripes don't yet look like the final image. The attributes are correct, but the bitmap data is not correct yet. That will come later.

Step 3: Chevrons

Step 3 is the one that takes up the most program space. It's 68 bytes in total. It uses the string printing function in the ROM to generate the stripes that are at a 45 degree angle. The string that it prints has control characters in it for changing the colour attributes while printing. The characters it is printing are a combination of built-in characters and custom characters. The space character, and the filled block character are both built in to the ROM. These two angled half-filled cells are custom characters, as is the dither pattern.

The chevrons are added, but the lower half of them appears to have each 8 pixel strip vertically mirrored

There is a function that prints this string 12 times in a row, advancing down and right by one space with each iteration.

Once the first 12 iterations are done, the program actually modifies itself, changing this decrement instruction to an increment instruction, so that the next time this loop runs, it will move down and to the left, instead of down and to the right.

It is still printing the exact same string though, and so it really doesn't look right at the moment, but that will be fixed later. It has also introduced some new problems. There's a couple of cells that now have incorrect data in them.o

Step 4: Oops, slightly undo step 3

Step 4 is purely here to fix up those issues introduced in step 3.

Unfortunately it takes another 32 bytes to do this. It re-prints the dither pattern over the cell that now has the wrong bitmap data, and it fixes the attribute data to get the right colours again. It also doesn't entirely cover the left edge of the stripes, so the left edge of the green stripe is visible slightly. It fixes this too.

A few small glitches are repaired

In the middle it did something that's not obvious yet. It stored a number in the space where the BASIC drawing and printing functions read attributes from. This will be important later.

Step 5: Making a Reflection

In step 5 we spend 36 bytes on the most magical part of this whole program. It takes the bitmap from the top half of the screen, and mirrors it to the bottom of the screen. This copies the dither pattern in to the lower two stripes, and fixes the angled stripes too. The result now looks really similar to the final image.

The theory of the mirror code is fairly simple, but the details are less simple. In theory, it just needs to copy lines of pixels from the top, to the bottom. It should be simple logic. It should just be a loop with 96 iterations, where each one copies one line from the top to the bottom. Unfortunately it's not quite that simple. It starts with a pointer to the start of the first line, and calculates a pointer to the start of the last line, then copies the bitmap data for that line in to place. This works fine. Then it moves down by one line, and does the same. Except, it skips 7 lines! This is because of the unusual order of the pixel data in the ZX Spectrum's frame buffer.

The top half of the bitmap is coped to the lower half of the screen, vertically mirrored

Mathematically, it's not a problem. The maths that calculates the offset from the end given the offset from the start is still correct, despite this strange ordering. It's still just a simple subtraction operation. So this isn't a problem, right? Well, the problem becomes obvious when you consider the middle. If there was no special handling of the middle, then we would end up copying some lines from the lower half of the screen in to the top half of the scree, which is clearly not helpful. The solution to this was to add in some logic that determines if the current offset is below the centre line of the screen. If it is then it will skip that line, and continue. This means that the loop actually needs to do 128 iterations. Even though there's only 96 lines to copy, the offset of the 96th line is 128 row-lengths past the first byte in the frame buffer. 32 lines get skipped.

Step 6: The Circle

This is where that mystery attribute value from before becomes useful. It was the right attribute value for the circle colour. This code uses a fairly sophisticated feature of the ZX Spectrum BASIC ROM to load some constant values in to the calculator stack, and then call the circle drawing routine, which uses the calculator stack values to determine the X and Y coordinates, and the radius of the circle to draw. The ZX Spectrum ROM calculator is a whole subject in itself, and not one that I'm going to get in to here. Think of it like a little DSL inside of the assembly language. It has its own op codes, which it interprets at run time in software. The only opcode that I use in this program is the one that stacks a constant value on the calculator stack.

A circle is drawn on the left side of the flag

This makes the circle drawing step really compact. Only 14 bytes to draw the circle.

The last two bytes of the program are simply a jump-to-self, so that the program never returns. After the end of the main code path, we find some additional data. First is the list of attribute values for the horizontal stripes, as we saw earlier, then the function for drawing the angled stripes, and the string value that it uses.

But when do the custom characters get loaded?

Well, those are what comes after everything else in the file. Right at the end.

The BASIC loader loads the program at a very specific location, just a little bit before the start of the default user defined character area in the RAM. The custom characters are loaded in to place before the program even starts, simply by carefully choosing where the program starts loading in to memory. This was the last optimisation that I made, since doing it requires knowing exactly how long the program is, and thus what address to start the program at.

Fortunately, the assembler that I used for this project has an assert command that I can use to cause an error if the character data ends up in the wrong place.

So that's it. In real time this process completes in about a second or two. with the slowest part being the circle drawing. But by capturing frames from the emulator much more frequently than the real hardware can display new frames, I'm able to make the super slow motion sequences from this video. I quite enjoy watching the image appear in slow motion.

Bubbles (31 bytes)

The second demo I want to talk about is quite different.

As the previous animation, but also with random sizes of bubbles

This was my entry for the 32 Byte Intro Competition. It's a pseudo-random stream of bubbles rising up the screen. So this one is about one eighth of the size of the flag, and includes animation!

This one doesn't do anything particularly surprising, but it's still interesting.

I could just walk through the program as it exists in its final form, and explain how it works, like I did for the pride flag demo. But to do that would mean skipping over some important details about the process I used to develop it. To give you an insight in to that process, I'll walk through how it happened. I can do this here because I can actually remember the whole process.

Starting by Experimenting

I deliberately set out to write a 32 byte demo, specifically for LoveByte. I didn't have too much of an idea for what I wanted to do, but I thought it might be fun to try and find a way to use the ZX Spectrum ROM's built in circle drawing function in a tiny demo. As we saw in the previous demo, the circle drawing function can be accessed fairly easily from a machine code program with not too many bytes of code.

The first thing that I did was write some code that would draw a circle somewhere on the screen, just to test things out.

A single circle drawn on to the screen

The ZX Spectrum ROM has been disassembled by various people over the years. And thanks to these efforts, it is well documented where all the functions are in the ROM.

The function uses parameters from the calculator stack. This time I used a slightly different approach to the pride flag demo. I knew I wanted to be able to move the circles around, so I didn't use hard-coded constants.

The circle function takes three values from the calculator stack. The first one is the radius of the circle. The second is the Y coordinate, and the third is the X coordinate. Of course, because this is a stack, we need to push these in the reverse order to the order they'll be used. Conveniently, there's a function that can put the current value of the A register on the calculator stack, and so I call that function several times, to put three values on to the calculator stack.

Okay, so I have a circle. Now I want it to move. I've played around with the ZX Spectrum enough to know that there's a ROM routine for scrolling the entire screen up by 8 rows. It's normally used by the print function to move all the text up the screen if there's more to print but you've reached the end of the screen.

It works just fine for non-text things too, since it just scrolls the whole bitmap without regard for what's in it.

So now I can draw a circle, move the screen up, and then draw another. It's a very simple animation, but it works.

Circles being drawn on the screen and then shifted up, creating a stack of circles

Making it interesting

Now I want this to be a little more interesting. I don't just want one stream of circles coming from one point and overlapping in the least exciting way possible. I want them to vary in size and displacement. I want the Y values to mostly remain the same, somewhere low down on the screen, but I want to vary the X value and the Radius. Ideally I also need them to vary in different ways, so the pattern isn't too predictable and boring.

The first thing I try is just adding a displacement with each iteration. I have to store and recall the value of the A register with each iteration just before pushing the X value. This means that the circle centres slowly drift to the right.

Circles being drawn on the screen and then shifted up, each circle is drawn slightly further to the right of the previous one, creating a slanted stack of circles

This works as expected, but introduces an issue. When the circles reach the end of the screen, it causes an error in the circle drawing routine. The only way to avoid this is to avoid letting the values get too big. If I apply a mask to the result of the addition, then I can effectively do modulo arithmetic on it, so that the X values cycle around this short loop.

As the previous animation, but once the bubbles get too close the right edge, they loop back to the left

This isn't very random, however. I want more randomness. I'm able to modify the step size, and this does change the pattern a little, but I want something more chaotic.

The change that adds chaos is fairly simple. I just modify the mask value so that sometimes the mask has the effect of decreasing the number instead of just having a modulo effect.

I also applied the same effect to the circle radius. I loaded the same value from the stack that I was using for the chaotic X motion, and applied another mask and an addition to enforce a minimum size.

As the previous animation, but the starting position of the bubbles appears more random

Now I have a bunch of parameters I can tweak. There's the minimum offset in X, the minimum circle radius, and the mask values for creating chaotic patterns in the X and radius. The mask values are more of an art than a science.

I think the values I chose create a nice pattern. There's two clear groupings that the animation switches between, but it takes long enough to repeat the exact same group of circles that it looks suitably random.

As the previous animation, but also with random sizes of bubbles

Sizecoding it

The file is 35 bytes at this point, so I had to do some optimisations.

The first thing I did was rearrange some things so that I don't have to initialise the A register at the start of the program. Instead, I pop some value from the stack, which now becomes a kind of random seed for the visualisation. This does technically cause the stack to be corrupt, but that doesn't actually matter, since this would only be a problem if I wanted to return control to the BASIC interpreter, which I don't.

This gets it down to 33 bytes, so I still need to save at least one byte.

I decided to see what happens when I removed the assignment to A after the first stack operation. The code that pushes the value of A on to the calculator stack actually consumes the value of A, and leaves something else in its place. I'm not sure what value exactly, but after trying it out, it appeared to do something that looked okay.

There's always a slight risk with an optimisation like that. The risk is that this value depends on something unpredictable, and you might get a very different effect to the one you intended.

Regardless, this works fine every time I've tested it, with a few different timings, so I was happy enough to submit this to the competition.

It was only after writing this that I realised "hey these look like bubbles", and so I decided that these are bubbles, hence the name of the demo.

Despite being some of the smallest demos I have submitted to any demo competition, these are the demos that I've enjoyed working on more than any other I've done previously.

Blog post

CFax: A fax service that compiles your C code

Published: 2024-07-27

This blog post is also available as a video series! Watch it on YouTube: Part 1 | Part 2

Yeah, it's as silly as it sounds.

What's that? "Why?"? ... don't ask such silly questions!

Let me explain...

What is this cursed device?

I made a fax service that compiles C code for you.

To use it, take a sheet of paper with some C code printed on it, and feed it in to your fax machine, then dial the number for your instance of Compiler Fax (AKA CFax). For me, this was a Raspberry Pi with a USB Fax Modem attached to the PBX in York Hackspace, so I just dialled "8". You should now be connected to the compiler fax service. Once you hear that the service has picked up and is making the tone to say it's ready to initiate a connection, press the send button on your fax machine to send the C code over to the compiler service.

What's fax? Fax, for all those lucky enough to have only ever used email. Is essentially like email before email was a big thing. It's essentially just a system for sending a bitmap image of a scanned document to a printer that will print it. This happens over a phone line, and is much slower than email. Normally you can hear a fax being sent.

Eventually, the C compiler service will have finished processing the document and is ready to fax back the result. It calls back on the number specified in the original fax, the fax machine answers, accepts the fax, and prints it out.

You're probably wondering what does CompilerFax actually look like? What is it, and how does it work? Can I make one for myself? Do I need a real phone line to be able to use it? What is the meaning of life? Why is the telephone number just "8"?

I also got some more questions in the YouTube comments for my demo video, I'll try to answer all these questions here.

Easy first question: what does it look like?

Here it is! It's a Raspberry Pi and a USB Fax Modem. Well, at the time of this photo it had two modems connected.

The CFax hardware. A Raspberry Pi in a black case with two USB Fax Modems attached

Yeah, that's all there is to it, that is all you need. This is the whole system. Well, I suppose you also need a phone line to connect it to, but that much should be obvious. Once you have this it's just a case of installing the right software. The source code for CompilerFax is on github, you can build yourself one of these if you want.

The Basics

The Raspberry Pi is running Raspbian. The default choice for a Raspberry Pi really. On top of that I have installed Hylafax. Hylafax is, according to the website, "an enterprise-class system for sending and receiving facsimiles…". I've found it to be a pain to configure, and so it certainly feels like enterprise class software.

Hylafax handles the connection to the fax modem, accepts calls and receives faxes in a receive queue, and whenever the line is not busy it attempts to transmit faxes from its outgoing fax queue. There's a program you can run to add a fax to the outgoing fax queue. So, to make the C compiler part of this work, all I had to do was write a program that takes faxes from the incoming fax queue, processes them, and generates a report for each one, which gets added to the outgoing fax queue with the appropriate destination phone number.

But how exactly does it process them? It needs to have a C source code file to be able to compile it, but all it has is a bitmap image of the received fax. Well, the problem of extracting text from images is a well studied one, and we have readily available applications for doing just that. Tesseract is one such application. It does Optical Character Recognition (OCR).

My CompilerFax program takes the incoming fax, does some transforms on it because for some reason Hylafax provides me with a squashed version of the fax, then crops off a bit of the top and bottom because fax machines often add headers and footers and we don't want the text in them to be in the OCR output. Then it feeds that resulting image into Tesseract, and gets a text file out.

Now, the user needs to make sure they put the return phone number in the program text somewhere. They can just add a comment with a line like this one. CompilerFax looks for this line to determine where to send the reply. If it can't find the line, then it's not able to reply, so it just ignores the fax and doesn't process it any further. If it does find it though, then it needs to compile and run the code, and generate a report to send back.

When it works, it looks like this!

An example C program printed on a sheet of A4 paper on the left, and the resulting output on the right, also printed on A4 paper. The program outputs "Hello World" ten times.

Can I break this?

This is the point at which lots of people say "woah, wait a minute, I just realised that this thing is going to run arbitrary C code sent to it by a random person with a fax machine. What if they send malicious code? An infinite loop? A fork bomb? What happens then!?".

Well, those sounded like fun, so I gave them a go…

Let's start with an infinite loop that just prints the same line over and over again.

CFax handles this just fine. If the report's too long then it just gets truncated to 10 pages.

Okay, let's up the ante. You wanted a fork bomb, let's try a fork bomb!

Kinda anticlimactic really, it just times out and does not reply. Fork bombs are no issue.

Clearly I put more thought into this than some people gave me credit for! I did make some mistakes though.

One thing I didn't think about at first was: what if you tell it to reply to its own phone number? Well, initially this wasn't a problem, because it only uses a single phone line, so it would never be able to call itself because the line would be busy, and it would give up after a few attempts. But I was planning to take this to EMF Camp and connect up two phone lines at once, so it probably could have dialled itself then. If it had done, then it would send the report to itself as a new fax, and if that report had the reply line in, which it likely would, then the next report would be the result of trying to compile the text of the report as C code. That would probably include the reply line, and thus it would send another fax, and then another, and another, and thus permanently have a fax circling around the incoming and outgoing fax queues. I added some logic to check if it's faxing itself, and then just not fax itself. This logic is not perfect, and is probably still exploitable on some phone systems where there's an optional prefix for the number, so watch out for that if you build one of these for yourself.

I also recently discovered a bug that means it fails to reply when it should. If you generate enough output text then you can cause a crash in the report generator code. It loads the whole output log into memory before it starts generating the report, and so if you generated enough output then it would run out of memory and crash before it completed. It did eventually recover and continue handling faxes after the crash, but it would cause a bit of a delay, and you'd never get the report for your program. I fixed this by limiting the log size to a sensible maximum.

How is this secure?

How did I make it safe to compile and run random code including fork bombs? Well, I used "prlimit", and a really powerful linux utility called "unshare". Unshare creates new kernel namespaces temporarily to run a given program. It can also change the root directory at the same time, with the chroot system call. Namespaces in linux are essentially separate contexts in which programs have access to a different set of resources. I used it to make sure that the compiler and the compiled program run without root access, without access to the network interfaces, without being able to communicate with other processes on the system, and they can only run inside a minimal Alpine root.

The Alpine root only has a few select packages from Alpine. It has a minimal base set of packages, plus GCC for compilation. That's it, nothing more.

The preparation of the report is done outside the sandbox by grabbing the output file from the sandbox. It also resets the sandbox in between runs. There's only one directory that is writeable in the sandbox, so a reset is as simple as deleting and recreating that directory.

So there's the whole software stack. Raspbian, Hylafax, Tesseract, a hint of ImageMagick, a little bit of Alpine, and a bunch of glue code that I wrote to join it all together and generate faxable compilation reports.

I was hoping for a real stress test at EMF Camp 2024, where there would be a telephone network to connect it to, and plenty of hackers to have a go at breaking it. Here's a picture of the advert that I got on the beam slides that show between talks. I actually mailed it to the beam team through sneakernet, the camp's volunteer postal service. They kindly photographed the poster and put it on the screens.

An advert for CFax, printed on paper, phorographed, and projected on to a large screen in a tent.

Unfortunately, it didn't get much of a stress test. Perhaps I need to make it more reliable for EMF Camp 2026? Then I'll get some takers!

More questions answered

Let's end on some quickfire questions and answers:

Q1: Do you need a real phone line to be able to use this? A: No! in fact, the only way to use my instance of it right now is to turn up at York Hackspace and use the internal phone system. There's an old PBX on the wall, and it's only connected up to local phones and fax machines, no external connections at the moment. If you have your own PBX then you can run this in your home too! If anyone knows of a cheap web host that also provides a phone number and fax modem connected to your machine, let me know, I might make a publicly accessible CompilerFax.

Q2: Why is the number just 8? A: Partly answered by the previous question, it's on a small private phone network in a hackspace. There's only 8 phone lines on it, so they're numbered 1 to 8. The fax machine I'm testing it with is on line 7.

Q3: What if you need more than one page to send all your code? A: Multipage faxes are not supported at the moment. Patches welcome!

Q4: Is the sandbox actually secure? A: I've done the best I can to secure it, but there might still be issues. Try and break it for yourself! The code is all on github.

Q5: Can you specify the compilation options? If so how? A: No, unfortunately. I could maybe add in a way to do this, perhaps a special comment at the top of the file. For now though it will always compile with this command: gcc -lm program.c -o program So it does link in the maths library, but that's it. Otherwise it needs to be a self-contained single-file program that can be compiled with the default options.

I hope that clears up all the questions people had, but please do feel free to ask more!