Validate the transaction ID of a transaction

            Args:
                tx_body (dict): The Transaction to be transformed.
767737
def validate_id(tx_body):
        
        # NOTE: Remove reference to avoid side effects
        # tx_body = deepcopy(tx_body)
        tx_body = rapidjson.loads(rapidjson.dumps(tx_body))

        try:
            proposed_tx_id = tx_body['id']
        except KeyError:
            raise InvalidHash('No transaction id found!')

        tx_body['id'] = None

        tx_body_serialized = Transaction._to_str(tx_body)
        valid_tx_id = Transaction._to_hash(tx_body_serialized)

        if proposed_tx_id != valid_tx_id:
            err_msg = ("The transaction's id '{}' isn't equal to "
                       "the hash of its body, i.e. it's not valid.")
            raise InvalidHash(err_msg.format(proposed_tx_id))
1033168
def validate_schema(cls, tx):
        
        _validate_schema(TX_SCHEMA_COMMON, tx)
        _validate_schema(TX_SCHEMA_CREATE, tx)
        if cls.TX_SCHEMA_CUSTOM:
            _validate_schema(cls.TX_SCHEMA_CUSTOM, tx)
1196696
def parse_transaction_id(self, data):
        ""
        if data[0] == TDS_ERROR_TOKEN:
            raise self.parse_error('begin()', data)
        t, data = _parse_byte(data)
        assert t == TDS_ENVCHANGE_TOKEN
        _, data = _parse_int(data, 2)   # packet length
        e, data = _parse_byte(data)
        assert e == TDS_ENV_BEGINTRANS
        ln, data = _parse_byte(data)
        assert ln == 8                  # transaction id length
        return data[:ln], data[ln:]
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))
112902
def send_raw_transaction(self, tx: Transaction, is_full: bool = False) -> str:
        
        tx_data = tx.serialize(is_hex=True)
        payload = self.generate_json_rpc_payload(RpcMethod.SEND_TRANSACTION, [tx_data])
        response = self.__post(self.__url, payload)
        if is_full:
            return response
        return response['result']
776037
def broadcast_transaction(hex_tx, blockchain_client):
    
    if not isinstance(blockchain_client, BlockcypherClient):
        raise Exception('A BlockcypherClient object is required')

    url = '%s/txs/push' % (BLOCKCYPHER_BASE_URL)
    payload = json.dumps({'tx': hex_tx})
    r = requests.post(url, data=payload)

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

    if 'tx' in data:
        reply = {}
        reply['tx_hash'] = data['tx']['hash']
        reply['success'] = True
        return reply
    else:
        err_str = 'Tx hash missing from blockcypher response: ' + str(data)
        raise Exception(err_str)
1232526
def issue(self, chain):
        

        blockchain_bytes = self.certificate_batch_handler.prepare_batch()

        for attempt_number in range(0, self.max_retry):
            try:
                txid = self.transaction_handler.issue_transaction(blockchain_bytes)
                self.certificate_batch_handler.finish_batch(txid, chain)
                logging.info('Broadcast transaction with txid %s', txid)
                return txid
            except BroadcastError:
                logging.warning(
                    'Failed broadcast reattempts. Trying to recreate transaction. This is attempt number %d',
                    attempt_number)
        logging.error('All attempts to broadcast failed. Try rerunning issuer.')
        raise BroadcastError('All attempts to broadcast failed. Try rerunning issuer.')
182285
def transaction_type(self, value):
        """"""
        if value is not None:
            if value not in self.ALLOWED_TRANSACTION_TYPES:
                raise AttributeError('%s transaction_type element must be one of %s not %s' % (
                    self.__class__.__name__, ','.join(self.ALLOWED_TRANSACTION_TYPES), value,))
        self._transaction_type = value
974581
def _txn_is_in_valid_batch(self, txn_id):
        

        batch = self._batches_by_txn_id[txn_id]

        # Return whether every transaction in the batch with a
        # transaction result is valid
        return all(
            self._txn_results[sig].is_valid
            for sig in set(self._txn_results).intersection(
                (txn.header_signature for txn in batch.transactions)))
1353251
def _handle_response(self, transaction):
        
        code = transaction.response.code
        utils.check_code(code)
        """
        VALID response:
        change the current cache value by switching the option set with the one provided
        also resets the timestamp
        if the request etag is different from the response, send the cached response
        """
        if code == Codes.VALID.number:
            logger.debug("received VALID")
            self.cache.validate(transaction.request, transaction.response)
            if transaction.request.etag != transaction.response.etag:
                element = self.cache.search_response(transaction.request)
                transaction.response = element.cached_response
            return transaction

        """
        CHANGED, CREATED or DELETED response:
        mark the requested resource as not fresh
        """
        if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number:
            target = self.cache.search_related(transaction.request)
            if target is not None:
                for element in target:
                    self.cache.mark(element)
            return transaction

        """
        any other response code can be cached normally
        """
        self.cache.cache_add(transaction.request, transaction.response)
        return transaction
480786
def get_transaction_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict:
        
        payload = self.generate_json_rpc_payload(RpcMethod.GET_TRANSACTION, [tx_hash, 1])
        response = self.__post(self.__url, payload)
        if is_full:
            return response
        return response['result']
744478
def validate(self, bigchain, current_transactions=[]):
        

        current_validators = self.get_validators(bigchain)

        super(ValidatorElection, self).validate(bigchain, current_transactions=current_transactions)

        # NOTE: change more than 1/3 of the current power is not allowed
        if self.asset['data']['power'] >= (1/3)*sum(current_validators.values()):
            raise InvalidPowerChange('`power` change must be less than 1/3 of total power')

        return self
665503
def handle_get_txn_req(self, request: Request, frm: str):
        
        ledger_id = request.operation.get(f.LEDGER_ID.nm, DOMAIN_LEDGER_ID)
        if ledger_id not in self.ledger_to_req_handler:
            self.send_nack_to_client((request.identifier, request.reqId),
                                     'Invalid ledger id {}'.format(ledger_id),
                                     frm)
            return

        seq_no = request.operation.get(DATA)
        self.send_ack_to_client((request.identifier, request.reqId), frm)
        ledger = self.getLedger(ledger_id)

        try:
            txn = self.getReplyFromLedger(ledger, seq_no)
        except KeyError:
            txn = None

        if txn is None:
            logger.debug(
                "{} can not handle GET_TXN request: ledger doesn't "
                "have txn with seqNo={}".format(self, str(seq_no)))

        result = {
            f.IDENTIFIER.nm: request.identifier,
            f.REQ_ID.nm: request.reqId,
            TXN_TYPE: request.operation[TXN_TYPE],
            DATA: None
        }

        if txn:
            result[DATA] = txn.result
            result[f.SEQ_NO.nm] = get_seq_no(txn.result)

        self.transmitToClient(Reply(result), frm)
134853
def to_dict(self):
        
        if self.txid is None and self.output is None:
            return None
        else:
            return {
                'transaction_id': self.txid,
                'output_index': self.output,
            }
662091
function getId (transaction) {
	var hash = crypto.createHash('sha256').update(getBytes(transaction).toString('hex'), 'hex').digest();
	var temp = new Buffer(8);
	for (var i = 0; i < 8; i++) {
		temp[i] = hash[7 - i];
	}

	var id = bignum.fromBuffer(temp).toString();
	return id;
}
697193
def verify_eth_transaction(signed_hextx, eth_data_field):
    
    logging.info('verifying ethDataField value for transaction')
    ethdata_hash = []
    for s in signed_hextx.split('80a0'):
        ethdata_hash.append(s)
    ethdata_hash = ethdata_hash[1][:64]
    result = (eth_data_field == ethdata_hash)
    if not result:
        error_message = 'There was a problem verifying the transaction'
        raise UnverifiedTransactionError(error_message)
    logging.info('verified ethDataField')
283497
def check_tx(tx, state)
      # Basic checks that don't depend on any context
      if tx.inputs.empty?
        return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vin-empty')
      end

      if tx.outputs.empty?
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-empty')
      end

      # Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
      if tx.serialize_old_format.bytesize * Bitcoin::WITNESS_SCALE_FACTOR > Bitcoin::MAX_BLOCK_WEIGHT
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-oversize')
      end

      # Check for negative or overflow output values
      amount = 0
      tx.outputs.each do |o|
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-negative') if o.value < 0
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < o.value
        amount += o.value
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < amount
      end

      # Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
      out_points = tx.inputs.map{|i|i.out_point.to_payload}
      unless out_points.size == out_points.uniq.size
        return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-inputs-duplicate')
      end

      if tx.coinbase_tx?
        if tx.inputs[0].script_sig.size < 2 || tx.inputs[0].script_sig.size > 100
          return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-cb-length')
        end
      else
        tx.inputs.each do |i|
          if i.out_point.nil? || !i.out_point.valid?
            return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-prevout-null')
          end
        end
      end
      true
    end