Deserialize according to <a href="https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki">BIP144</a> or
the <a href="https://en.bitcoin.it/wiki/Protocol_documentation#tx">classic format</a>, depending on if the
transaction is segwit or not.
554378
@Override
    protected void parse() throws ProtocolException {
        cursor = offset;
        optimalEncodingMessageSize = 4;

        // version
        version = readUint32();
        // peek at marker
        byte marker = payload[cursor];
        boolean useSegwit = marker == 0;
        // marker, flag
        if (useSegwit) {
            readBytes(2);
            optimalEncodingMessageSize += 2;
        }
        // txin_count, txins
        parseInputs();
        // txout_count, txouts
        parseOutputs();
        // script_witnesses
        if (useSegwit)
            parseWitnesses();
        // lock_time
        lockTime = readUint32();
        optimalEncodingMessageSize += 4;

        length = cursor - offset;
    }
518214
@Override
    public Message deserialize(ByteBuffer in) throws ProtocolException, IOException {
        // A Bitcoin protocol message has the following format.
        //
        //   - 4 byte magic number: 0xfabfb5da for the testnet or
        //                          0xf9beb4d9 for production
        //   - 12 byte command in ASCII
        //   - 4 byte payload size
        //   - 4 byte checksum
        //   - Payload data
        //
        // The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't
        // present for all messages, notably, the first one on a connection.
        //
        // Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because
        // sometimes it sends us stuff that isn't part of any message.
        seekPastMagicBytes(in);
        BitcoinPacketHeader header = new BitcoinPacketHeader(in);
        // Now try to read the whole message.
        return deserializePayload(header, in);
    }
5793
def decodetx(tx_hex, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert is_valid_coin_symbol(coin_symbol)
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, **dict(txs='decode'))

    params = {'token': api_key}
    data = {
        'tx': tx_hex,
        'token': api_key,
    }

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
898245
def Deserialize(self, reader):
        
        self.PrevHash = reader.ReadUInt256()
        self.PrevIndex = reader.ReadUInt16()
316442
@Override
    public byte[] bitcoinSerialize() {
        // we have completely cached byte array.
        if (headerBytesValid && transactionBytesValid) {
            Preconditions.checkNotNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
            if (length == payload.length) {
                return payload;
            } else {
                // byte array is offset so copy out the correct range.
                byte[] buf = new byte[length];
                System.arraycopy(payload, offset, buf, 0, length);
                return buf;
            }
        }

        // At least one of the two cacheable components is invalid
        // so fall back to stream write since we can't be sure of the length.
        ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength() : length);
        try {
            writeHeader(stream);
            writeTransactions(stream);
        } catch (IOException e) {
            // Cannot happen, we are serializing to a memory stream.
        }
        return stream.toByteArray();
    }
469441
def from_signed_raw(cls: Type[TransactionType], raw: str) -> TransactionType:
        
        lines = raw.splitlines(True)
        n = 0

        version = int(Transaction.parse_field("Version", lines[n]))
        n += 1

        Transaction.parse_field("Type", lines[n])
        n += 1

        currency = Transaction.parse_field("Currency", lines[n])
        n += 1

        blockstamp = None  # type: Optional[BlockUID]
        if version >= 3:
            blockstamp = BlockUID.from_str(Transaction.parse_field("Blockstamp", lines[n]))
            n += 1

        locktime = Transaction.parse_field("Locktime", lines[n])
        n += 1

        issuers = []
        inputs = []
        unlocks = []
        outputs = []
        signatures = []

        if Transaction.re_issuers.match(lines[n]):
            n += 1
            while Transaction.re_inputs.match(lines[n]) is None:
                issuer = Transaction.parse_field("Pubkey", lines[n])
                issuers.append(issuer)
                n += 1

        if Transaction.re_inputs.match(lines[n]):
            n += 1
            while Transaction.re_unlocks.match(lines[n]) is None:
                input_source = InputSource.from_inline(version, lines[n])
                inputs.append(input_source)
                n += 1

        if Transaction.re_unlocks.match(lines[n]):
            n += 1
            while Transaction.re_outputs.match(lines[n]) is None:
                unlock = Unlock.from_inline(lines[n])
                unlocks.append(unlock)
                n += 1

        if Transaction.re_outputs.match(lines[n]) is not None:
            n += 1
            while not Transaction.re_comment.match(lines[n]):
                _output = OutputSource.from_inline(lines[n])
                outputs.append(_output)
                n += 1

        comment = Transaction.parse_field("Comment", lines[n])
        n += 1

        if Transaction.re_signature.match(lines[n]) is not None:
            while n < len(lines):
                sign = Transaction.parse_field("Signature", lines[n])
                signatures.append(sign)
                n += 1

        return cls(version, currency, blockstamp, locktime, issuers, inputs, unlocks, outputs,
                   comment, signatures)
64552
def DeserializeForImport(self, reader):
        
        super(Block, self).Deserialize(reader)

        self.Transactions = []
        transaction_length = reader.ReadVarInt()

        for i in range(0, transaction_length):
            tx = Transaction.DeserializeFrom(reader)
            self.Transactions.append(tx)

        if len(self.Transactions) < 1:
            raise Exception('Invalid format %s ' % self.Index)
773445
def deserialize_bitarray(ser):
    # type: (str) -> bitarray
    
    ba = bitarray()
    ba.frombytes(base64.b64decode(ser.encode(encoding='UTF-8', errors='strict')))
    return ba
737972
def _deserialize(self, value, attr, data):
        """"""
        token_builder = URLSafeTimedSerializer(
            current_app.config['SECRET_KEY'],
            salt=data['verb'],
        )
        result = token_builder.loads(value, max_age=current_app.config[
            'OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME'])
        result['token'] = value
        result['kwargs'] = self.root.load(result['kwargs'], partial=True).data
        return result
1005988
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode):
    
    # always compressed
    if len(privkey_str) == 64:
        privkey_str += '01'

    pk = ecdsalib.ecdsa_private_key(str(privkey_str))
    pubk = pk.public_key()
    
    priv = pk.to_hex()

    # must always be compressed
    pub = keylib.key_formatting.compress(pubk.to_hex())
    sighash = btc_tx_sighash_segwit(tx, idx, prevout_amount, prevout_script, hashcode=hashcode)
    
    # sign using uncompressed private key
    # pk_uncompressed_hex, pubk_uncompressed_hex = ecdsalib.get_uncompressed_private_and_public_keys(priv)
    sigb64 = ecdsalib.sign_digest( sighash, priv )

    # sanity check 
    # assert ecdsalib.verify_digest( txhash, pubk_uncompressed_hex, sigb64 )

    sig_r, sig_s = ecdsalib.decode_signature(sigb64)
    sig_bin = btc_tx_der_encode_signature(sig_r, sig_s)
    sig = sig_bin.encode('hex') + encoding.encode(hashcode, 16, 2)

    # print 'segwit signature: {}'.format(sig)
    return sig
1256139
def DeserializeTX(buffer):
        
        mstream = MemoryStream(buffer)
        reader = BinaryReader(mstream)

        tx = Transaction.DeserializeFrom(reader)

        return tx
556733
def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain='bitcoin', **blockchain_opts):
    
    if blockchain == 'bitcoin':
        return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts)
    else:
        raise ValueError('Unknown blockchain "{}"'.format(blockchain))
255118
def tx_serialization_order(provider: Provider, blockhash: str, txid: str) -> int:
    ''''''

    return provider.getblock(blockhash)["tx"].index(txid)
710472
def parse_bewit(bewit):
    
    decoded_bewit = b64decode(bewit).decode('ascii')
    bewit_parts = decoded_bewit.split("\\")
    if len(bewit_parts) != 4:
        raise InvalidBewit('Expected 4 parts to bewit: %s' % decoded_bewit)
    return bewittuple(*bewit_parts)
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
303733
def DeserializeUnsignedWithoutType(self, reader):
        
        self.Version = reader.ReadByte()
        self.DeserializeExclusiveData(reader)
        self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute',
                                                       max=self.MAX_TX_ATTRIBUTES)
        self.inputs = reader.ReadSerializableArray('neo.Core.CoinReference.CoinReference')
        self.outputs = reader.ReadSerializableArray('neo.Core.TX.Transaction.TransactionOutput')
211587
def DeserializeExclusiveData(self, reader):
        
        self.Type = TransactionType.StateTransaction

        self.Descriptors = reader.ReadSerializableArray('neo.Core.State.StateDescriptor.StateDescriptor')