Exemplo n.º 1
0
def _get_state_data(names, context):
    LOGGER.debug("SMART_BGT>processor>handler>_get_state_data"
                 "\nnames=%s\ncontext=%s",
                 names, context)

    alist = []
    for name in names:
        address = make_smart_bgt_address(name)
        alist.append(address)
    state_entries = context.get_state(alist)

    LOGGER.debug('_get_state_data state_entries=%s', state_entries)
    try:
        states = {}
        for entry in state_entries:
            state = cbor.loads(entry.data)
            LOGGER.debug('_get_state_data state=(%s)', state)
            for key, val in state.items():
                LOGGER.debug('_get_state_data add=%s', key)
                states[key] = val
        return states
    except IndexError:
        return {}
    except:
        LOGGER.debug('_get_state_data: Failed to load state data')
        raise InvalidTransaction('Failed to load state data')
Exemplo n.º 2
0
def create_smart_bgt_transaction(verb, name, value, signer):
    payload = SmartBgtPayload(
        verb=verb, name=name, value=value)

    # The prefix should eventually be looked up from the
    # validator's namespace registry.
    addr = make_smart_bgt_address(name)

    header = transaction_pb2.TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name=FAMILY_NAME,
        family_version=FAMILY_VER,
        inputs=[addr],
        outputs=[addr],
        dependencies=[],
        payload_sha512=payload.sha512(),
        batcher_public_key=signer.get_public_key().as_hex(),
        nonce=hex(random.randint(0, 2**64)))

    header_bytes = header.SerializeToString()

    signature = signer.sign(header_bytes)

    transaction = transaction_pb2.Transaction(
        header=header_bytes,
        payload=payload.to_cbor(),
        header_signature=signature)

    return transaction
    def create_set_request(self, name, value):
        address = make_smart_bgt_address(name)

        if value is not None:
            data = self._dumps({name: value})
        else:
            data = None

        return self._factory.create_set_request({address: data})
Exemplo n.º 4
0
def _set_state_data(state, context):
    new_states = {}
    for key, val in state.items():
        LOGGER.debug('_set_state_data  [%s]=%s', key, val)
        address = make_smart_bgt_address(key)
        encoded = cbor.dumps({key: val})
        new_states[address] = encoded

    addresses = context.set_state(new_states)

    if not addresses:
        LOGGER.debug('_set_state_data  State error')
        raise InternalError('State error')
    LOGGER.debug('_set_state_data  DONE address=%s', address)
Exemplo n.º 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
Exemplo n.º 6
0
def create_smart_bgt_transaction(verb, name, value, deps, signer):
    """Creates a signed smart bgt transaction.

    Args:
        verb (str): the action the transaction takes, either 'set', 'inc',
            or 'dec'
        name (str): the variable name which is altered by verb and value
        value (int): the amount to set, increment, or decrement
        deps ([str]): a list of transaction header_signatures which are
            required dependencies which must be processed prior to
            processing this transaction
        signer (:obj:`Signer`): the cryptographic signer for signing the
            transaction

    Returns:
        transaction (transaction_pb2.Transaction): the signed bgt
            transaction
    """
    payload = SmartBgtPayload(
        verb=verb, name=name, value=value)

    # The prefix should eventually be looked up from the
    # validator's namespace registry.
    addr = make_smart_bgt_address(name)

    header = transaction_pb2.TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name=FAMILY_NAME,
        family_version=FAMILY_VER,
        inputs=[addr],
        outputs=[addr],
        dependencies=deps,
        payload_sha512=payload.sha512(),
        batcher_public_key=signer.get_public_key().as_hex(),
        nonce=hex(random.randint(0, 2**64)))

    header_bytes = header.SerializeToString()

    signature = signer.sign(header_bytes)

    transaction = transaction_pb2.Transaction(
        header=header_bytes,
        payload=payload.to_cbor(),
        header_signature=signature)

    return transaction
Exemplo n.º 7
0
def _get_state_data(names, context):
    alist = []
    for name in names:
        address = make_smart_bgt_address(name)
        alist.append(address)
    state_entries = context.get_state(alist)

    LOGGER.debug('_get_state_data state_entries=%s', state_entries)
    try:
        states = {}
        for entry in state_entries:
            state = cbor.loads(entry.data)
            for key, val in state.items():
                LOGGER.debug('_get_state_data add=%s', key)
                states[key] = val
        return states
    except IndexError:
        return {}
    except:
        raise InternalError('Failed to load state data')
Exemplo n.º 8
0
    async def _get_state_by_addr(self,request,address):
        LOGGER.debug('BgxRouteHandler:_get_state_by_addr %s',address)
        state_address = make_smart_bgt_address(address)

        error_traps = [error_handlers.InvalidAddressTrap] #,error_handlers.StateNotFoundTrap]

        head = request.url.query.get('head', None)

        head, root = await self._head_to_root(head)
        response = await self._query_validator(
            Message.CLIENT_STATE_GET_REQUEST,
            client_state_pb2.ClientStateGetResponse,
            client_state_pb2.ClientStateGetRequest(
                state_root=root, address=state_address),
            error_traps)
        LOGGER.debug('BgxRouteHandler:_get_state_by_addr %s',address)
        try:
            result = cbor.loads(base64.b64decode(response['value']))
            LOGGER.debug('BgxRouteHandler: _get_state_by_addr result=%s',type(result))
        except BaseException:
            LOGGER.debug('BgxRouteHandler: Cant get state FOR=%s',address)
            return None
        return result
Exemplo n.º 9
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)


        # Ask validator for batch status while it changes from PENDING
        pending_status = 'PENDING'
        status = ''
        while True:
            error_traps = [error_handlers.StatusResponseMissing]
            validator_query = \
                client_batch_submit_pb2.ClientBatchStatusRequest(
                    batch_ids=[batch_id])
            self._set_wait(request, validator_query)
            response = await self._query_validator(
                Message.CLIENT_BATCH_STATUS_REQUEST,
                client_batch_submit_pb2.ClientBatchStatusResponse,
                validator_query,
                error_traps)
            metadata = self._get_metadata(request, response)
            data = self._drop_id_prefixes(
                self._drop_empty_props(response['batch_statuses']))

            LOGGER.debug('CLIENT_BATCH_STATUS_REQUEST:metadata:%s', metadata)
            LOGGER.debug('CLIENT_BATCH_STATUS_REQUEST:data:%s', data)
            batch = data[0]
            if batch['status'] != pending_status:
                status = batch['status']
                break
            time.sleep(5)


        # Build response envelope
        # link = self._build_url(request, path='/batch_statuses', id=batch_id)
        return status
 def create_set_response(self, name):
     addresses = [make_smart_bgt_address(name)]
     return self._factory.create_set_response(addresses)
 def create_get_request(self, name):
     addresses = [make_smart_bgt_address(name)]
     return self._factory.create_get_request(addresses)
    def _create_txn(self, txn_function, verb, name, value):
        payload = self._dumps({'Verb': verb, 'Name': name, 'Value': value})

        addresses = [make_smart_bgt_address(name)]

        return txn_function(payload, addresses, addresses, [])