Пример #1
0
def _set_setting_value(context, key, value):
    address = _make_settings_key(key)
    setting = _get_setting_entry(context, address)

    old_value = None
    old_entry_index = None
    for i, entry in enumerate(setting.entries):
        if key == entry.key:
            old_value = entry.value
            old_entry_index = i

    if old_entry_index is not None:
        setting.entries[old_entry_index].value = value
    else:
        setting.entries.add(key=key, value=value)

    try:
        addresses = list(
            context.set_state({address: setting.SerializeToString()},
                              timeout=STATE_TIMEOUT_SEC))
    except FutureTimeoutError:
        LOGGER.warning('Timeout occured on context.set_state([%s, <value>])',
                       address)
        raise InternalError('Unable to set {}'.format(key))

    if len(addresses) != 1:
        LOGGER.warning('Failed to save value on address %s', address)
        raise InternalError('Unable to save config value {}'.format(key))
    if setting != 'sawtooth.settings.vote.proposals':
        LOGGER.info('Setting setting %s changed from %s to %s', key, old_value,
                    value)
Пример #2
0
def _set_config_value(state, key, value):
    address = _make_config_key(key)
    setting = _get_setting_entry(state, address)

    old_value = None
    old_entry_index = None
    for i, entry in enumerate(setting.entries):
        if key == entry.key:
            old_value = entry.value
            old_entry_index = i

    if old_entry_index is not None:
        setting.entries[old_entry_index].value = value
    else:
        setting.entries.add(key=key, value=value)

    try:
        addresses = list(
            state.set([
                StateEntry(address=address, data=setting.SerializeToString())
            ],
                      timeout=STATE_TIMEOUT_SEC))
    except FutureTimeoutError:
        LOGGER.warning('Timeout occured on state.set([%s, <value>])', address)
        raise InternalError('Unable to set {}'.format(key))

    if len(addresses) != 1:
        LOGGER.warning('Failed to save value on address %s', address)
        raise InternalError('Unable to save config value {}'.format(key))
    LOGGER.info('Config setting %s changed from %s to %s', key, old_value,
                value)
Пример #3
0
    def get_cached_data(self, resolvers, timeout=STATE_TIMEOUT_SEC):
        for address, pb_class in resolvers:
            try:
                data = self._storage[address]
                logger.debug('Got loaded data for address '
                             f'"{address}": {data}')
            except KeyError:
                try:
                    data = self.get_state([address])[0].data
                    self._storage[address] = data
                    logger.debug('Got pre-loaded data for address '
                                 f'"{address}": {data}')
                except IndexError:
                    yield None
                    continue
                except Exception as e:
                    logger.exception(e)
                    raise InternalError(f'Address "{address}" does not '
                                        'have access to data')

            if data is None:
                yield data
                continue

            try:
                pb = pb_class()
                pb.ParseFromString(data)
                yield pb
            except ParseError:
                raise InternalError('Failed to deserialize data')
            except Exception as e:
                logger.exception(e)
                yield None
Пример #4
0
    def fromJSON(self, json_string):

        try:
            data = json.loads(json_string)
        except:
            LOGGER.error('Cant read json with token: %s', sys.exc_info()[0])
            raise InternalError('Failed to load token')

        try:
            group_code = data['group_code']
            balance = int(data['balance'])
            granularity = int(data['granularity'])
            decimals = int(data['decimals'])
            owner_key = data['owner_key']
            sign = data['sign']
        except KeyError:
            LOGGER.error("json with token has not all arg")
            raise InternalError('Failed to load token')

        if not self.__checkValues(balance, granularity, decimals):
            LOGGER.error("Loading token from JSON - wrong args")
            raise InternalError('Failed to load token')

        if not self.active_flag:
            msg = 'Update "{n}"'.format(n=self.toJSON())
            LOGGER.debug(msg)

        self.active_flag = True
        self.group_code = group_code
        self.balance = balance
        self.granularity = granularity
        self.decimals = decimals
        self.owner_key = owner_key
        self.sign = sign
Пример #5
0
def _update_state(state, board):
    x_wins = _is_win(board, 'X')
    o_wins = _is_win(board, 'O')

    if x_wins and o_wins:
        raise InternalError('Two winners (there can be only one)')

    elif x_wins:
        return 'P1-WIN'

    elif o_wins:
        return 'P2-WIN'

    elif '-' not in board:
        return 'TIE'

    elif state == 'P1-NEXT':
        return 'P2-NEXT'

    elif state == 'P2-NEXT':
        return 'P1-NEXT'

    elif state in ('P1-WINS', 'P2-WINS', 'TIE'):
        return state

    else:
        raise InternalError('Unhandled state: {}'.format(state))
Пример #6
0
def _storeEvidence(context, evidenceToStore, address):

    # Retrieve all entries at the given address
    state_entries = context.get_state([address])
    evidenceList = evidence_pb2.EvidenceList()

    if state_entries == []:
        LOGGER.info('No previous evidences, creating new list for address %s',
                    address)
        evidenceList.Evidences.extend([evidenceToStore])
    else:   
        LOGGER.info('Appending evidence to existing list for address %s',
                    address)
        try:
            StoredEvidenceList = state_entries[0].data
            evidenceList.ParseFromString(StoredEvidenceList)
            evidenceList.Evidences.extend([evidenceToStore])
        except:
            raise InternalError('Failed to load state data')
        
    state_data = evidenceList.SerializeToString()
    LOGGER.info('State Data String: %s',
                        state_data)
    addresses = context.set_state({address: state_data})

    # Check if data was actually written to addresses
    if len(addresses) < 1:
        raise InternalError("State Error")
    def _make_eat(cls, context, amount, from_key):
        '''Eat (subtract) "amount" cookies.'''
        cookiejar_address = _get_cookiejar_address(from_key)
        LOGGER.info('Got the key %s and the cookiejar address %s.', from_key,
                    cookiejar_address)

        state_entries = context.get_state([cookiejar_address])
        new_count = 0

        if state_entries == []:
            LOGGER.info('No cookie jar with the key %s.', from_key)
        else:
            try:
                count = int(state_entries[0].data)
            except:
                raise InternalError('Failed to load state data')
            if count < int(amount):
                raise InvalidTransaction(
                    'Not enough cookies to eat. '
                    'The number should be <= %s.', count)
            else:
                new_count = count - int(amount)

        LOGGER.info('Eating %s cookies out of %d.', amount, count)
        state_data = str(new_count).encode('utf-8')
        addresses = context.set_state(
            {_get_cookiejar_address(from_key): state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
Пример #8
0
    def _make_bid(cls, context, amount, name, from_key):
        '''Bid add auction amount.'''
        cookiejar_address = _get_cookiejar_address(from_key)
        LOGGER.info('Got the key %s and the auction address %s.',
                    from_key, cookiejar_address)
        state_entries = context.get_state([cookiejar_address])
        new_count = 0

        if state_entries == []:
            LOGGER.info('No previous cookies, creating new cookie jar %s.',
                        from_key)
            new_count = int(amount)
        else:
            try:
                status = int(state_entries[0].data)
            except:
                raise InternalError('Failed to load state data')
	    count =int(status.split('by')[0])
            if new_count < count:
		new_status = str(new_count)+"by"+name
		state_data = str(new_status).encode('utf-8')
	    else 
		raise InternalError('value more than or equal to quoated value')
 		
        addresses = context.set_state({cookiejar_address: state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
Пример #9
0
    def _make_bake(cls, context, amount, from_key):
        '''Bake (add) "amount" cookies.'''
        cookiejar_address = _get_cookiejar_address(from_key)
        LOGGER.info('Got the key %s and the cookiejar address %s.', from_key,
                    cookiejar_address)
        state_entries = context.get_state([cookiejar_address])
        new_count = 0

        if state_entries == []:
            LOGGER.info('No previous cookies, creating new cookie jar %s.',
                        from_key)
            new_count = int(amount)
        else:
            try:
                count = int(state_entries[0].data)
            except:
                raise InternalError('Failed to load state data')
            new_count = int(amount) + int(count)

        state_data = str(new_count).encode('utf-8')
        addresses = context.set_state({cookiejar_address: state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
        context.add_event(event_type="cookiejar/bake",
                          attributes=[("cookies-baked", amount)])
Пример #10
0
def _set_container(state, address, container):
    """ Updates the state once any given handler has run."""

    try:
        addresses = state.set_state({address: container.SerializeToString()})
        if not addresses:
            raise InternalError('State error, failed to set state entities')
    except:
        raise InternalError(
            'State error, likely using wrong in/output fields in tx header.')
Пример #11
0
 def _set(state, items):
     entries = {}
     for (addr, container) in items:
         entries.update({addr: container.SerializeToString()})
     result_addresses = state.set(entries)
     if result_addresses:
         for (addr, _) in items:
             if addr not in result_addresses:
                 raise InternalError(
                     "Error setting state, " + "address %s not set.", addr)
     else:
         raise InternalError("Error setting state nothing updated?")
Пример #12
0
def _set_container(state, address, container):
    '''Sets the state at a certain address to a given container'''
    try:
        addresses = state.set_state({
        address: container.SerializeToString()
        })  
        if not addresses:
            raise InternalError(
                'State error, failed to set state entities')
    except:
        raise InternalError(
            'State error, likely using wrong in/output fields in tx header.')
Пример #13
0
 def _set(state, items):
     entries = []
     for (addr, container) in items:
         entries.append(
             StateEntry(address=addr, data=container.SerializeToString()))
     result_addresses = state.set(entries)
     if result_addresses:
         for (addr, _) in items:
             if addr not in result_addresses:
                 raise InternalError(
                     "Error setting state, " + "address %s not set.", addr)
     else:
         raise InternalError("Error setting state nothing updated?")
Пример #14
0
def __set_exchange(context, exchange, exchangeFQNAddress):
    """
    Sets an exchange state
    """
    exchange_data = exchange.SerializeToString()
    state_dict = {exchangeFQNAddress: exchange_data}
    try:
        addresses = context.set_state(state_dict, timeout=STATE_TIMEOUT_SEC)
    except FutureTimeoutError:
        raise InternalError('Unable to set {}'.format(exchangeFQNAddress))
    if len(addresses) != 1:
        raise InternalError('Unable to save exchange for address {}'.format(
            exchangeFQNAddress))
Пример #15
0
def _set_data(state, address, data):
    try:
        addresses = list(
            state.set([StateEntry(address=address, data=data)],
                      timeout=STATE_TIMEOUT_SEC))

    except FutureTimeoutError:
        LOGGER.warning('Timeout occured on state.set([%s, <value>])', address)
        raise InternalError(
            'Failed to save value on address {}'.format(address))

    if len(addresses) != 1:
        LOGGER.warning('Failed to save value on address %s', address)
        raise InternalError(
            'Failed to save value on address {}'.format(address))
Пример #16
0
def _set_data(context, address, data):
    try:
        addresses = list(
            context.set_state({address: data}, timeout=STATE_TIMEOUT_SEC))

    except FutureTimeoutError:
        LOGGER.warning('Timeout occurred on context.set_state([%s, <value>])',
                       address)
        raise InternalError(
            'Failed to save value on address {}'.format(address))

    if len(addresses) != 1:
        LOGGER.warning('Failed to save value on address %s', address)
        raise InternalError(
            'Failed to save value on address {}'.format(address))
Пример #17
0
    def _make_item_transfer(self, context, transfer_details, item_name_code):
        item_address = self._get_item_address(item_name_code)
        LOGGER.info('Got the key {} and the item address {} '.format(
            item_name_code, item_address))
        current_entry = context.get_state([item_address])
        transfer_history = str([
            'current_time', 'current_date', 'item_name_code', 'from_client',
            'current_client', 'to_client'
        ])

        if current_entry == []:
            LOGGER.info(
                'No previous item transfers, creating new item transfer {} '.
                format(item_name_code))
            transfer_history = str(transfer_history) + str(transfer_details)
        else:
            item_history = str(current_entry[0].data)
            item_history = str(item_history) + str(transfer_details)
            transfer_history = str(item_history)

        state_data = str(transfer_history).encode('utf-8')
        addresses = context.set_state({item_address: state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
Пример #18
0
    def delete_identity(self, name):
        """Delete the identity named name from state.

        Args:
            name (str): The name.

        Raises:
            KeyError: The identity with name does not exist.
        """

        identities = self._load_identities(name=name)

        # delete identity from dict of name, identity pairs
        try:
            del identities[name]
        except KeyError:
            raise InternalError(
                "The identity with name {} does not exist.".format(name))

        # If identities is not empty
        if identities:

            # update address cache and validator state to reflect remaining identities
            # that said, it feels weird to store on the _address_cache
            # deleted_name, remaining identities pair since deleted_name
            self._store_identity(name, identities=identities)
        else:

            # Remove from address cache and validator state
            self._delete_identity(name)
Пример #19
0
    def apply(self, transaction, context):
        self.log("Apply called")

        # unpack transaction info
        action, key, data = unpack_transaction(transaction)

        # get the current state
        state = get_state_data(key, context)

        if action == 'set':
            self.log(" Action is 'set'")
            # use protobuf data to create a DatabaseEntry and execute it
            entry = DatabaseEntry(data)

            try:
                self.apply_callback(entry.key())
            except ValueError:
                self.log(" Database entry apply failed")

            # update the state
            updated_state = dict(state.items())
            updated_state[key] = data
            set_state_data(key, updated_state, context)

        else:
            raise InternalError('Invalid function requested to be executed by CCellular Handler')
    def _make_withdraw(self, context, amount, from_key):
        wallet_key = self._get_wallet_key(from_key)
        LOGGER.info('Got the key {} and the wallet key {} '.format(
            from_key, wallet_key))
        current_entry = context.get_state([wallet_key])
        new_balance = 0

        if current_entry == []:
            LOGGER.info('No user with the key {} '.format(from_key))
        else:
            balance = int(current_entry[0].data)
            if balance < int(amount):
                raise InvalidTransaction(
                    'Not enough money. Tha amount should be lesser or equal to {} '
                    .format(value))
            else:
                new_balance = balance - int(amount)

        LOGGER.info('Withdrawing {} '.format(amount))
        state_data = str(new_balance).encode()
        addresses = context.set_state(
            {self._get_wallet_key(from_key): state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
Пример #21
0
def _get_state_data(context, namespace_prefix, name):
    # Get data from address
    state_entries = \
        context.get_state([_make_xo_address(namespace_prefix, name)])

    # context.get_state() returns a list. If no data has been stored yet
    # at the given address, it will be empty.
    if state_entries:
        try:
            state_data = state_entries[0].data

            game_list = {
                name: (board, state, player1, player2)
                for name, board, state, player1, player2 in
                [game.split(',') for game in state_data.decode().split('|')]
            }

            board, state, player1, player2 = game_list[name]

        except ValueError:
            raise InternalError("Failed to deserialize game data.")

    else:
        game_list = {}
        board = state = player1 = player2 = None

    return board, state, player1, player2, game_list
Пример #22
0
def delete_state(context, addresses):
    """Deletes a list of addresses from the blockchain state"""
    try:
        return context.delete_state(addresses=addresses,
                                    timeout=TIMEOUT_SECONDS)
    except FutureTimeoutError:
        raise InternalError(ERROR_MESSAGE_TIMEOUT, TIMEOUT_SECONDS)
Пример #23
0
def get_addresses(context, addresses):
    """Reads a list of addresses from the blockchain state"""
    try:
        return list(
            context.get_state(addresses=addresses, timeout=TIMEOUT_SECONDS))
    except FutureTimeoutError:
        raise InternalError(ERROR_MESSAGE_TIMEOUT, TIMEOUT_SECONDS)
Пример #24
0
    def apply(self, transaction, context):
        def saleAsset(context, payloadAttributes, assetAddress):
            state_data = context.get_state([assetAddress])
            bottleData = json.loads((state_data[0].data).decode('utf-8'))

            #sanitycheck
            if bottleData['bottleID'] == payloadAttributes[1]:
                bottleData['posSale'] = payloadAttributes[2]
                return bottleData
            else:
                raise InvalidTransaction("Wrong bottle!")

        payloadAttributes = transaction.payload.decode().split(",")

        if checkPayload(payloadAttributes):
            assetAddress = _hash(payloadAttributes[1])

        bottleData = saleAsset(context, payloadAttributes, assetAddress)

        #writing the bottleData to state
        state_data = json.dumps(bottleData).encode('utf-8')

        addresses = context.set_state({assetAddress: state_data})

        if len(addresses) < 1:
            raise InternalError("State Error")
Пример #25
0
    def apply(self, transaction, state):

        txn_header = TransactionHeader()
        txn_header.ParseFromString(transaction.header)
        pubkey = txn_header.signer_pubkey

        auth_type = _get_auth_type(state)
        auth_keys = _get_auth_keys(state)
        if len(auth_keys) > 0 and pubkey not in auth_keys:
            raise InvalidTransaction(
                '{} is not authorized to change settings'.format(pubkey))

        config_payload = ConfigPayload()
        config_payload.ParseFromString(transaction.payload)

        if auth_type == 'Ballot':
            return self._apply_ballot_config(pubkey, config_payload, auth_keys,
                                             state)
        elif auth_type == 'None':
            return self._apply_noauth_config(pubkey, config_payload, state)
        else:
            LOGGER.error('auth_type %s should not have been allowed',
                         auth_type)
            raise InternalError(
                'auth_type {} should not have been allowed'.format(auth_type))
Пример #26
0
    def __init__(self,
                 group_code=None,
                 balance=0,
                 digital_signature=None,
                 granularity=1,
                 decimals=18):

        if group_code == None:
            self.active_flag = False
            self.group_code = 'None'
            self.balance = 0
            self.granularity = granularity
            self.decimals = decimals
            self.owner_key = 'None'
            self.sign = 'None'
        else:
            if not self.__checkValues(balance, granularity, decimals,
                                      digital_signature):
                LOGGER.error("Init token - wrong args")
                raise InternalError('Failed to init token')

            self.active_flag = True
            self.group_code = str(group_code)
            self.balance = balance
            self.granularity = granularity
            self.decimals = decimals
            self.owner_key = str(digital_signature.getVerifyingKey())
            self.sign = str(digital_signature.sign(self.getImprint()))
def _get_state_data(context, namespace_prefix, b_id, upd_location=None):
    # Get data from address
    state_entries = context.get_state(
        [_make_xo_address(namespace_prefix, b_id)])
    append_location = ''
    if upd_location is not None:
        append_location = '-> {}'.format(upd_location)
    # context.get_state() returns a list. If no data has been stored yet
    # at the given address, it will be empty.
    if state_entries:
        try:
            state_data = state_entries[0].data

            barcode_list = {
                b_id: (product_name, mfg_date, location + append_location)
                for b_id, product_name, mfg_date, location in [
                    barcode.split(',')
                    for barcode in state_data.decode().split('|')
                ]
            }

            (product_name, mfg_date,
             location) = barcode_list[re.sub("^0+", "", b_id)]

        except ValueError:
            raise InternalError("Failed to deserialize game data.")

    else:
        barcode_list = {}
        product_name = mfg_date = location = None

    return product_name, mfg_date, location, barcode_list
Пример #28
0
    def handle_add_related(self, event):
        assert isinstance(event, Events.AddRelated)

        def add(evt, obj_class, related_class, list_name):
            logger.debug("Generic Add Related")
            logger.debug("    source  : %r of %r" %
                         (evt.object_key, obj_class))
            logger.debug("    related : %r of %r" %
                         (evt.related_key, related_class))
            # get the state & address of the two items, using the mapping class to handle any class
            src = self.state.get_and_parse(
                obj_class, address.addr_map[obj_class](evt.object_key))
            related = self.state.get_and_parse(
                related_class,
                address.addr_map[related_class](evt.related_key))

            list_field = getattr(
                src, list_name
            )  # acts like a list, but really is a RepeatedScalarContext
            list_field[:] = list(set(list_field[:] + [related.key]))

            self.state.set_for_object(src)

        action_map = {
            "farm_cert": (Farm, Certification, "certifications"),
            "harvest_farm": (Harvest, Farm, "farms"),
            "harvest_shipment": (Harvest, Shipment, "shipments"),
            "roast_harvest": (Roast, Harvest, "harvests")
        }

        if event.action not in action_map:
            raise InternalError("Unmapped action for AddRelated: %s" %
                                event.action)

        add(event, *action_map[event.action])
Пример #29
0
    def add_event(self, event_type, attributes=None, data=None, timeout=None):
        """Add a new event to the execution result for this transaction.

        Args:
            event_type (str): This is used to subscribe to events. It should be
                globally unique and describe what, in general, has occured.
            attributes (list of (str, str) tuples): Additional information
                about the event that is transparent to the validator.
                Attributes can be used by subscribers to filter the type of
                events they receive.
            data (bytes): Additional information about the event that is opaque
                to the validator.
        """
        if attributes is None:
            attributes = []

        event = events_pb2.Event(
            event_type=event_type,
            attributes=[
                events_pb2.Event.Attribute(key=key, value=value)
                for key, value in attributes
            ],
            data=data,
        )
        request = state_context_pb2.TpEventAddRequest(
            context_id=self._context_id, event=event).SerializeToString()
        response = state_context_pb2.TpEventAddResponse()
        response.ParseFromString(
            self._stream.send(Message.TP_EVENT_ADD_REQUEST,
                              request).result(timeout).content)
        if response.status == state_context_pb2.TpEventAddResponse.ERROR:
            raise InternalError("Failed to add event: ({}, {}, {})".format(
                event_type, attributes, data))
Пример #30
0
    def apply(self, transaction, context):
        transaction_payload = TransactionPayload()
        transaction_payload.ParseFromString(transaction.payload)

        state_processor = self.get_state_processor()
        try:
            data_pb = state_processor[transaction_payload.method][PB_CLASS]()
            data_pb.ParseFromString(transaction_payload.data)
            processor = state_processor[transaction_payload.method][PROCESSOR]
            updated_state = processor(context,
                                      transaction.header.signer_public_key,
                                      data_pb)
        except KeyError:
            raise InvalidTransaction(
                'Unknown value {} for the pub_key operation type.'.format(
                    int(transaction_payload.method)))
        except ParseError:
            raise InvalidTransaction('Cannot decode transaction payload')

        addresses = context.set_state(
            {k: v.SerializeToString()
             for k, v in updated_state.items()})

        if len(addresses) < len(updated_state):
            raise InternalError('Failed to update all of states. Updated: {}. '
                                'Full list of states to update: {}.'.format(
                                    addresses, updated_state.keys()))

        event_name = state_processor[transaction_payload.method].get(
            EMIT_EVENT, None)
        if event_name:
            add_event(
                context, event_name,
                get_event_attributes(updated_state, transaction.signature))