Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created November 29, 2012 22:22
Show Gist options
  • Save zachallaun/4172300 to your computer and use it in GitHub Desktop.
Save zachallaun/4172300 to your computer and use it in GitHub Desktop.
HS Presentation 11/29/12

#| #| #| #| #|

Encoding Constrained Byte Arrays

(or Fun With Lisp)

#| #| #| #| #|

The BitTorrent Handshake

5 components:

  • a single byte protocol length
  • a variable byte protocol string
  • 8 reserved bytes (to indicate protocol changes)
  • a 20-byte info hash
  • a 20-byte peer id

Exactly what these are aren't important -- that they are constrained is.

#| #| #| #| #|

Somewhere in your code, you need to check that this is valid

If you don't, you run the risk of sending garbage.

#| #| #| #| #|

So, you could do this check with a bunch of if statements...

#| #| #| #| #|

Or, you could build a system for constraining byte arrays!

(bit-struct handshake
  [len :byte]
  [protocol :len/bytes]
  [reserved :8/bytes]
  [info-hash :20/bytes]
  [peer-id :20/bytes])

#| #| #| #| #|

And a function that encodes based on that spec...

(encode handshake 19 "BitTorrent protocol" (reserved-bytes) info-hash
peer-id)
;; => Returns a ByteArray if the data meets the constraints

(encode handshake 5 "BitTorrent protocol" (reserved-bytes) info-hash
peer-id)
;; => Or throws an exception if it doesn't!

#| #| #| #| #|

Oh, and encode knows how to convert all of these things, including strings, to bytes. :-)

#| #| #| #| #|

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment