Given a transaction dict returned by btc_tx_deserialize, convert it back into a
    hex-encoded byte string.

    Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools)

def btc_tx_serialize(_txobj):
    """
    Given a transaction dict returned by btc_tx_deserialize, convert it back into a
    hex-encoded byte string.

    Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools)
    """
    
    # output buffer
    o = []
    txobj = None
    if encoding.json_is_base(_txobj, 16):
        # txobj is built from hex strings already.  deserialize them 
        txobj = encoding.json_changebase(_txobj, lambda x: binascii.unhexlify(x))
    else:
        txobj = copy.deepcopy(_txobj)

    # version
    o.append(encoding.encode(txobj["version"], 256, 4)[::-1])

    # do we have any witness scripts?
    have_witness = False
    for inp in txobj['ins']:
        if inp.has_key('witness_script') and len(inp['witness_script']) > 0:
            have_witness = True
            break

    if have_witness:
        # add segwit marker 
        o.append('\x00\x01')
    
    # number of inputs
    o.append(encoding.num_to_var_int(len(txobj["ins"])))

    # all inputs
    for inp in txobj["ins"]:
        # input tx hash
        o.append(inp["outpoint"]["hash"][::-1])

        # input tx outpoint
        o.append(encoding.encode(inp["outpoint"]["index"], 256, 4)[::-1])

        # input scriptsig
        script = inp.get('script')
        if not script:
            script = bytes()

        scriptsig = encoding.num_to_var_int(len(script)) + script
        o.append(scriptsig)

        # sequence
        o.append(encoding.encode(inp.get("sequence", UINT_MAX - 1), 256, 4)[::-1])

    # number of outputs
    o.append(encoding.num_to_var_int(len(txobj["outs"])))

    # all outputs
    for out in txobj["outs"]:
        # value
        o.append(encoding.encode(out["value"], 256, 8)[::-1])

        # scriptPubKey
        scriptpubkey = encoding.num_to_var_int(len(out['script'])) + out['script']
        o.append(scriptpubkey)

    # add witnesses 
    if have_witness:
        for inp in txobj['ins']:
            witness_script = inp.get('witness_script')
            if not witness_script:
                witness_script = '\x00'

            o.append(witness_script)

    # locktime
    o.append(encoding.encode(txobj["locktime"], 256, 4)[::-1])

    # full string
    ret = ''.join( encoding.json_changebase(o, lambda x: encoding.safe_hexlify(x)) )
    return ret