Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Last active August 29, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlrobinson/8702161 to your computer and use it in GitHub Desktop.
Save tlrobinson/8702161 to your computer and use it in GitHub Desktop.
"loopInto" for Substack's "binary" parsing toolkit
block = ->
@word32lu("version").tap (vars) ->
throw new Error("version="+vars.version) if vars.version isnt 1
@buffer "previous", 32
@buffer "merkle", 32
@word32lu "timestamp"
@word32lu "difficulty"
@word32lu "nonce"
varInt @, "txCount"
loopInto @, "transactions", "txCount", ->
@word32lu "version"
@tap (vars) ->
throw new Error("txversion="+vars.version) if vars.version isnt 1
varInt @, "inputCount"
loopInto @, "inputs", "inputCount", ->
@buffer "txHash", 32
@word32lu "txIndex"
varInt @, "scriptLength"
@buffer "script", "scriptLength"
@word32lu "sequenceNumber"
varInt @, "outputCount"
loopInto @, "outputs", "outputCount", ->
@word64lu "value"
varInt @, "scriptLength"
@buffer "script", "scriptLength"
@word32lu("txLockTime")
varInt = (p, key) ->
p.word8lu key
p.tap (vars) ->
switch vars[key]
when 0xfd then p.word16lu key
when 0xfe then p.word32lu key
when 0xff then p.word64lu key
loopInto = (p, prop, countProp, callback) ->
count = 0
p.loop (end, vars) ->
return end() if count++ >= vars[countProp]
@into "#{prop}.#{count-1}", callback
p.tap (vars) ->
vars[prop].length = vars[countProp]
vars[prop] = Array::slice.call vars[prop]
delete vars[countProp]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment