Looking at the original BitTorrent client

I wanted to learn more about how the original BitTorrent client implemented “choking”, so I downloaded the source to the original Python-based BitTorrent client from SourceForge.

I was impressed, as always, by the brevity and clarity of Python. The original BitTorrent client sources are very easy to read. (Especially now that I understand the problem domain pretty well.) The code has a nice OO design, with a clear separation of responsibilities.

I was also impressed by the extensive use of unit tests. About half the code in the BitTorrent source is unit tests of the different classes, to make sure that the program behaves correctly. This is a really good idea when developing a peer-to-peer application. The synthetic tests let you test things like your end-of-torrent logic immediately, rather than by having to find an active torrent swarm and wait for a real-world torrent to complete.

When I get a chance I’m going to refactor the Taipei-Torrent code into smaller classes and add unit tests like the original BitTorrent client implementation has.

And come to think of it, why didn’t I check out the original BitTorrent client code sooner? It would have saved me some time and I’d probably have a better result. D’Oh! Oh well, live and learn!

Some details on Xbox Project Natal

From Scientific American: Binary Body Double: Microsoft Reveals the Science Behind Project Natal

Short summary: They used machine-learning algorithms and lots of training data to come up with an algorithm that converts moving images into moving joint skeletons.

Given the huge variation in human body shapes and clothing, it will be interesting to see how well this performs in practice.

I bet people will have a lot of fun aiming the Natal camera at random moving object to see what happens. I can already imagine the split-screen YouTube videos we’ll see of Natal recognizing pets, prerecorded videos of people, puppets and marionettes.

Oh, and of course, people will point Natal back at the TV screen and see if the video game character can control itself.

Great fun!

800 lines of code for a bencode serializer?!

Wow, my Taipei-Torrent post made it to Hacker News and reddit.com/r/programming. I’m thrilled!

One comment on Hacker News was “800 lines for a bencode serializer?! It only took me 50 lines of Smalltalk!” That was a good comment! I replied:

A go bencode serialization library could be smaller if it just serialized the bencode data to and from a generic dictionary container. I think another go BitTorrent client, gobit, takes this approach.

But it’s convenient to be able to serialize arbitrary application types. That makes the bencode library larger because of the need to use go’s reflection APIs to analyze and access the application types. Go’s reflection APIs are pretty verbose, which is why the line count is so high.

To make things even more complicated, the BitTorrent protocol has a funny “compute-the-sha1-of-the-info-dictionary” requirement that forces BitTorrent clients to parse that particular part of the BitTorrent protocol using a generic parser.

So in the end, the go bencode serializer supports both a generic dictionary parser and an application type parser, which makes it even larger.

In general, Taipei-Torrent was not written to minimize lines-of-code. (If anything, I was trying to maximize functionality per unit of coding time.) One example of not minimizing lines-of-code is that I used a verbose error handling idiom:

a, err := f()
if err != nil {
  return
}

There are alternative ways to handle errors in go. Some of the alternatives take fewer lines of code in some situations. The above idiom is my preference because it works correctly in all cases. But it has the drawback of adding 3 lines of code to every function call that might return an error.

The go authors are considering adding exceptions to the go language. If they do so it will probably dramatically improve the line count of Taipei-Torrent.

A Taipei-Torrent postmortem: Writing a BitTorrent client in Go

This is a BitTorrent client. There are many like it, but this one is mine.

-- the BitTorrent Implementer’s Creed

For fun I’ve started writing a command-line BitTorrent client in Google’s go programming language. The program, Taipei-Torrent , is about 70% done. It can successfully download a torrent, but there are still lots of edge cases to implement.

Go routines and channels are a good base for writing multithreaded network code. My design uses goroutines as follows:

  • a single main goroutine contains most of the BitTorrent client logic.
  • each BitTorrent peer is serviced by two goroutines: one to read data from the peer, the other to write data to the peer.
  • a goroutine is used to communicate with the tracker
  • some “time.Tick” goroutines are used to wake the main goroutine up periodically to perform housekeeping duties.

All the complicated data structures are owned by the main goroutine. The other goroutines just perform potentially blocking network I/O using channels, network connections, and []byte slices. For example, here’s a slightly simplified version of the goroutine that handles writing messages to a peer:

func (p *peerState) peerWriter(errorChan chan peerMessage,
  header []byte) {
  _, err := p.conn.Write(header)
  if err != nil {
    goto exit
  }
  for msg := range p.writeChan {
    err = writeNBOUint32(p.conn, uint32(len(msg)))
    if err != nil {
      goto exit
    }
    _, err = p.conn.Write(msg)
    if err != nil {
      goto exit
    }
  }
exit:
  errorChan <- peerMessage{p, nil}
}

Good things about the Go language and standard packages for this project:

  • Even without IDE support it is easy to refactor go code. This ease-of-refactoring makes it pleasant to develop a program incrementally.
  • Goroutines and channels make networking code easy to write.
  • The log.Stderr() function makes debugging-by-printf fairly painless.
  • Go maps serve as pretty good one-size-fits-all collection classes.
  • I received very fast responses from the go authors to my bug reports.
  • The standard go packages are reliable and easy to use. I used the xml, io, http, and net packages pretty extensively in this project. I also used the source of the json package as a base for the bencode package.
  • gofmt -w is a great way to keep my code formatted.
  • Named return values, that are initialized to zero, are very pleasant to use.
  • The code writing process was very smooth and stress free. I rarely had to stop and think about how to achieve what I wanted to do next. And I could often add the next feature with relatively little typing. The feeling was similar to how it feels when I write Python code, only with fewer type errors. :-)
  • With the exception of using the reflect package I never felt like I was fighting the language or the compiler.

Minor Problems:

  • It was a little tedious to write if err != nil {return} after every function call in order to handle errors.
  • The standard go http package is immature. It is missing some features required for real-world scenarios, especially in the client-side classes. In my case I needed to expose an internal func and modify the way a second internal func worked in order to implement a client for the UPnP protocol. The good news is that the http package is open source, and it was possible to copy and fork the http package to create my own version.

What wasted my time:

  • Several hours wasted debugging why deserializing into a copy of a variable (rather than a pointer to the original variable) had no effect on the value of the original variable. I notice that I often make mistakes like this in go, because go hides the difference between a pointer and a value more than C does. And there’re confusing differences in behavior between a struct (which you can pass by either value or reference) and an interface (which has reference semantics on its contents even though you pass the interface by value). When you are reading and reasoning about go code you must mentally keep track of whether a given type is a struct type or an interface type in order to know how it behaves.
  • Several hours wasted figuring out how to send and receive multicast UDP messages. This may be an OSX-specific bug, and it may already be fixed. I found the Wireshark packet sniffer very helpful in debugging this problem.
  • Several hours wasted with crashes and hangs related to running out of OS threads on OSX. This was due to my code instantiating time.Tick objects too frequently. (Each live time.Tick object consumes a hardware thread.)
  • Many hours spent trying to understand and use the reflect package. It is powerful, but subtle and mostly undocumented. Even now, some things remain a mystery to me, such as how to convert a []interface{} to an interface{} using reflection.

Project statistics:

  • Line count: Main program: 1500 lines, http package patches: 50 lines, UPnP support: 300 lines, bencode serialization package: 800 lines. Tests for bencode serialization: 300 lines
  • Executable size: 1.5 MB. Why so large? One reason is that go doesn’t use shared libraries, so everything is linked into one executable. Even so, 1.5 MB seems pretty large. Maybe go’s linker doesn’t strip unused code.
  • Development time: ~8 days so far, probably 11 days total.
  • The source is available under a BSD-style license at: github.com/jackpal/Taipei-Torrent

Edits since first post:

  • Added error reporting to code example.
  • Added a link to the source code.
  • Give more details about the line count. I had mistakenly included some test code in the lines-of-code for the main program.
  • Add a statistic about program size.

Objects vs. the L2 Cache

An excellent little performance optimization presentation that shows how important memory layout is for today’s processors:

Pitfalls of Object Oriented Programming

The beginning of the talk makes the observation that since C++ was started in 1979 the cost of accessing uncached main memory has ballooned from 1 cycle to 400 cycles.

The bulk of the presentation shows the optimization of a graphics hierarchy library, where switching from a traditional OO design to a structure-of-arrays design makes the code run 3 times faster. (Because of better cache access patterns.)

3D toolchain musings

I’m writing a skinning sample for a future Android SDK. This has prompted me to construct a toolchain to get skinned animated models into Android applications.

I’m really only just getting started, but so far I’m thinking along these lines:

Wings 3D -> Blender 2.5 -> FBX ASCII -> ad-hoc tool -> ad-hoc binary file -> ad-hoc loader.

For what it’s worth, right now Blender 2.5 doesn’t support FBX export, so I have to do Collada -> FBX Converter -> FBX. But Blender 2.5 support should be ready fairly soon.

You may wonder why I’m considering using the proprietary and undocumented FBX standard rather than the open source Collada standard. I’m doing it for the same reason so many other tool chains (e.g. Unity, XNA) do, namely that FBX is a simpler format that just seems to work more reliably when exchanging data between DCC applications.

Blender 2.5 alpha 0 is looking pretty good

The open-source Blender 3D DCC tool has long suffered from an ugly, non-standard, hard-to-learn UI. I’m very happy to see that the latest release, which just entered alpha status, has a much improved UI. It’s not quite Modo quality, but it’s starting to get into the same league as commercial DCC tools.

Prince of Persia Developer's blog

In the late 1980’s Jordan Mechner single-handedly designed and programmed the original Apple II version of Prince of Persia and several other groundbreaking games. He published his development journals and technical design documents on his web site.

The journals touch on:

  • The development of the stop-motion animation techniques used so effectively in PoP
  • The tension in Jordan’s life between his two callings: game development and feature film scriptwriting / directing.
  • The difficulties involved in developing and selling a new game idea.
  • A view into the late 80’s / early 90’s pre-web game development business.

Although many games are now written by large teams of people, in the end, a lot of the business, artistic, and technical issues Jordan writes about remain relevant. I highly recommend these journals for anyone interested in an inside view of game development. (Or anyone interested in trying to break into Hollywood. :-) )