async def submit_batches(self, request):
        """Accepts a binary encoded BatchList and submits it to the validator.

        Request:
            body: octet-stream BatchList of one or more Batches
        Response:
            status:
                 - 202: Batches submitted and pending
            link: /batches or /batch_statuses link for submitted batches

        """
        timer_ctx = self._post_batches_total_time.time()
        self._post_batches_count.inc()

        # Parse request
        if request.headers['Content-Type'] != 'application/octet-stream':
            LOGGER.debug('Submission headers had wrong Content-Type: %s',
                         request.headers['Content-Type'])
            self._post_batches_error.inc()
            raise errors.SubmissionWrongContentType()

        body = await request.read()
        if not body:
            LOGGER.debug('Submission contained an empty body')
            self._post_batches_error.inc()
            raise errors.NoBatchesSubmitted()

        try:
            batch_list = BatchList()
            batch_list.ParseFromString(body)
        except DecodeError:
            LOGGER.debug('Submission body could not be decoded: %s', body)
            self._post_batches_error.inc()
            raise errors.BadProtobufSubmitted()

        # Query validator
        error_traps = [
            error_handlers.BatchInvalidTrap, error_handlers.BatchQueueFullTrap
        ]
        validator_query = client_batch_submit_pb2.ClientBatchSubmitRequest(
            batches=batch_list.batches)

        with self._post_batches_validator_time.time():
            await self._query_validator(
                Message.CLIENT_BATCH_SUBMIT_REQUEST,
                client_batch_submit_pb2.ClientBatchSubmitResponse,
                validator_query, error_traps)

        # Build response envelope
        id_string = ','.join(b.header_signature for b in batch_list.batches)

        status = 202
        link = self._build_url(request, path='/batch_statuses', id=id_string)

        retval = self._wrap_response(request,
                                     metadata={'link': link},
                                     status=status)

        timer_ctx.stop()
        return retval
Example #2
0
    async def _send_and_wait_for_commit(self, batch):
        # Send transaction to validator
        submit_request = client_batch_submit_pb2.ClientBatchSubmitRequest(
            batches=[batch])
        await self._connection.send(
            validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
            submit_request.SerializeToString())

        # Send status request to validator
        batch_id = batch.header_signature
        status_request = client_batch_submit_pb2.ClientBatchStatusRequest(
            batch_ids=[batch_id], wait=True)
        validator_response = await self._connection.send(
            validator_pb2.Message.CLIENT_BATCH_STATUS_REQUEST,
            status_request.SerializeToString())

        # Parse response
        status_response = client_batch_submit_pb2.ClientBatchStatusResponse()
        status_response.ParseFromString(validator_response.content)
        status = status_response.batch_statuses[0].status
        if status == client_batch_submit_pb2.ClientBatchStatus.INVALID:
            error = status_response.batch_statuses[0].invalid_transactions[0]
            raise ApiBadRequest(error.message)
        elif status == client_batch_submit_pb2.ClientBatchStatus.PENDING:
            raise ApiInternalError('Transaction submitted but timed out')
        elif status == client_batch_submit_pb2.ClientBatchStatus.UNKNOWN:
            raise ApiInternalError('Something went wrong. Try again later')
Example #3
0
    async def _send_and_wait_for_commit(self, batch):
        # Send transaction to validator
        submit_request = client_batch_submit_pb2.ClientBatchSubmitRequest(
            batches=[batch])
        res = await self._connection.send(
            validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
            submit_request.SerializeToString(), 500)

        submit_response = client_batch_submit_pb2.ClientBatchSubmitResponse()
        submit_response.ParseFromString(res.content)

        # Send status request to validator
        batch_id = batch.header_signature
        status_request = client_batch_submit_pb2.ClientBatchStatusRequest(
            batch_ids=[batch_id], wait=True, timeout=500)
        validator_response = await self._connection.send(
            validator_pb2.Message.CLIENT_BATCH_STATUS_REQUEST,
            status_request.SerializeToString(), 500)

        # Parse response
        status_response = client_batch_submit_pb2.ClientBatchStatusResponse()
        status_response.ParseFromString(validator_response.content)
        status = status_response.batch_statuses[0].status
        if status == client_batch_submit_pb2.ClientBatchStatus.INVALID \
                or status == client_batch_submit_pb2.ClientBatchStatus.PENDING \
                or status == client_batch_submit_pb2.ClientBatchStatus.UNKNOWN:
            return False

        return True
Example #4
0
async def send(conn, batch_list, timeout):
    batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest()
    batch_request.batches.extend(list(batch_list.batches))

    validator_response = await conn.send(
        validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
        batch_request.SerializeToString(),
        timeout,
    )

    client_response = client_batch_submit_pb2.ClientBatchSubmitResponse()
    client_response.ParseFromString(validator_response.content)

    if (client_response.status ==
            client_batch_submit_pb2.ClientBatchSubmitResponse.INTERNAL_ERROR):
        raise ApiInternalError("Internal Error")
    elif (client_response.status ==
          client_batch_submit_pb2.ClientBatchSubmitResponse.INVALID_BATCH):
        raise ApiBadRequest("Invalid Batch")
    elif (client_response.status ==
          client_batch_submit_pb2.ClientBatchSubmitResponse.QUEUE_FULL):
        raise ApiInternalError("Queue Full")

    status_request = client_batch_submit_pb2.ClientBatchStatusRequest()
    status_request.batch_ids.extend(
        list(b.header_signature for b in batch_list.batches))
    status_request.wait = True
    status_request.timeout = timeout

    validator_response = await conn.send(
        validator_pb2.Message.CLIENT_BATCH_STATUS_REQUEST,
        status_request.SerializeToString(),
        timeout,
    )

    status_response = client_batch_submit_pb2.ClientBatchStatusResponse()
    status_response.ParseFromString(validator_response.content)

    if status_response.status != client_batch_submit_pb2.ClientBatchStatusResponse.OK:
        raise ApiInternalError("Internal Error")

    resp = status_response.batch_statuses[0]

    if resp.status == client_batch_submit_pb2.ClientBatchStatus.COMMITTED:
        return resp
    elif resp.status == client_batch_submit_pb2.ClientBatchStatus.INVALID:
        raise ApiBadRequest("Bad Request: {}".format(
            resp.invalid_transactions[0].message))
    elif resp.status == client_batch_submit_pb2.ClientBatchStatus.PENDING:
        raise ApiInternalError(
            "Internal Error: Transaction submitted but timed out.")
    elif resp.status == client_batch_submit_pb2.ClientBatchStatus.UNKNOWN:
        raise ApiInternalError(
            "Internal Error: Something went wrong. Try again later.")
Example #5
0
    async def _make_token_transfer(self,request,address_from,address_to,num_bgt,coin_code='bgt'):
        """
        Make transfer from wallet to wallet
        """
        
        payload_bytes = cbor.dumps({
            'Verb'   : 'transfer',
            'Name'   : address_from,
            'to_addr': address_to,
            'num_bgt': num_bgt,
            'group_id' : coin_code
        })
        LOGGER.debug('BgxRouteHandler: _make_token_transfer make payload=%s',payload_bytes)
        in_address = make_smart_bgt_address(address_from)
        out_address = make_smart_bgt_address(address_to)
        inputs =[in_address, out_address]   
        outputs=[in_address, out_address]
        transaction = self._create_transaction(payload_bytes,inputs,outputs)
        batch = self._create_batch([transaction])
        batch_id = batch.header_signature #batch_list.batches[0].header_signature

        # Query validator
        error_traps = [error_handlers.BatchInvalidTrap,error_handlers.BatchQueueFullTrap]
        validator_query = client_batch_submit_pb2.ClientBatchSubmitRequest(batches=[batch])
        LOGGER.debug('BgxRouteHandler: _make_token_transfer send batch_id=%s',batch_id)

        with self._post_batches_validator_time.time():
            await self._query_validator(
                Message.CLIENT_BATCH_SUBMIT_REQUEST,
                client_batch_submit_pb2.ClientBatchSubmitResponse,
                validator_query,
                error_traps)

        # Build response envelope
        link = self._build_url(request, path='/batch_statuses', id=batch_id)
        return link
async def send(conn, timeout, batches):
    batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest()
    batch_request.batches.extend(batches)
    await conn.send(validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
                    batch_request.SerializeToString(), timeout)
Example #7
0
def main():
    #loop = zmq.asyncio.ZMQEventLoop()
    #asyncio.set_event_loop(loop)
    #loop = asyncio.get_event_loop()
    try:
        init_context_pkey_signer()
        #validator_conn = Connection(VALIDATOR_URL)

        batches, batch_id = create_account("SampleAccount",
                                           "Sample Description!!", 5)
        batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest()
        batch_request.batches.extend(batches)
        #loop.run_until_complete(validator_conn.send(
        #    validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
        #    batch_request.SerializeToString(),
        #    TIMEOUT))
        #loop.run_until_complete(createacctmsg)
        #messaging.send(
        #    validator_conn,
        #    TIMEOUT,
        #    batches)
        send_batch_request(batch_request.SerializeToString())
        #time.sleep(1)

        inp = input("Have you created all the user accounts (y/n): ")
        print(inp)

        rule_proto = rule_pb2.Rule(type=rule_pb2.Rule.RULE_UNSET)
        rule_proto.value = bytes([1])
        assetbatches, assetbatch_id = create_asset("SampleAsset",
                                                   "Sample Asset Desc", 2,
                                                   [rule_proto])
        asset_batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest(
        )
        asset_batch_request.batches.extend(assetbatches)
        #validator_conn.send(
        #    validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
        #    asset_batch_request.SerializeToString(),
        #    TIMEOUT)
        send_batch_request(asset_batch_request.SerializeToString())

        inp = input('Have you created all the assets (y/n): ')
        print(inp)

        apprbatches, apprbatch_id = approve_asset("SampleAsset", 1)
        appr_batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest()
        appr_batch_request.batches.extend(apprbatches)
        #validator_conn.send(
        #    validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
        #    appr_batch_request.SerializeToString(),
        #    TIMEOUT)
        send_batch_request(appr_batch_request.SerializeToString())
        inp = input('Have you approved all the steps (y/n): ')
        print(inp)

        closebatches, closebatch_id = close_asset("SampleAsset")
        close_batch_request = client_batch_submit_pb2.ClientBatchSubmitRequest(
        )
        close_batch_request.batches.extend(closebatches)
        #validator_conn.send(
        #    validator_pb2.Message.CLIENT_BATCH_SUBMIT_REQUEST,
        #    close_batch_request.SerializeToString(),
        #    TIMEOUT)
        send_batch_request(close_batch_request.SerializeToString())
        print('asset closed successfully.')

    except KeyboardInterrupt:
        print("Keyboard Interruption.")
        sys.exit(0)
    finally:
        print("Client Exited Successfully.")