serialize tx with segwit tx format
 https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki
485047
def serialize_witness_format
      buf = [version, MARKER, FLAG].pack('Vcc')
      buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
      buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
      buf << witness_payload << [lock_time].pack('V')
      buf
    end
633570
def btc_make_payment_script( address, segwit=None, **ignored ):
    
    
    if segwit is None:
        segwit = get_features('segwit')

    # is address bech32-encoded?
    witver, withash = segwit_addr_decode(address)
    if witver is not None and withash is not None:
        # bech32 segwit address
        if not segwit:
            raise ValueError("Segwit is disabled")

        if len(withash) == 20:
            # p2wpkh
            script_hex = '0014' + withash.encode('hex')
            return script_hex
            
        elif len(withash) == 32:
            # p2wsh
            script_hex = '0020' + withash.encode('hex')
            return script_hex

        else:
            raise ValueError("Unrecognized address '%s'" % address )

    else:
        # address is b58check-encoded
        vb = keylib.b58check.b58check_version_byte(address)
        if vb == version_byte:
            # p2pkh
            hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
            script = 'OP_DUP OP_HASH160 {} OP_EQUALVERIFY OP_CHECKSIG'.format(hash160)
            script_hex = btc_script_to_hex(script)
            return script_hex

        elif vb == multisig_version_byte:
            # p2sh
            hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
            script = 'OP_HASH160 {} OP_EQUAL'.format(hash160)
            script_hex = btc_script_to_hex(script)
            return script_hex

        else:
            raise ValueError("Unrecognized address '%s'" % address )
416438
def broadcast_tx(self, tx):
        
        url = self.base_url("txs/push")
        data = {"tx": tx.as_hex()}
        result = json.loads(urlopen(url, data=json.dumps(data)).read().decode("utf8"))
        return result
401167
def tx_for_tx_hash(self, tx_hash):
        ""
        url = self.base_url("get_tx", b2h_rev(tx_hash))
        r = json.loads(urlopen(url).read().decode("utf8"))
        tx = Tx.parse(io.BytesIO(h2b(r.get("data").get("tx_hex"))))
        return tx
876917
def btc_script_serialize(_script):
    
    script = _script
    if encoding.json_is_base(_script, 16):
        # hex-to-bin all hex strings in this script
        script = encoding.json_changebase(_script, lambda x: binascii.unhexlify(x))

    # encode each item and return the concatenated list
    return encoding.safe_hexlify( ''.join(map(_btc_script_serialize_unit, script)) )
728861
def broadcast_transaction(hex_tx, blockchain_client):
    
    if not isinstance(blockchain_client, ChainComClient):
        raise Exception('A ChainComClient object is required')

    auth = blockchain_client.auth
    if not auth or len(auth) != 2:
        raise Exception('ChainComClient object must have auth credentials.')

    url = CHAIN_API_BASE_URL + '/bitcoin/transactions/send'
    payload = json.dumps({ 'signed_hex': hex_tx })
    r = requests.post(url, data=payload, auth=auth)

    try:
        data = r.json()
    except ValueError, e:
        raise Exception('Received non-JSON from chain.com.')

    if 'transaction_hash' in data:
        reply = {}
        reply['tx_hash'] = data['transaction_hash']
        reply['success'] = True
        return reply
    else:
        raise Exception('Tx hash missing from chain.com response: ' + str(data) + '\noriginal: ' + str(payload))
1256139
def DeserializeTX(buffer):
        
        mstream = MemoryStream(buffer)
        reader = BinaryReader(mstream)

        tx = Transaction.DeserializeFrom(reader)

        return tx
1282026
def btc_tx_sign_multisig_segwit(tx, idx, prevout_amount, witness_script, private_keys, hashcode=SIGHASH_ALL, hashcodes=None, native=False):
    

    from .multisig import parse_multisig_redeemscript

    if hashcodes is None:
        hashcodes = [hashcode] * len(private_keys)

    txobj = btc_tx_deserialize(str(tx))
    privs = {}
    for pk in private_keys:
        pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()

        compressed_pubkey = keylib.key_formatting.compress(pubk)
        privs[compressed_pubkey] = pk

    m, public_keys = parse_multisig_redeemscript(witness_script)

    used_keys, sigs = [], []
    for i, public_key in enumerate(public_keys):
        if public_key not in privs:
            continue

        if len(used_keys) == m:
            break

        if public_key in used_keys:
            raise ValueError('Tried to reuse key in witness script: {}'.format(public_key))

        pk_str = privs[public_key]
        used_keys.append(public_key)

        sig = btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, witness_script, pk_str, hashcodes[i])
        sigs.append(sig)

        # print ''

    if len(used_keys) != m:
        raise ValueError('Missing private keys (used {}, required {})'.format(len(used_keys), m))
   
    if native: 
        # native p2wsh
        txobj['ins'][idx]['witness_script'] = btc_witness_script_serialize([None] + sigs + [witness_script]) 

        # print 'segwit multisig: native p2wsh: witness script {}'.format(txobj['ins'][idx]['witness_script'])

    else:
        # p2sh-p2wsh
        redeem_script = btc_make_p2sh_p2wsh_redeem_script(witness_script)
        txobj['ins'][idx]['script'] = redeem_script
        txobj['ins'][idx]['witness_script'] = btc_witness_script_serialize([None] + sigs + [witness_script]) 
        
        # print 'segwit multisig: p2sh p2wsh: witness script {}'.format(txobj['ins'][idx]['witness_script'])
        # print 'segwit multisig: p2sh p2wsh: redeem script {}'.format(txobj['ins'][idx]['script'])
    
    return btc_tx_serialize(txobj)
102068
def make_multisig_segwit_address_from_witness_script(script):
    
    script_hash = hashing.bin_sha256(script.decode('hex')).encode('hex')
    scriptsig_script = '0020' + script_hash
    addr = btc_make_p2sh_address(scriptsig_script)
    return addr
797099
def btc_script_hex_to_address( script_hex, segwit=None ):
    
    # TODO: make this support more than bitcoin-like scripts
    if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50:
        # p2pkh script
        hash160_bin = binascii.unhexlify(script_hex[6:-4])
        return bin_hash160_to_address(hash160_bin, version_byte=version_byte)

    elif script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
        # p2sh script
        hash160_bin = binascii.unhexlify(script_hex[4:-2])
        return bin_hash160_to_address(hash160_bin, version_byte=multisig_version_byte)

    elif script_hex.startswith('0014') and len(script_hex) == 44:
        # p2wpkh script (bech32 address)
        hash160_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(hash160_bin) 

    elif script_hex.startswith('0020') and len(script_hex) == 68:
        # p2wsh script (bech32 address)
        sha256_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(sha256_bin)

    return None
1313936
def _make_txn(signer, setting_key, payload):
    
    serialized_payload = payload.SerializeToString()
    header = TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name='sawtooth_settings',
        family_version='1.0',
        inputs=_config_inputs(setting_key),
        outputs=_config_outputs(setting_key),
        dependencies=[],
        payload_sha512=hashlib.sha512(serialized_payload).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex()
    ).SerializeToString()

    return Transaction(
        header=header,
        header_signature=signer.sign(header),
        payload=serialized_payload)
72504
def btc_tx_serialize(_txobj):
    
    
    # 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
712556
public function serialize(): void
    {
        $keysgroup = [];

        if (! isset($this->transaction['version']) || 1 === $this->transaction['version']) {
            foreach ($this->transaction['asset']['multisignature']['keysgroup'] as $key) {
                $keysgroup[] = '+' === substr($key, 0, 1)
                    ? substr($key, 1)
                    : $key;
            }
        } else {
            $keysgroup = $this->transaction['asset']['multisignature']['keysgroup'];
        }

        $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['min']);
        $this->buffer->writeUInt8(count($this->transaction['asset']['multisignature']['keysgroup']));
        $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['lifetime']);
        $this->buffer->writeHexBytes(implode('', $keysgroup));
    }
627527
def btc_make_p2wpkh_address( pubkey_hex ):
    
    pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
    hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
    return segwit_addr_encode(hash160_bin)
203102
def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver):
    
    witprog_bytes = [ord(c) for c in witprog_bin]
    ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5))
    assert segwit_addr_decode(hrp, ret) is not (None, None)
    return ret
588021
def segwit_addr_decode(addr, hrp=bech32_prefix):
    
    hrpgot, data = bech32_decode(addr)
    if hrpgot != hrp:
        return (None, None)
    decoded = convertbits(data[1:], 5, 8, False)
    if decoded is None or len(decoded) < 2 or len(decoded) > 40:
        return (None, None)
    if data[0] > 16:
        return (None, None)
    if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
        return (None, None)
    return (data[0], ''.join([chr(x) for x in decoded]))
1096272
def serializeTo(io)
      raise "PeerId is not set" if ! @peerId
      raise "InfoHash is not set" if ! @infoHash
      result = [ProtocolName.length].pack("C")
      result << ProtocolName
      result << [0,0,0,0,0,0x10,0,0].pack("C8") # Reserved. 0x10 means we support extensions (BEP 10).
      result << @infoHash
      result << @peerId
      
      io.write result
    end