Exemplo n.º 1
0
    def check_valid(self, store, txn):
        # make sure the holding is really a holding
        if not holding_update.HoldingObject.is_valid_object(
                store, self._holding_id):
            raise InvalidTransactionError(
                "HoldingId does not reference a holding")

        # We don't need to check for any permissions since we are adding
        # tokens to a holding

        # Make sure the holding contains validation token assets, this will
        # require getting access to the token type, probably by name (ugghhh)
        if not IncentiveUpdate.ValidationTokenAssetID:
            IncentiveUpdate.ValidationTokenAssetID = store.n2i(
                '//marketplace/asset/validation-token', 'Asset')
            assert IncentiveUpdate.ValidationTokenAssetID

        obj = holding_update.HoldingObject.get_valid_object(
            store, self._holding_id)
        if obj.get('asset') != IncentiveUpdate.ValidationTokenAssetID:
            logger.info('holding %s does not contain validation tokens',
                        self._holding_id)
            raise InvalidTransactionError(
                "Holding {} does not contain validation "
                "tokens".format(self._holding_id))
Exemplo n.º 2
0
    def check_valid(self, store, txn):
        if self._object_id not in store:
            raise InvalidTransactionError("Object does not exist {}".format(
                self._object_id))

        participant = store.lookup("participant:object-id", self._object_id)

        try:
            creator = store.lookup("participant:key-id", txn.OriginatorID)
        except KeyError:
            raise InvalidTransactionError(
                "Only the creator can update particpant")

        if creator["object-id"] != participant["creator-id"]:
            raise InvalidTransactionError(
                "Only the creator can update particpant")

        if self._username is not None:
            try:
                store.lookup('participant:username', self._username)
                raise InvalidTransactionError(
                    "Username already exists: {}".format(self._username))
            except KeyError:
                pass

        if self._firm_id is not None:
            try:
                store.lookup('organization:object-id', self._firm_id)
            except KeyError:
                raise InvalidTransactionError("Firm does not exist: {}".format(
                    self._firm_id))
Exemplo n.º 3
0
    def check_valid(self, store, txn):
        if txn.Identifier in store:
            raise InvalidTransactionError("ObjectId already in store")

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator address is different from txn.OriginatorID")

        if not market_place_object_update.global_is_valid_name(
                store, self._name, self.ObjectType, self._creator_id):
            raise InvalidTransactionError(
                "Name, {}, is not valid".format(self._name))

        if not liability_update.LiabilityObject.is_valid_object(
                store, self._input_id):
            raise InvalidTransactionError(
                "{} is not a Liability".format(self._input_id))

        obj = liability_update.LiabilityObject.get_valid_object(store,
                                                                self._input_id)
        if not self.CreatorType.is_valid_creator(store, obj.get('creator'),
                                                 txn.OriginatorID):
            logger.info('%s does not have permission to modify liability %s',
                        txn.OriginatorID, self._input_id)
            raise InvalidTransactionError(
                "Txn.OriginatorID not allowed to modify liability")

        if not holding_update.HoldingObject.is_valid_object(store,
                                                            self._output_id):
            raise InvalidTransactionError(
                "OutputId is not a valid Holding")

        obj = holding_update.HoldingObject.get_valid_object(
            store, self._output_id)
        if not self.CreatorType.is_valid_creator(store, obj.get('creator'),
                                                 txn.OriginatorID):
            logger.info('%s does not have permission to modify liability %s',
                        txn.OriginatorID, self._output_id)
            raise InvalidTransactionError(
                "Txn.OriginatorID does not have permission to modify "
                "liability")

        if self._ratio <= 0:
            logger.debug('invalid ratio %s in offer %s', self._ratio,
                         txn.Identifier)
            raise InvalidTransactionError(
                "Ratio < 0")

        if self._minimum < 0 or self._maximum < 0 or \
                self._maximum < self._minimum:
            logger.debug('inconsistent range %s < %s in offer %s',
                         self._minimum, self._maximum, txn.Identifier)
            raise InvalidTransactionError(
                "Minimum and Maximum are inconsistent")
        if self._execution not in SellOfferObject.ExecutionStyle:
            logger.debug('invalid execution style %s in offer %s',
                         self._execution, txn.Identifier)
            raise InvalidTransactionError(
                "Execution not a valid ExecutionStyle")
Exemplo n.º 4
0
    def check_valid(self, store, txn):
        """Determines if the update is valid.
            Check policy on each element of validator_name, validator_id,
            and signup_info

        Args:
            store (Store): Transaction store.
            txn (Transaction): Transaction encompassing this update.
        """
        LOGGER.debug('check update %s from %s', str(self), self.validator_id)

        # Check name
        if not self.is_valid_name():
            raise InvalidTransactionError('Illegal validator name {}'.format(
                self.validator_name[:64]))

        # Check registering validator matches transaction signer.
        if self.validator_id != txn.OriginatorID:
            raise InvalidTransactionError(
                'Signature mismatch on validator registration with validator'
                ' {} signed by {}'.format(self.validator_id, txn.OriginatorID))

        # Nothing to check for anti_sybil_id
        # Apply will invalidate any previous entries for this anti_sybil_id
        # and create a new entry.

        # Check signup_info. Policy is encapsulated by SignupInfo.
        if not self.signup_info.is_valid():
            raise InvalidTransactionError('Invalid Signup Info: {}'.format(
                self.signup_info))
        return True
Exemplo n.º 5
0
    def check_valid(self, store, txn):
        if txn.Identifier in store:
            raise InvalidTransactionError("ObjectId already in store")

        if not market_place_object_update.global_is_valid_name(
                store, self._name, self.ObjectType, self._creator_id):
            raise InvalidTransactionError("Name is not valid")

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator Address not the same as txn.OriginatorID")

        assettype = asset_type_update.AssetTypeObject.load_from_store(
            store, self._asset_type_id)
        if not assettype:
            logger.debug('missing asset type %s', self._asset_type_id)
            raise InvalidTransactionError(
                "AssetTypeId does not reference an AssetType")

        # if the asset type is restricted then the creator of the asset type
        # is the only one who can create assets of that type
        if assettype.Restricted and assettype.CreatorID != self._creator_id:
            logger.debug('no permission to create an asset of type %s',
                         self._asset_type_id)
            raise InvalidTransactionError(
                "AssetType is restricted and the creator is not the same "
                "as txn creator")
Exemplo n.º 6
0
    def check_valid(self, store, txn):
        assert txn.OriginatorID

        if not self.ObjectType.is_valid_object(store, self._object_id):
            raise InvalidTransactionError("ObjectId is not an AssetType")

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator address is not the same as txn.OriginatorID")
Exemplo n.º 7
0
    def check_valid(self, store, txn):
        if txn.Identifier in store:
            raise InvalidTransactionError("Object Id is already in store")

        if not market_place_object_update.global_is_valid_name(
                store, self._name, self.ObjectType, self._creator_id):
            raise InvalidTransactionError("Name isn't valid")

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator address is not the same as txn.OriginatorID")
Exemplo n.º 8
0
    def check_valid(self, store, txn):
        assert txn.OriginatorID
        assert self._object_id
        assert self._creator_id

        if not self.ObjectType.is_valid_object(store, self._object_id):
            raise InvalidTransactionError(
                "ObjectId does not reference an ExchangeOffer")

        if not self.CreatorType.is_valid_creator(store, self._creator_id,
                                                 txn.OriginatorID):
            raise InvalidTransactionError(
                "CreatorId address is not the same as txn.OriginatorID")
Exemplo n.º 9
0
    def apply(self, store):
        logger.debug('apply %s', str(self))

        if self._name in store:
            game = store[self._name].copy()
        elif self._hand is not None:
            raise InvalidTransactionError(
                'Hand to be played without a game registered (should not '
                'happen)')
        else:
            if self._players == 1:
                game = {
                    'State': 'OPEN',
                    'Hands': {},
                    'Players': 2,
                    'InitialID': self.OriginatorID,
                    'Computer': True
                }
            else:
                game = {
                    'State': 'OPEN',
                    'Hands': {},
                    'Players': self._players,
                    'InitialID': self.OriginatorID,
                }

        if self._hand is not None:
            if self.OriginatorID in game['Hands']:
                raise InvalidTransactionError('hand already registered')

            if self._hand not in VALID_HANDS:
                raise InvalidTransactionError('invalid hand')

            game['Hands'][self.OriginatorID] = self._hand

        nr_hands = len(game['Hands'])
        if game['State'] != 'OPEN' and nr_hands < game['Players']:
            raise InvalidTransactionError("state not open while missing hands")
        elif nr_hands == game['Players']:
            # find out how won
            initial_id = game['InitialID']
            hand_a = game['Hands'][initial_id]
            results = {}
            for player, hand_b in game['Hands'].iteritems():
                if player == initial_id:
                    continue
                results[player] = self._is_winner(hand_a, hand_b)
            game['Results'] = results
            game['State'] = 'COMPLETE'
        store[self._name] = game
Exemplo n.º 10
0
    def check_valid(self, store, txn):
        if self._object_id not in store:
            raise InvalidTransactionError(
                "Object with id does not exist: {}".format(self._object_id))

        organization = store.get(self._object_id)
        try:
            participant = store.lookup('participant:key-id', txn.OriginatorID)
        except:
            raise InvalidTransactionError("Participant does not exist.")

        if participant["object-id"] != organization["creator-id"]:
            raise InvalidTransactionError(
                "Organization can only be updated by its creator {}".format(
                    participant["object-id"]))
        if self._name:
            try:
                store.lookup('organization:name', self._name)
                raise InvalidTransactionError(
                    "Object with name already exists: {}".format(self._name))
            except KeyError:
                pass

        if self._ticker is not None:
            if "ticker" in organization:
                raise InvalidTransactionError(
                    "Organization already has a ticker {}".format(
                        self._ticker))
            try:
                store.lookup("organization:ticker", self.ticker)
                raise InvalidTransactionError(
                    "The ticker already exists {}".format(self._ticker))
            except KeyError:
                pass

        if self._pricing_source is not None:
            if "pricing-source" in organization:
                raise InvalidTransactionError(
                    "Organization already has a pricing source {}".format(
                        self._pricing_source))
            try:
                store.lookup("organization:pricing-source",
                             self._pricing_source)
                raise InvalidTransactionError(
                    "The pricing source already exists {}".format(
                        self._pricing_source))
            except KeyError:
                pass

            if len(self._pricing_source) != 4:
                raise InvalidTransactionError(
                    "Pricing source must be a four-character string: {}".
                    format(self._pricing_source))
Exemplo n.º 11
0
    def check_valid(self, store, txn):
        if not self.ObjectType.is_valid_object(store, self._object_id):
            return False

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator Address is not the same as txn.OriginatorID")
Exemplo n.º 12
0
    def check_valid(self, store):
        """Determines if the transaction is valid.

        Args:
            store (dict): Transaction store mapping.
        """
        if not super(Transaction, self).is_valid(store):
            raise InvalidTransactionError("invalid signature")
Exemplo n.º 13
0
    def check_valid(self, store, txn):
        logger.debug('market update: %s', str(self))

        assert txn.OriginatorID
        assert self._object_id
        assert self._creator_id

        if not self.ObjectType.is_valid_object(store, self._object_id):
            raise InvalidTransactionError(
                "ObjectId does not reference a valid object")

        if not self.is_valid_name(store):
            raise InvalidTransactionError(
                "Name isn't valid")

        if not self.is_permitted(store, txn):
            raise InvalidTransactionError(
                "Creator address not the same as txn.OriginatorID")
Exemplo n.º 14
0
    def check_valid(self, store, txn):
        """Determines if the update is valid.
            Check policy on each element of validator_name, validator_id,
            and signup_info

        Args:
            store (Store): Transaction store.
            txn (Transaction): Transaction encompassing this update.
        """
        LOGGER.debug('check update %s from %s', str(self), self.validator_id)

        # Check name
        if not self.is_valid_name():
            raise InvalidTransactionError(
                'Illegal validator name {}'.format(self.validator_name[:64]))

        # Check registering validator matches transaction signer.
        if self.validator_id != txn.OriginatorID:
            raise InvalidTransactionError(
                'Signature mismatch on validator registration with validator'
                ' {} signed by {}'.format(self.validator_id,
                                          txn.OriginatorID))

        # Nothing to check for anti_sybil_id
        # Apply will invalidate any previous entries for this anti_sybil_id
        # and create a new entry.

        try:
            public_key_hash = \
                hashlib.sha256(
                    signing.encode_pubkey(
                        txn.originator_public_key,
                        'hex')).hexdigest()

            self.signup_info.check_valid(
                originator_public_key_hash=public_key_hash,
                most_recent_wait_certificate_id='0' * 16)
        except SignupInfoError as error:
            raise InvalidTransactionError(
                'Invalid Signup Info: {0}, Reason: {1}'.format(
                    self.signup_info,
                    error))

        return True
    def check_valid(self, store, txn):
        """Determines if the update is valid.
            Check policy
        Args:
            store (Store): Transaction store.
            txn (Transaction): Transaction encompassing this update.
        """
        LOGGER.debug('check update %s from %s', str(self), self.whitelist_name)

        # Check name
        if not self.is_valid_name():
            raise InvalidTransactionError('Illegal whitelist name {}'.format(
                self.whitelist_name[:64]))


#         try:
#             with open("/home/vagrant/sawtooth/whitelist.json")\
#                     as whitelist_fd:
#                 whitelist_dic = json.load(whitelist_fd)
#         except IOError, ex:
#             raise InvalidTransactionError(
#                 'could not open /home/vagrant/sawtooth/whitelist.json {}'
#                 .format(str(ex)))

        if not PermissionedValidators:
            raise InvalidTransactionError('No Permissioned Validators')

        whitelist_dic = PermissionedValidators
        if 'PermissionedValidatorPublicKeys' in whitelist_dic:
            permissioned_public_keys =\
                whitelist_dic['PermissionedValidatorPublicKeys']
            for public_key in self.permissioned_public_keys:
                if public_key not in permissioned_public_keys:
                    raise InvalidTransactionError(
                        'Illegal public key {}'.format(str(public_key)))

        if 'PermissionedValidatorAddrs' in whitelist_dic:
            permissioned_addrs = whitelist_dic['PermissionedValidatorAddrs']
            for addr in self.permissioned_addrs:
                if addr not in permissioned_addrs:
                    raise InvalidTransactionError(
                        'Illegal public addr {}'.format(str(addr)))

        return True
Exemplo n.º 16
0
    def check_valid(self, store, txn):
        if self._creator_id != self._object_id:
            logger.info('creator and object are the same for participant '
                        'unregistration')
            return False

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator Address not the same as txn.OriginatorID")
Exemplo n.º 17
0
    def check_valid(self, store):
        """Determines if the transaction is valid.

        Args:
            store (dict): Transaction store mapping.
        """

        super(SegTransaction, self).check_valid(store)

        LOGGER.debug('checking %s', str(self))

        if self._address is None or self._address == '':
            raise InvalidTransactionError('address not set')

        if self._balance is None or self._balance == '':
            raise InvalidTransactionError('balance not set')

        if self._block is None or self._block == '':
            raise InvalidTransactionError('block not set')
Exemplo n.º 18
0
    def check_valid(self, store):
        """Determines if the update is valid.

        Args:
            store (dict): Transaction store mapping.

        Returns:
            bool: Whether or not the update is valid.
        """
        logger.debug('check update %s', str(self))

        # in theory, the name should have been checked before the transaction
        # was submitted... not being too careful about this
        if not self.Name or self.Name == '':
            raise InvalidTransactionError('"{}" is not a valid key'.format(
                self.Name))

        # in theory, the value should have been checked before the transaction
        # was submitted... not being too careful about this
        if not isinstance(self.Value, (int, long)):
            raise InvalidTransactionError(
                '{} is not a valid value type'.format(
                    type(self.Value).__name__))

        # in theory, the value should have been checked before the transaction
        # was submitted... not being too careful about this
        if self.Verb == 'set':
            if self.Name in store:
                raise InvalidTransactionError('key "{}" already exists'.format(
                    self.Name))
            if self.Value < 0:
                raise InvalidTransactionError('Initial value must be >= 0')

        elif self.Verb == 'inc':
            if self.Name not in store:
                raise InvalidTransactionError('key "{}" does not exist'.format(
                    self.Name))

        elif self.Verb == 'dec':
            if self.Name not in store:
                raise InvalidTransactionError('key "{}" does not exist'.format(
                    self.Name))
            if store[self.Name] < self.Value:
                # value after a decrement operation must remain above zero
                raise InvalidTransactionError(
                    'key "{}" value must be > 0 after decrement: {} - {} = {}'.
                    format(self.Name, store[self.Name], self.Value,
                           store[self.Name] - self.Value))
        else:
            raise InvalidTransactionError('Verb "{}" is not understood '
                                          '(i.e, it is not "set", "inc" or '
                                          '"dec").'.format(self.Name))
Exemplo n.º 19
0
    def check_valid(self, store, txn):
        logger.debug('market update: %s', str(self))

        assert txn.OriginatorID
        assert txn.Identifier
        assert self._creator_id

        if not self.ObjectType.IsValidObject(store, txn.Identifier):
            raise InvalidTransactionError(
                "ObjectId does not reference a valid object")

        if not self.CreatorType.IsValidCreator(store, self._creator_id,
                                               txn.OriginatorID):
            raise InvalidTransactionError(
                "Creator Address not the same as txn.OriginatorId")

        if len(self._description) > 255:
            logger.debug('description must be less than 255 bytes')
            raise InvalidTransactionError(
                "Description is longer than 255 characters")
Exemplo n.º 20
0
    def check_valid(self, store, txn):
        if self._object_id not in store:
            raise InvalidTransactionError(
                "Object with id does not exist: {}".format(self._object_id))

        organization = store.get(self._object_id)
        try:
            participant = store.lookup('participant:key-id', txn.OriginatorID)
        except:
            raise InvalidTransactionError("Participant does not exist.")

        if participant["object-id"] != organization["creator-id"]:
            raise InvalidTransactionError(
                "Organization can only be deleted by its creator {}".format(
                    participant["object-id"]))

        if organization["ref-count"] != 0:
            raise InvalidTransactionError(
                "Organization can only be deleted if its ref-count is zero {}".
                format(organization["ref-count"]))
Exemplo n.º 21
0
    def check_valid(self, store):
       """Determines if the transaction is valid.

        Args:
            store (dict): Transaction store mapping.
        """

        super(XoTransaction, self).check_valid(store)

        LOGGER.debug('checking %s', str(self))
        
        raise InvalidTransactionError('XoTransaction.check_valid is not implemented')
Exemplo n.º 22
0
    def check_valid(self, store, txn):
        clock_tolerance = 120

        if self._blocknum is None or self._blocknum == '':
            raise InvalidTransactionError('blocknum not set')

        if self._timestamp is None or self._timestamp == '':
            raise InvalidTransactionError('timestamp not set')

        if self.__key__ in store:
            raise InvalidTransactionError(
                'clock entry already exists: {}'.format(self.__key__))

        if self._blocknum != 0 and self.__prev_key__ not in store:
            raise InvalidTransactionError(
                'previous clock entry does not exist: '
                '{}'.format(self.__prev_key__))

        if self._blocknum != 0 and \
           (self._timestamp + clock_tolerance) <= \
                store[self.__prev_key__]['timestamp']:
            raise InvalidTransactionError(
                'timestamp is smaller than prior block blocknum {0}: {1},'
                'blocknum {2}: {3}'.format(
                    self._blocknum - 1, store[self.__prev_key__]['timestamp'],
                    self._blocknum, self._timestamp))

        if self._timestamp >= (time.time() + clock_tolerance):
            raise InvalidTransactionError('timestamp is in the future')
Exemplo n.º 23
0
    def check_valid(self, store, txn):
        if self._object_id in store:
            raise InvalidTransactionError(
                "Object with id already exists: {}".format(self._object_id))

        try:
            store.lookup('participant:username', self._username)
            raise InvalidTransactionError("Username already exists: {}".format(
                self._username))
        except KeyError:
            pass

        if self._firm_id:
            try:
                store.get(self._firm_id, object_type='organization')
            except KeyError:
                raise InvalidTransactionError("Firm does not exist: {}".format(
                    self._firm_id))

        if len(self._username) < 3 or len(self._username) > 16:
            raise InvalidTransactionError(
                "Usernames must be between 3 and 16 characters")
Exemplo n.º 24
0
    def check_valid(self, store, txn):
        if txn.Identifier in store:
            raise InvalidTransactionError("ObjectId alread in store")

        if not market_place_object_update.global_is_valid_name(
                store, self._name, self.ObjectType, self._creator_id):
            raise InvalidTransactionError("Name isn't valid")

        if not market_place_object_update.global_is_permitted(
                store, txn, self._creator_id, self.CreatorType):
            raise InvalidTransactionError(
                "Creator Address not the same as txn.OriginatorID")

        if not account_update.AccountObject.is_valid_object(
                store, self._account_id):
            raise InvalidTransactionError(
                "AccountID does not reference an Account")

        if self._count < 0:
            raise InvalidTransactionError("Count is less than 0")

        # make sure we have a valid asset
        asset = asset_update.AssetObject.load_from_store(store, self._asset_id)
        if not asset:
            logger.debug('invalid asset %s in holding', self._asset_id)
            raise InvalidTransactionError(
                "AssetId does not reference an Asset")

        # if the asset is restricted, then only the creator of the asset can
        # create holdings with a count greater than 0
        if asset.Restricted:
            if self._creator_id != asset.CreatorID and 0 < self._count:
                logger.debug(
                    'instances of a restricted asset %s can only be created '
                    'by the owner', self._asset_id)
                raise InvalidTransactionError(
                    "Instances of a restricted asset {} can only be created "
                    "by the owner".format(self._asset_id))

        # if the asset is not consumable then counts dont matter, the only
        # valid counts are 0 or 1
        if not asset.Consumable:
            if 1 < self._count:
                logger.debug(
                    'non consumable assets of type %s are retricted to '
                    'a single instance', self._asset_id)
                raise InvalidTransactionError(
                    "Non consumable assets are restricted to a single "
                    "instance")
Exemplo n.º 25
0
    def check_valid(self, store, txn):
        logger.debug('market update: %s', str(self))

        # check to make sure that the originator has permission to decrement
        # the InitialLiability
        if not liability_update.LiabilityObject.is_valid_object(
                store, self._initial_liability_id):
            raise InvalidTransactionError(
                "Initial Liability does not reference a liability")

        # verify that the originator of the transaction is the owner of the
        # source liability
        payer = _LiabilityInformation.load_from_store(
            store, self._initial_liability_id)
        if not self.CreatorType.is_valid_creator(store, payer.CreatorID,
                                                 txn.OriginatorID):
            logger.warn(
                '%s does not have permission to transfer assets from '
                'liability %s', payer.CreatorID, self._initial_liability_id)
            raise InvalidTransactionError("Payer is not a valid Creator "
                                          "or does not have access to "
                                          "liability")

        # check to make sure that the originator has permission to increment
        # the FinalLiability
        if not liability_update.LiabilityObject.is_valid_object(
                store, self._final_liability_id):
            raise InvalidTransactionError(
                "Final liability does not reference a liability")

        # ensure that all of the offers are valid
        offermap = set()
        for offerid in self._offer_id_list:
            # make sure the offerid references a valid offer, note that a
            # selloffer is really just a subclass of exchangeoffer so a
            # selloffer is a valid exchange offer
            if not exchange_offer_update.ExchangeOfferObject.is_valid_object(
                    store, offerid):
                raise InvalidTransactionError(
                    "Offerid {} is not an ExchangeOffer".format(str(offerid)))
            # ensure that there are no duplicates in the list, duplicates can
            # cause of tests for validity to fail
            if offerid in offermap:
                logger.info('duplicate offers not allowed in an exchange; %s',
                            offerid)
                raise InvalidTransactionError("Duplicate offers not allowed")
            offermap.add(offerid)

        # and finally build the adjustment lists to make sure that all of the
        # adjustments are valid
        if not self.build_adjustment_list(store):
            logger.warn('failed to build the adjustment list')
            raise InvalidTransactionError(
                "Failed to build the adjustment list")
Exemplo n.º 26
0
 def _is_winner(self, hand_a, hand_b):
     resolutions = (
         ('ROCK', 'ROCK', 'TIE'),
         ('ROCK', 'PAPER', 'LOSE'),
         ('ROCK', 'SCISSORS', 'WIN'),
         ('PAPER', 'PAPER', 'TIE'),
         ('PAPER', 'ROCK', 'WIN'),
         ('PAPER', 'SCISSORS', 'LOSE'),
         ('SCISSORS', 'SCISSORS', 'TIE'),
         ('SCISSORS', 'PAPER', 'WIN'),
         ('SCISSORS', 'ROCK', 'LOSE'),
     )
     for a, b, resolution in resolutions:
         if hand_a == a and hand_b == b:
             return resolution
     raise InvalidTransactionError(
         'no resolution found for hand_a: %s, hand_b: %s' %
         (hand_a, hand_b))
Exemplo n.º 27
0
    def check_valid(self, store, txn):
        if self._object_id not in store:
            raise InvalidTransactionError(
                "Object with id does not exist: {}".format(self._object_id))

        organization = store.get(self._object_id)
        try:
            participant = store.lookup('participant:key-id', txn.OriginatorID)
        except:
            raise InvalidTransactionError("Participant does not exist.")

        if participant["object-id"] != self._participant_id:
            if participant["object-id"] != organization["creator-id"]:
                raise InvalidTransactionError("Only the creator of the "
                                              "organization, or the "
                                              "participant themselves, "
                                              "may remove or add a "
                                              "participant to the "
                                              "Authorization list")

        if self._action == "add":
            if "authorization" in organization:
                for participant in organization["authorization"]:
                    if self._participant_id == participant["participant-id"]:
                        raise InvalidTransactionError(
                            "Participant is "
                            "already in the "
                            "authorization list: {}".format(
                                self._participant_id))

        is_in = False
        if self._action == "remove":
            if "authorization" in organization:
                for participant in organization["authorization"]:
                    if self._participant_id in participant["participant-id"]:
                        is_in = True
            if not is_in:
                raise InvalidTransactionError("Participant is not in the" +
                                              " authorization list")

        if self._role != "marketmaker" and self._role != "trader":
            raise InvalidTransactionError(
                "Role must be either " +
                "marketmaker or trader: {}".format(self._role))
Exemplo n.º 28
0
    def check_valid(self, store, txn):
        if txn.Identifier in store:
            raise InvalidTransactionError(
                "ObjectId already in store")

        if not market_place_object_update.global_is_valid_name(
                store, self._name, self.ObjectType, self._creator_id):
            raise InvalidTransactionError(
                "Name is not valid")

        if not market_place_object_update.global_is_permitted(
                store,
                txn,
                self._creator_id,
                self.CreatorType):
            raise InvalidTransactionError(
                "Creator Address not the same as txn.OriginatorID")

        if not account_update.AccountObject.is_valid_object(store,
                                                            self._account_id):
            raise InvalidTransactionError(
                "AccountId does not reference an Account")

        if not asset_type_update.AssetTypeObject.is_valid_object(
                store, self._asset_type_id):
            raise InvalidTransactionError(
                "AssetTypeid not a valid AssetType")

        if not participant_update.ParticipantObject.is_valid_object(
                store, self._guarantor_id):
            raise InvalidTransactionError(
                "GuarantorID not a valid Participant")

        if self._count < 0:
            raise InvalidTransactionError(
                "Count < 0")

        return True
Exemplo n.º 29
0
 def check_valid(self, store, txn):
     if not self.is_valid_name(store):
         raise InvalidTransactionError("Name, {}, is not valid".format(
             self._name))
Exemplo n.º 30
0
    def render_post(self, request, components, msg):
        """
        Do server-side session prevalidation.
        """
        session = request.getSession()
        if not session:
            raise \
                Error(http.BAD_REQUEST, 'Session has not been started')

        data = request.content.getvalue()
        msg = self._get_message(request)
        mymsg = copy.deepcopy(msg)

        if hasattr(mymsg, 'Transaction') and mymsg.Transaction is not None:
            mytxn = mymsg.Transaction
            LOGGER.info(
                'starting server-side prevalidation '
                'for txn id: %s type: %s', mytxn.Identifier,
                mytxn.TransactionTypeName)

            transaction_type = mytxn.TransactionTypeName

            temp_store_session = ITempTransactionTypeStore(session)
            temp_store_session.count += 1
            LOGGER.debug('visit %d times in the session.uid: %s',
                         temp_store_session.count, session.uid)

            if not temp_store_session.my_store:
                temp_store_map = self._get_store_map()
                if transaction_type not in temp_store_map.TransactionStores:
                    LOGGER.info('transaction type %s not in global store map',
                                transaction_type)
                    raise Error(
                        http.BAD_REQUEST, 'unable to prevalidate enclosed '
                        'transaction {0}'.format(data))

                tstore = temp_store_map.get_transaction_store(transaction_type)
                temp_store_session.my_store = tstore.clone_store()

            try:
                if not mytxn.is_valid(temp_store_session.my_store):
                    raise InvalidTransactionError('invalid transaction')

            except InvalidTransactionError as e:
                LOGGER.info(
                    'submitted transaction fails transaction '
                    'family validation check: %s; %s', request.path,
                    mymsg.dump())
                raise Error(
                    http.BAD_REQUEST,
                    'InvalidTransactionError: failed transaction '
                    'family validation check: {}'.format(str(e)))
            except:
                LOGGER.info('submitted transaction is '
                            'not valid %s; %s; %s', request.path, mymsg.dump(),
                            traceback.format_exc(20))
                raise Error(
                    http.BAD_REQUEST, 'enclosed transaction is not '
                    'valid {}'.format(data))

            LOGGER.info('transaction %s is valid', msg.Transaction.Identifier)
            mytxn.apply(temp_store_session.my_store)

        return msg