Beispiel #1
0
    def __init__(self, payload):

        actions = ['create-voter', 'create-voting', 'register-voter', 'unregister-voter', 'apply-voting-method', 'set-preferences', 'get-entity-info', 'get-all-info']
        print('ESTO ES EL PAYLOAD', payload)

        try:
            print(payload)
            print(payload.decode())
            # The payload is csv utf-8 encoded string
            action, name_id, configurations_preferences_id, sc_method = payload.decode().split(";")
        
        except ValueError:
            print('ESTO ES EL PAYLOAD', payload)

            raise InvalidTransaction("Invalid payload serialization {}, {}".format(payload, type(payload)))

        if not action:
            raise InvalidTransaction('Action is required')

        if action not in actions:
            raise InvalidTransaction('Invalid action: {}'.format(action))

        if not name_id:
            raise InvalidTransaction('Name of voting/id of voter is required')

        if '|' in name_id or ';' in name_id:
            raise InvalidTransaction('Name of voting/id of voter cannot contain "|" or ";" ')


        if action == 'create-voter':
            
            if not configurations_preferences_id:
                raise InvalidTransaction('Preferences of the voter are required')
            if not type(ast.literal_eval(configurations_preferences_id)) is dict:
                raise InvalidTransaction('Preferences must be a dictionary')

        elif action == 'create-voting':

            if not configurations_preferences_id:
                raise InvalidTransaction('Configurations to be voted are required')
            if not type(ast.literal_eval(configurations_preferences_id)) is list:
                raise InvalidTransaction('Configurations must be a list')
            
            if not sc_method:
                raise InvalidTransaction('Social choice method is required')


        elif action == 'register-voter':

            if not configurations_preferences_id:
                raise InvalidTransaction('Id of the voter is required')


        self._action = action
        self._name_id = name_id
        self._configurations_preferences_id = configurations_preferences_id
        self._sc_method = sc_method
Beispiel #2
0
def _validate_name(name):
    if not isinstance(name, str) or len(name) > MAX_NAME_LENGTH:
        raise InvalidTransaction(
            'Name must be a string of no more than {} characters'.format(
                MAX_NAME_LENGTH))
 def validate_input_holding_exists(self):
     if not self._receiver.target:
         raise InvalidTransaction(
             "Failed to accept offer, holding specified as target, {},"
             " does not exist".format(self._accept_offer.target))
Beispiel #4
0
    def apply(self, transaction: TpProcessRequest, context):
        LOGGER.debug('[apply] init header and signer')
        header = transaction.header
        signer = header.signer_public_key
        try:
            LOGGER.debug('[apply] create CaState, ApproveState, CaPayload')
            state = CaState(context=context,
                            namespace=self._namespace_prefix,
                            timeout=2)
            astate = ApproveState(context=context,
                                  namespace=self._namespace_prefix,
                                  timeout=2)
            # state.check_CA_cert()
            payload = CaPayload(payload=transaction.payload)

            if payload.action == 'init':
                state.init_CA_cert(date=payload.date,
                                   nonce=int(header.nonce, 0),
                                   spkey=payload.value,
                                   csr=payload.csr,
                                   signer=signer)
            elif payload.action == 'create':
                astate.add_csr_request(date=payload.date,
                                       nonce=int(header.nonce, 0),
                                       csr=payload.value,
                                       signer=signer)
            elif payload.action == 'list_approve':
                if state.admin == signer:
                    t_bytes = astate.get_list().encode()
                    event_name = "{}/list_approve".format(
                        self._namespace_prefix)
                    self._fire_event(context, event_name, {}, t_bytes)
            elif payload.action == 'list_my':
                lc = astate.get_my_certificate(signer).encode()
                event_name = "{}/list_my".format(self._namespace_prefix)
                self._fire_event(context, event_name,
                                 {"signer": "{}".format(signer)}.items(), lc)
            elif payload.action == 'approve':
                if state.admin == signer:
                    d, n, c = astate.approve(payload.serial)
                    cert_bytes, cert_serial = state.create_certificate(date=d,
                                                                       nonce=n,
                                                                       csr=c)
                    astate.save_certificate(payload.serial, cert_serial)

            elif payload.action == 'get':
                cert_bytes = state.get_certificate(payload.serial)
                event_name = "{}/get".format(self._namespace_prefix)
                self._fire_event(context, event_name,
                                 {"serial":
                                  "{}".format(payload.serial)}.items(),
                                 cert_bytes)
            elif payload.action == 'revoke':
                state.revoke_certificate(payload.serial)
                event_name = "{}/revoke".format(self._namespace_prefix)
                self._fire_event(context, event_name,
                                 {"serial":
                                  "{}".format(payload.serial)}.items())
            elif payload.action == 'status':
                status = state.check_status(payload.serial)
                event_name = "{}/status".format(self._namespace_prefix)
                self._fire_event(context, event_name,
                                 {"serial":
                                  "{}".format(payload.serial)}.items(),
                                 status.encode('utf-8'))
            else:
                raise InvalidTransaction("Transaction payload type unknown.")
        except InternalError as er:
            raise InvalidTransaction(str(er)) from er
        except BaseException as ex:
            raise InvalidTransaction(str(ex)) from ex
Beispiel #5
0
    def __init__(self, payload, transactionCreator):
        print("__init__ payload")
        try:
            data = json.loads(payload.decode('utf-8'))
        except ValueError:
            raise InvalidTransaction("Invalid payload serialization")

        operation = data.get('operation')
        if not operation:
            raise InvalidTransaction('Not operation, operation is required')
        if operation not in ('putOnSale', 'buy', 'createBuyPetition',
                             'satisfyBuyPetition', 'editSale', 'deleteSale',
                             'editBuyPetition', 'deleteBuyPetition'):
            raise InvalidTransaction('Invalid operation: {}'.format(operation))

        #Common section
        kwhAmountSell = data.get('kwhAmountSell')
        pricePerKwh = data.get('pricePerKwh')
        createWritedate = data.get('createWritedate')
        validWritedate = data.get('validWritedate')
        elementID = data.get('elementID')

        # Sell section
        if operation == 'putOnSale' or operation == 'editSale' or operation == 'deleteSale':

            sellerPubKey = transactionCreator

            if operation == 'putOnSale' or operation == 'editSale':
                #Validate that the amount to sell is not null, or anything different from a positive int
                if not kwhAmountSell:
                    raise InvalidTransaction('Amount to sell is required')
                if not kwhAmountSell.isdigit() or kwhAmountSell == "0":
                    raise InvalidTransaction(
                        'Amount to sell must be a positive integer number')
            if operation == 'editSale' or operation == 'deleteSale':
                sellerPubKey = data.get('sellerPubKey')

            if not sellerPubKey:
                raise InvalidTransaction('A seller is required to sell')

            self._sellerPubKey = sellerPubKey

            #Validate that the amount to sell is not null, or anything different from a positive decimal
            if not pricePerKwh:
                raise InvalidTransaction('Price per kwh is required')
            if not pricePerKwh.replace('.', '',
                                       1).isdigit() or pricePerKwh == "0":
                raise InvalidTransaction(
                    'Price per kwh must be a positive number')

            #Validate creation date not null
            if not createWritedate:
                raise InvalidTransaction(
                    'Date of creation of sale is required')
            #Validate creation date format
            print(" Creation dat is === ", createWritedate)
            try:
                datetime.strptime(createWritedate, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise InvalidTransaction(
                    "Incorrect data format, creation Date should be YYYY-MM-DD hh:mm:ss"
                )

            #Validate validity date not null
            if not validWritedate:
                raise InvalidTransaction('Date limit of sale is required')
            #Validate valid date format
            try:
                datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise InvalidTransaction(
                    "Incorrect data format, validity Date should be YYYY-MM-DD hh:mm:ss"
                )
            # Validate valid date after creation date
            createDate = datetime.strptime(createWritedate,
                                           '%Y-%m-%d %H:%M:%S')
            validDate = datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            if validDate < createDate:
                raise InvalidTransaction(
                    "Validity date can't be earlier than creation date")

            if not elementID:
                raise InvalidTransaction('Sale id (elementID) is required')

            self._operation = operation
            self._kwhAmountSell = kwhAmountSell
            self._pricePerKwh = pricePerKwh
            self._createWritedate = createWritedate
            self._validWritedate = validWritedate
            self._elementID = elementID

        # create Buy Petition section
        elif operation == 'createBuyPetition' or operation == 'editBuyPetition' or operation == 'deleteBuyPetition':

            sellerPubKey = transactionCreator

            if operation == 'createBuyPetition' or operation == 'editBuyPetition':
                #Validate that the amount to sell is not null, or anything different from a positive int
                if not kwhAmountSell:
                    raise InvalidTransaction('Solicited amount is required')
                if not kwhAmountSell.isdigit() or kwhAmountSell == "0":
                    raise InvalidTransaction(
                        'Solicited amount must be a positive integer number')
            if operation == 'editBuyPetition' or operation == 'deleteBuyPetition':
                sellerPubKey = data.get('sellerPubKey')

            if not sellerPubKey:
                raise InvalidTransaction(
                    'A creator is required to create buy petition')

            self._sellerPubKey = sellerPubKey

            #Validate that the amount to sell is not null, or anything different from a positive decimal
            if not pricePerKwh:
                raise InvalidTransaction('Price per kwh is required')
            if not pricePerKwh.replace('.', '',
                                       1).isdigit() or pricePerKwh == "0":
                raise InvalidTransaction(
                    'Price per kwh must be a positive number')

            #Validate creation date not null
            if not createWritedate:
                raise InvalidTransaction(
                    'Date of creation of petition is required')
            #Validate creation date format
            try:
                datetime.strptime(createWritedate, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise InvalidTransaction(
                    "Incorrect data format, creation Date should be YYYY-MM-DD hh:mm:ss"
                )

            #Validate validity date not null
            if not validWritedate:
                raise InvalidTransaction('Date limit of petition is required')
            #Validate valid date format
            try:
                datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise InvalidTransaction(
                    "Incorrect data format, validity Date should be YYYY-MM-DD hh:mm:ss"
                )
            # Validate valid date after creation date
            createDate = datetime.strptime(createWritedate,
                                           '%Y-%m-%d %H:%M:%S')
            validDate = datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            if validDate < createDate:
                raise InvalidTransaction(
                    "Validity date can't be earlier than creation date")
            if not elementID:
                raise InvalidTransaction('Petition ID is required')

            self._operation = operation
            self._kwhAmountSell = kwhAmountSell
            self._pricePerKwh = pricePerKwh
            self._createWritedate = createWritedate
            self._validWritedate = validWritedate
            self._elementID = elementID

        # Buy section
        elif operation == "buy":
            sellerPubKey = data.get('sellerPubKey')
            kwhAmountBuy = data.get('kwhAmountBuy')
            buyWritedate = data.get('buyWritedate')
            elementID = data.get('elementID')
            counterpartID = data.get('counterpartID')
            buyerPubKey = transactionCreator

            if not kwhAmountBuy:
                raise InvalidTransaction('Amount to buy is required')
            if kwhAmountSell == "0":
                raise InvalidTransaction("Can't buy when no energy is offered")
            if int(kwhAmountBuy) > int(kwhAmountSell):
                raise InvalidTransaction(
                    "Can't buy more than the offered amount")
            if not sellerPubKey:
                raise InvalidTransaction(
                    'There is no seller in this transaction')
            if not kwhAmountBuy:
                raise InvalidTransaction('Amount to buy is required to buy')
            if not buyWritedate:
                raise InvalidTransaction('Date of buy is required to buy')
            if not elementID:
                raise InvalidTransaction('Sale id (elementID) required to buy')
            if not counterpartID:
                raise InvalidTransaction(
                    'Buy id (counterpartID) required to buy')
            if not buyerPubKey:
                raise InvalidTransaction('A buyer is required to buy')

            limitDate = datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            buyDate = datetime.strptime(buyWritedate, '%Y-%m-%d %H:%M:%S')
            if limitDate < buyDate:
                raise InvalidTransaction("Can't buy after validity date")
            self._operation = operation
            self._kwhAmountSell = kwhAmountSell
            self._pricePerKwh = pricePerKwh
            self._createWritedate = createWritedate
            self._validWritedate = validWritedate
            self._elementID = elementID
            self._sellerPubKey = sellerPubKey
            self._kwhAmountBuy = kwhAmountBuy
            self._buyWritedate = buyWritedate
            self._counterpartID = counterpartID
            self._buyerPubKey = buyerPubKey

        # Buy section
        elif operation == "satisfyBuyPetition":
            sellerPubKey = data.get('sellerPubKey')
            kwhAmountBuy = data.get('kwhAmountBuy')
            buyWritedate = data.get('buyWritedate')
            elementID = data.get('elementID')
            counterpartID = data.get('counterpartID')
            buyerPubKey = transactionCreator

            if not kwhAmountBuy:
                raise InvalidTransaction('Amount requested is required')
            if kwhAmountSell == "0":
                raise InvalidTransaction("The petition is already satisfied")
            if int(kwhAmountBuy) > int(kwhAmountSell):
                raise InvalidTransaction(
                    "Can't offer more than the requested amount")
            if not sellerPubKey:
                raise InvalidTransaction(
                    'There is no creator of Buy Petition in this transaction')
            if not kwhAmountBuy:
                raise InvalidTransaction('Amount to offer is required')
            if not buyWritedate:
                raise InvalidTransaction('Date is required to buy')
            if not elementID:
                raise InvalidTransaction('Buy Petition id required')
            if not counterpartID:
                raise InvalidTransaction(
                    'Satisfy Buy Petition id is required ')
            if not buyerPubKey:
                raise InvalidTransaction(
                    'A key is required to satisfy a buy petition')
            limitDate = datetime.strptime(validWritedate, '%Y-%m-%d %H:%M:%S')
            buyDate = datetime.strptime(buyWritedate, '%Y-%m-%d %H:%M:%S')
            if limitDate < buyDate:
                raise InvalidTransaction(
                    "Can't satisfy buy petition after validity date")
            self._operation = operation
            self._kwhAmountSell = kwhAmountSell
            self._pricePerKwh = pricePerKwh
            self._createWritedate = createWritedate
            self._validWritedate = validWritedate
            self._elementID = elementID
            self._sellerPubKey = sellerPubKey
            self._kwhAmountBuy = kwhAmountBuy
            self._buyWritedate = buyWritedate
            self._counterpartID = counterpartID
            self._buyerPubKey = buyerPubKey
Beispiel #6
0
    def _store_certificate(self, context, signer_pubkey, transaction_payload):
        address = self.make_address_from_data(
            transaction_payload.certificate_raw)
        data = get_data(context, CertificateStorage, address)
        if data:
            raise InvalidTransaction('This certificate is already registered.')

        certificate = x509.load_der_x509_certificate(
            bytes.fromhex(transaction_payload.certificate_raw),
            default_backend())
        certificate_pubkey = certificate.public_key()
        try:
            certificate_pubkey.verify(
                bytes.fromhex(transaction_payload.signature_crt),
                bytes.fromhex(transaction_payload.signature_rem),
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())
        except InvalidSignature:
            raise InvalidTransaction('signature_crt mismatch')

        crt_hash = hashlib.sha512(
            transaction_payload.certificate_raw.encode(
                'utf-8')).hexdigest().encode('utf-8')
        sawtooth_signing_ctx = Secp256k1Context()
        sawtooth_signing_pubkey = Secp256k1PublicKey.from_hex(signer_pubkey)
        sawtooth_signing_check_res = \
            sawtooth_signing_ctx.verify(transaction_payload.signature_rem,
                                        crt_hash,
                                        sawtooth_signing_pubkey)
        if not sawtooth_signing_check_res:
            raise InvalidTransaction(
                'signature_rem mismatch with signer key {}'.format(
                    signer_pubkey))

        subject = certificate.subject
        organization = subject.get_attributes_for_oid(
            NameOID.ORGANIZATION_NAME)[0].value
        uid = subject.get_attributes_for_oid(NameOID.USER_ID)[0].value
        valid_from = certificate.not_valid_before
        valid_until = certificate.not_valid_after

        if organization != CERT_ORGANIZATION:
            raise InvalidTransaction(
                'The organization name should be set to REMME. The actual name is {}'
                .format(organization))
        if uid != signer_pubkey:
            raise InvalidTransaction(
                'The certificate should be sent by its signer. Certificate signed by {}. '
                'Transaction sent by {}.'.format(uid, signer_pubkey))
        if subject != certificate.issuer:
            raise InvalidTransaction('Expecting a self-signed certificate.')
        if valid_until - valid_from > CERT_MAX_VALIDITY:
            raise InvalidTransaction(
                'The certificate validity exceeds the maximum value.')

        fingerprint = certificate.fingerprint(hashes.SHA512()).hex()[:64]
        data = CertificateStorage()
        data.hash = fingerprint
        data.owner = signer_pubkey
        data.revoked = False

        account_address, account = TokenHandler.get_account_by_pub_key(
            context, signer_pubkey)
        if account.balance < CERT_STORE_PRICE:
            raise InvalidTransaction(
                'Not enough tokens to register a new certificate. Current balance: {}'
                .format(account.balance))
        account.balance -= CERT_STORE_PRICE

        LOGGER.info(
            'Registered a new certificate on address {}. Fingerprint: {}'.
            format(address, fingerprint))

        return {address: data, account_address: account}
Beispiel #7
0
    def apply(self, transaction, context):
        # Extraction du header / signature de la transaction

        header = transaction.header
        signer = header.signer_public_key

        # Definition de la classe XoPayload ou dans le prochain exemple AssetsPayload

        xo_payload = XoPayload.from_bytes(transaction.payload)

        # Definition de la classe XoSTate   ou dans le prochain exemple AssetsState

        xo_state = XoState(context)

        # Gestion des actions dans la transaction

        if xo_payload.action == 'delete':

            game = xo_state.get_game(xo_payload.name)

            if game is None:
                raise InvalidTransaction('Invalid action: game does not exist')

            xo_state.delete_game(xo_payload.name)

        elif xo_payload.action == 'create':
            # Testing in the state if the payload name exists in state
            if xo_state.get_game(xo_payload.name) is not None:
                raise InvalidTransaction(
                    'Invalid action: Game already exists: {}'.format(
                        xo_payload.name))
            # Creation of new game
            game = Game(name=xo_payload.name,
                        board="-" * 9,
                        state="P1-NEXT",
                        player1="",
                        player2="")

            xo_state.set_game(xo_payload.name, game)
            #_display("Player {} created a game.".format(signer[:6]))
            print("Player {} created a game.".format(signer[:6]))
        elif xo_payload.action == 'take':
            # Récuperation du nom du jeu depuis le state
            game = xo_state.get_game(xo_payload.name)

            if game is None:
                raise InvalidTransaction(
                    'Invalid action: Take requires an existing game')

            if game.state in ('P1-WIN', 'P2-WIN', 'TIE'):
                raise InvalidTransaction('Invalid Action: Game has ended')

            if (game.player1 and game.state == 'P1-NEXT' and
                game.player1 != signer) or \
                    (game.player2 and game.state == 'P2-NEXT' and
                        game.player2 != signer):
                raise InvalidTransaction("Not this player's turn: {}".format(
                    signer[:6]))

            if game.board[xo_payload.space - 1] != '-':
                raise InvalidTransaction(
                    'Invalid Action: space {} already taken'.format(
                        xo_payload))

            if game.player1 == '':
                game.player1 = signer

            elif game.player2 == '':
                game.player2 = signer

            upd_board = _update_board(game.board, xo_payload.space, game.state)

            upd_game_state = _update_game_state(game.state, upd_board)

            game.board = upd_board
            game.state = upd_game_state

            xo_state.set_game(xo_payload.name, game)
            _display("Player {} takes space: {}\n\n".format(
                signer[:6], xo_payload.space) +
                     _game_data_to_str(game.board, game.state, game.player1,
                                       game.player2, xo_payload.name))

        else:
            raise InvalidTransaction('Unhandled action: {}'.format(
                xo_payload.action))
    def apply(self, transaction, context):

        header = transaction.header
        signer = header.signer_public_key

        xo_payload = XoPayload.from_bytes(transaction.payload)

        xo_state = XoState(context)

        if xo_payload.action == 'delete':
            game = xo_state.get_game(xo_payload.name)

            if game is None:
                raise InvalidTransaction(
                    'Invalid action: game does not exist')

            xo_state.delete_game(xo_payload.name)

        elif xo_payload.action == 'create':

            if xo_state.get_game(xo_payload.name) is not None:
                raise InvalidTransaction(
                    'Invalid action: Game already exists: {}'.format(
                        xo_payload.name))

            game = Game(name=xo_payload.name,
                        board="-" * 9,
                        state="P1-NEXT",
                        player1="",
                        player2="")

            xo_state.set_game(xo_payload.name, game)
            _display("Player {} created a game.".format(signer[:6]))

        elif xo_payload.action == 'take':
            game = xo_state.get_game(xo_payload.name)

            if game is None:
                raise InvalidTransaction(
                    'Invalid action: Take requires an existing game')

            if game.state in ('P1-WIN', 'P2-WIN', 'TIE'):
                raise InvalidTransaction('Invalid Action: Game has ended')

            if (game.player1 and game.state == 'P1-NEXT'
                and game.player1 != signer) or \
                    (game.player2 and game.state == 'P2-NEXT'
                     and game.player2 != signer):
                raise InvalidTransaction(
                    "Not this player's turn: {}".format(signer[:6]))

            if game.board[xo_payload.space - 1] != '-':
                raise InvalidTransaction(
                    'Invalid Action: space {} already taken'.format(
                        xo_payload))

            if game.player1 == '':
                game.player1 = signer

            elif game.player2 == '':
                game.player2 = signer

            upd_board = _update_board(game.board,
                                      xo_payload.space,
                                      game.state)

            upd_game_state = _update_game_state(game.state, upd_board)

            game.board = upd_board
            game.state = upd_game_state

            xo_state.set_game(xo_payload.name, game)
            _display(
                "Player {} takes space: {}\n\n".format(
                    signer[:6],
                    xo_payload.space)
                + _game_data_to_str(
                    game.board,
                    game.state,
                    game.player1,
                    game.player2,
                    xo_payload.name))

        else:
            raise InvalidTransaction('Unhandled action: {}'.format(
                xo_payload.action))
Beispiel #9
0
    def _getFromDistributer(self, context, distributerName, pharmacyName,
                            batchID, date, action):
        LOGGER.info("entering getFromDistributer")
        action = str(action)
        distributerAddress = getDistributerAddress(distributerName)
        pharmacyRequestAddress = getPharmacyAddress(pharmacyName, "request")
        pharmacyHasAddress = getPharmacyAddress(pharmacyName, "has")
        batchAddress = getBatchAddress(batchID)
        try:
            pharmacy = self._readData(context, PHARMACY_TABLE)
            distributers = self._readData(context, DISTRIBUTERS_TABLE)
            LOGGER.info('pharmacy: {}'.format(pharmacy))
            LOGGER.info('distributers: {}'.format(distributers))
            if pharmacyName in pharmacy and distributerName in distributers:
                pharmacyRequestMedicine = self._readData(
                    context, pharmacyRequestAddress)
                if batchID in pharmacyRequestMedicine:
                    pharmacyRequestMedicine.remove(batchID)
                    LOGGER.info(batchID +
                                'removed from request list of pharmacy')
                    if action == "Accept":
                        pharmacyHasMedicine = self._readData(
                            context, pharmacyHasAddress)
                        pharmacyHasMedicine.append(batchID)

                        tracking = self._readData(context, batchAddress)
                        tracking = [pharmacyName] + tracking

                        addresses = context.set_state({
                            pharmacyHasAddress:
                            self._encode_data(pharmacyHasMedicine),
                            pharmacyRequestAddress:
                            self._encode_data(pharmacyRequestMedicine),
                            batchAddress:
                            self._encode_data(tracking)
                        })
                        LOGGER.info(
                            batchID +
                            'added to has list of distributer and tracking updated'
                        )
                    elif action == "Reject":
                        distributerMedicine = self._readData(
                            context, distributerAddress)
                        distributerMedicine.append(batchID)

                        addresses = context.set_state({
                            distributerAddress:
                            self._encode_data(distributerMedicine),
                            pharmacyRequestAddress:
                            self._encode_data(pharmacyRequestMedicine)
                        })

                        LOGGER.info(batchID + 'added back to distributer')
                else:
                    raise Exception("batchid not in list")
            else:
                raise Exception("dist or pharma not in lists")
            #LOGGER.info('{} gave {} to {}'.format(manufacturerName, medicineDetails, distributerName))
        except TypeError as t:
            logging.debug('TypeError in _giveTo: {}'.format(t))
            raise InvalidTransaction('Type error')
        except InvalidTransaction as e:
            logging.debug('excecption: {}'.format(e))
            raise e
        except Exception as e:
            logging.debug('exception: {}'.format(e))
            raise InvalidTransaction('excecption: {}'.format(e))
Beispiel #10
0
    def apply(self, transaction, context):
        '''This implements the apply function for the TransactionHandler class.
        '''
        LOGGER.info('starting apply function')
        try:
            payload_list = self._unpack_transaction(transaction)
            LOGGER.info('payload: {}'.format(payload_list))
            action = payload_list[0]
            try:
                if action == "addManufacturer":
                    manufacturerName = payload_list[1]
                    self._addManufacturer(context, manufacturerName)
                elif action == "addDistributor":
                    distributerName = payload_list[1]
                    self._addDistributer(context, distributerName)
                elif action == "addPharmacy":
                    pharmacyName = payload_list[1]
                    self._addPharmacy(context, pharmacyName)
            #l = [manufacturerName, medicineName, batchID, manufactureDate, expiryDate]
                elif action == "manufacture":
                    [
                        manufacturerName, medicineName, batchID,
                        manufactureDate, expiryDate
                    ] = payload_list[1:]
                    # manufacturerName = payload_list[1]
                    # medicineName = payload_list[2]
                    # batchid = pa
                    # medicineDetails = payload_list[3:7]
                    self._manufacture(context, manufacturerName, medicineName,
                                      batchID, manufactureDate, expiryDate)

                elif action == "giveTo":
                    manufacturerName = payload_list[1]
                    distributerName = payload_list[2]
                    self._giveTo(context, manufacturerName, distributerName,
                                 medicineName)
                    action = payload_list[0]

                elif action == "giveToDistributer":
                    manufacturerName = payload_list[1]
                    distributerName = payload_list[2]
                    batchid = payload_list[3]
                    date = payload_list[4]
                    # medicineDetails = payload_list[3:7]
                    self._giveToDistributer(context, manufacturerName,
                                            distributerName, batchid, date)

        # l = [distributer, pharmacy, batchID, date]
                elif action == "giveToPharmacy":
                    distributerName = payload_list[1]
                    pharmacyName = payload_list[2]
                    batchID = payload_list[3]
                    date = payload_list[4]
                    self._giveToPharmacy(context, distributerName,
                                         pharmacyName, batchID, date)
                    action = payload_list[0]

                # l = [manufacturerName, distributer, batchID, date, action]
                elif action == "getFromManufacturer":
                    manufacturerName = payload_list[1]
                    distributerName = payload_list[2]
                    batchID = payload_list[3]
                    date = payload_list[4]
                    action = payload_list[5]
                    self._getFromManufacturer(context, manufacturerName,
                                              distributerName, batchID, date,
                                              action)

        # l = [distributer, pharmacy, batchID, date, action]
                elif action == "getFromDistributer":
                    ditributerName = payload_list[1]
                    pharmacyName = payload_list[2]
                    batchID = payload_list[3]
                    date = payload_list[4]
                    action = payload_list[5]
                    self._getFromDistributer(context, ditributerName,
                                             pharmacyName, batchID, date,
                                             action)
                else:
                    LOGGER.debug("Unhandled action: " + action)
            except IndexError as i:
                LOGGER.debug('IndexError: {}'.format(i))
                raise Exception()
        except Exception as e:
            raise InvalidTransaction("Error: {}".format(e))
Beispiel #11
0
    def _getFromManufacturer(self, context, manufacturerName, distributerName,
                             batchID, date, action):
        LOGGER.info("entering getFromManufacturer")
        action = str(action)
        manufacturerAddress = getManufacturerAddress(manufacturerName)
        distributerRequestAddress = getDistributerAddress(
            distributerName, "request")
        distributerHasAddress = getDistributerAddress(distributerName, "has")
        batchAddress = getBatchAddress(batchID)
        try:
            manufacturers = self._readData(context, MANUFACTURERS_TABLE)
            distributers = self._readData(context, DISTRIBUTERS_TABLE)
            LOGGER.info('manufacturers: {}'.format(manufacturers))
            LOGGER.info('distributers: {}'.format(distributers))
            if manufacturerName in manufacturers and distributerName in distributers:
                distributerRequestMedicine = self._readData(
                    context, distributerRequestAddress)
                if batchID in distributerRequestMedicine:
                    distributerRequestMedicine.remove(batchID)
                    LOGGER.info(batchID +
                                'removed from request list of distributer')
                    if action == "Accept":
                        distributerHasMedicine = self._readData(
                            context, distributerHasAddress)
                        distributerHasMedicine.append(batchID)

                        tracking = self._readData(context, batchAddress)
                        tracking = [distributerName] + tracking

                        addresses = context.set_state({
                            distributerHasAddress:
                            self._encode_data(distributerHasMedicine),
                            distributerRequestAddress:
                            self._encode_data(distributerRequestMedicine),
                            batchAddress:
                            self._encode_data(tracking)
                        })
                        LOGGER.info(
                            batchID +
                            'added to has list of distributer and tracking updated'
                        )
                    elif action == "Reject":
                        manufacturerMedicine = self._readData(
                            context, manufacturerAddress)
                        manufacturerMedicine.append(batchID)

                        addresses = context.set_state({
                            manufacturerAddress:
                            self._encode_data(manufacturerMedicine),
                            distributerRequestAddress:
                            self._encode_data(distributerRequestMedicine)
                        })

                        LOGGER.info(batchID + 'added back to manufacturer')
                else:
                    raise Exception("batchid not in medicine list")
            else:
                raise Exception("manu or dist not in lists")
            #LOGGER.info('{} gave {} to {}'.format(manufacturerName, medicineDetails, distributerName))
        except TypeError as t:
            logging.debug('TypeError in _giveTo: {}'.format(t))
            raise InvalidTransaction('Type error')
        except InvalidTransaction as e:
            logging.debug('excecption: {}'.format(e))
            raise e
        except Exception as e:
            logging.debug('exception: {}'.format(e))
            raise InvalidTransaction('excecption: {}'.format(e))
 def validate_exchange_once(self):
     if _exchange_once(self._offer):
         if self._state.offer_has_receipt(offer_id=self._offer.id):
             raise InvalidTransaction(
                 "Failed to accept offer, offer has already been accepted "
                 "and EXCHANGE ONCE is set.")
 def validate_input_holding_assets(self):
     if not self._offerer.source.asset == self._receiver.target.asset:
         raise InvalidTransaction(
             "Failed to accept offer, expected Holding asset {}, got "
             "asset {}".format(self._offerer.source.asset,
                               self._receiver.target.asset))
Beispiel #14
0
def _validate_value(value):
    if not isinstance(value, int) or value < 0 or value > MAX_VALUE:
        raise InvalidTransaction(
            'Value must be an integer '
            'no less than {i} and no greater than {a}'.format(i=MIN_VALUE,
                                                              a=MAX_VALUE))
Beispiel #15
0
    def apply(self, transaction, context):
        try:

            _display("i'm inside handler _display")
            print("i'm inside handler print")

            header = transaction.header
            signer = header.signer_public_key
            LOGGER.debug("signer_public_key: " + str(signer))
            LOGGER.debug("transaction payload: " + str(transaction.payload))
            payload = EHRPayload(payload=transaction.payload)

            state = EHRState(context)

            if payload.is_create_hospital():
                hospital = payload.create_hospital()

                hp = state.get_hospital(signer)
                if hp is not None:
                    raise InvalidTransaction(
                        'Invalid action: Hospital already exists: ' + hospital.name)

                state.create_hospital(hospital)
            elif payload.is_create_investigator():
                investigator = payload.create_investigator()

                dp = state.get_investigator(investigator.public_key)
                if dp is not None:
                    raise InvalidTransaction(
                        'Invalid action: Investigator already exists: ' + investigator.name)

                state.create_investigator(investigator)
            elif payload.is_create_patient():
                patient = payload.create_patient()

                pat = state.get_patient(signer)
                if pat is not None:
                    raise InvalidTransaction(
                        'Invalid action: Patient already exists: ' + patient.name)

                state.create_patient(patient)
            # elif healthcare_payload.is_create_lab():
            #     lab = healthcare_payload.create_lab()
            #
            #     lb = healthcare_state.get_lab(signer)
            #     if lb is not None:
            #         raise InvalidTransaction(
            #             'Invalid action: Lab already exists: ' + lb.name)
            #
            #     healthcare_state.create_lab(lab)
            # elif healthcare_payload.is_create_claim():
            #
            #     claim = healthcare_payload.create_claim()
            #     cl = healthcare_state.get_claim2(claim.id)
            #     if cl is not None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim already exist: ' + cl.id)
            #
            #     healthcare_state.create_claim(claim)
            # elif healthcare_payload.is_close_claim():
            #
            #     claim = healthcare_payload.close_claim()
            #     original_claim = healthcare_state.get_claim2(claim.id)
            #     if original_claim is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + claim.id)
            #     if original_claim.state == Claim.CLOSED:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim already closed: ' + claim.id)
            #     original_claim.provided_service = claim.provided_service
            #     original_claim.state = Claim.CLOSED
            #     healthcare_state.close_claim(original_claim)
            # elif healthcare_payload.is_update_claim():
            #
            #     claim = healthcare_payload.update_claim()
            #     original_claim = healthcare_state.get_claim2(claim.id)
            #     if original_claim is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + claim.id)
            #     if original_claim.state == Claim.CLOSED:
            #         raise InvalidTransaction(
            #             'Invalid action: Can not update closed claim: ' + claim.id)
            #     original_claim.provided_service = claim.provided_service
            #     # original_claim.state = Claim.CLOSED
            #     healthcare_state.update_claim(original_claim)
            # elif healthcare_payload.is_assign_doctor():
            #     assign = healthcare_payload.assign_doctor()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(assign.claim_id, assign.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + assign.claim_id + '; clinic: ' + clinic.public_key)
            #
            #     healthcare_state.assign_doctor(assign.claim_id, assign.clinic_pkey, assign.description,
            #                                    assign.event_time)
            # elif healthcare_payload.is_first_visit():
            #     visit = healthcare_payload.first_visit()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(visit.claim_id, visit.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + visit.claim_id)
            #
            #     healthcare_state.first_visit(visit.claim_id, visit.clinic_pkey,
            #                                  visit.description, visit.event_time)
            # elif healthcare_payload.is_pass_tests():
            #     tests = healthcare_payload.pass_tests()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(tests.claim_id, tests.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + tests.claim_id)
            #
            #     healthcare_state.pass_tests(tests.claim_id, tests.clinic_pkey, tests.description, tests.event_time)
            # elif healthcare_payload.is_attend_procedures():
            #     procedures = healthcare_payload.attend_procedures()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(procedures.claim_id, procedures.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + procedures.claim_id)
            #
            # healthcare_state.attend_procedures(procedures.claim_id, procedures.clinic_pkey, procedures.description,
            # procedures.event_time) elif healthcare_payload.is_eat_pills(): pills = healthcare_payload.eat_pills()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(pills.claim_id, pills.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + pills.claim_id)
            #
            #     healthcare_state.eat_pills(pills.claim_id, pills.clinic_pkey, pills.description,
            #                                pills.event_time)
            # elif healthcare_payload.is_next_visit():
            #     examination = healthcare_payload.next_visit()
            #
            #     clinic = healthcare_state.get_clinic(signer)
            #     if clinic is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Clinic does not exist: ' + signer)
            #
            #     cl = healthcare_state.get_claim(examination.claim_id, examination.clinic_pkey)
            #     if cl is None:
            #         raise InvalidTransaction(
            #             'Invalid action: Claim does not exist: ' + examination.claim_id)
            #
            #     healthcare_state.next_visit(examination.claim_id, examination.clinic_pkey,
            #                                 examination.description,
            #                                 examination.event_time)
            # elif healthcare_payload.is_lab_test():
            #     lab_test = healthcare_payload.lab_test()
            #
            #     # clinic = healthcare_state.get_clinic(signer)
            #     # if clinic is None:
            #     #     raise InvalidTransaction(
            #     #         'Invalid action: Clinic does not exist: ' + signer)
            #
            #     # healthcare_state.add_lab_test(signer, lab_test.height, lab_test.weight, lab_test.gender,
            #     #                               lab_test.a_g_ratio, lab_test.albumin, lab_test.alkaline_phosphatase,
            #     #                               lab_test.appearance, lab_test.bilirubin, lab_test.casts,
            #     #                               lab_test.color, lab_test.event_time)
            #     healthcare_state.add_lab_test(lab_test)
            elif payload.is_create_ehr():
                ehr = payload.create_ehr()

                # patient = healthcare_state.get_patient(signer)
                # if patient is None:
                #     raise InvalidTransaction(
                #         'Invalid action: Patient does not exist: ' + signer)

                state.create_ehr(signer, ehr)
            elif payload.is_import_data():
                data = payload.import_data()
                state.import_data(signer, data)
            elif payload.is_set_eligible():
                data = payload.set_eligible()
                state.set_eligible(data)
            elif payload.is_update_data():
                data = payload.update_data()
                state.update_data(data)
            else:
                raise InvalidTransaction('Unhandled action: {}'.format(payload.transaction_type()))
        except Exception as e:
            print("Error: {}".format(e))
            logging.exception(e)
            raise InvalidTransaction(repr(e))
Beispiel #16
0
    def apply(self, transaction, context):
        """
        Applys the payload from transaction onto the state storage.
        
        Args:
            transaction (Transaction): The transaction pertaining the payload
            context (State): The current state of the ledger
            
        Returns:
            type: State
            The new state of the ledger, which includes the data from the
            transaction, is returned to be stored on the state storage.
        
        Raises:
            InvalidTransaction:
                * If deserialization for payload from transaction failed
                * If "create" was called on non-unique uuid
                * If "amend" was called on non-existing uuid
                * If "Add..." were called on non-existing uuid
                * If invalid operation was called
            InternalError:
                * If deserialization of State.data failed
            
        """
        
        # Parsing required fields from transaction payload
        try:
            payload = json.loads(transaction.payload.decode())
            org_id      = payload["uuid"]
            org_alias   = payload["alias"]
            org_name    = payload["name"]
            org_type    = payload["type"]
            description = payload["description"]
            org_url     = payload["url"]
            action      = payload["action"]
            prev        = payload["prev_block"]
            cur         = payload["cur_block"]
            timestamp   = payload["timestamp"]
            pt_id       = payload["pt_list"]
            
        except ValueError:
            raise InvalidTransaction("Invalid payload serialization")
        
        # Soft sanity check and loading required data
        validate_transaction(org_id, action)
        data_address = make_organization_address(self._namespace_prefix, org_id)
        state_entries = context.get_state([data_address])
        
        # Hard sanity check before creating final payload for the state storage
        if len(state_entries) != 0:
            try:

                stored_organization = json.loads(state_entries[0].data.decode())
                stored_organization_id = stored_organization["uuid"]
                
            except ValueError:
                raise InternalError("Failed to deserialize data.")
            
        else:
            stored_organization_id = stored_organization = None
            
        if action == "create" and stored_organization_id is not None:
            raise InvalidTransaction(
                        "Invalid Action-organization already exists."
                    )
        elif action == "create":
            organization = create_organization(org_id, org_alias, org_name, 
                                org_type, description, org_url, prev, cur, 
                                timestamp)
            _display("Created an organization.")
        elif action == "amend" and stored_organization_id is not None:
            organization = create_organization(org_id, org_alias, org_name, 
                                org_type, description, org_url, prev, cur, 
                                timestamp, pt_id)
            _display("Amended an organization.")
        elif action == "AddPart" and stored_organization_id is not None:
            organization = create_organization(org_id, org_alias, org_name, 
                                org_type, description, org_url, prev, cur, 
                                timestamp, pt_id)
        
        # Adding the final payload to the state storage   
        data = json.dumps(organization).encode()
        addresses = context.set_state({data_address:data})
        
        return addresses
Beispiel #17
0
def validate_role_rel_proposal(header,
                               propose,
                               rel_address,
                               state,
                               is_remove=False):
    """Validates that the User exists, the Role exists, and the User is not
    in the Role's relationship specified by rel_address.

    Args:
        header (TransactionHeader): The transaction header.
        propose (ProposeAddRole_____): The role relationship proposal.
        rel_address (str): The Role relationship address produced by the Role
            and the User.
        state (sawtooth_sdk.Context): The way to communicate to the validator
            the state gets and sets.

    Returns:
        (dict of addresses)
    """

    user_address = addresser.user.address(propose.user_id)
    role_address = addresser.role.address(propose.role_id)
    proposal_address = addresser.proposal.address(object_id=propose.role_id,
                                                  target_id=propose.user_id)

    state_entries = state_accessor.get_state(
        state, [user_address, role_address, proposal_address, rel_address])
    user_validator.validate_identifier_is_user(state_entries,
                                               identifier=propose.user_id,
                                               address=user_address)
    user_entry = state_accessor.get_state_entry(state_entries, user_address)
    user = message_accessor.get_user_from_container(
        message_accessor.get_user_container(user_entry), propose.user_id)

    if header.signer_public_key not in [user.user_id, user.manager_id]:
        raise InvalidTransaction(
            "Txn signer {} is not the user or the user's "
            "manager {}".format(header.signer_public_key,
                                [user.user_id, user.manager_id]))

    validate_identifier_is_role(state_entries,
                                identifier=propose.role_id,
                                address=role_address)

    try:
        role_admins_entry = state_accessor.get_state_entry(
            state_entries, rel_address)
        role_rel_container = message_accessor.get_role_rel_container(
            role_admins_entry)

        if (header.signer_public_key not in [
                user.user_id, user.manager_id
        ]) and (not message_accessor.is_in_role_rel_container(
                role_rel_container, propose.role_id, propose.user_id)):
            raise InvalidTransaction(
                "Txn signer {} is not the user or the user's "
                "manager {} nor the group owner / admin".format(
                    header.signer_public_key, [user.user_id, user.manager_id]))

        if (not is_remove) and message_accessor.is_in_role_rel_container(
                role_rel_container, propose.role_id, propose.user_id):
            raise InvalidTransaction("User {} is already in the Role {} "
                                     "relationship".format(
                                         propose.user_id, propose.role_id))
    except KeyError:
        # The role rel container doesn't exist so no role relationship exists
        pass

    return state_entries
Beispiel #18
0
    def apply(self, transaction, context):
        try:

            _display("i'm inside handler _display")
            print("i'm inside handler print")

            header = transaction.header
            signer = header.signer_public_key
            LOGGER.debug("signer_public_key: " + str(signer))
            LOGGER.debug("transaction payload: " + str(transaction.payload))
            healthcare_payload = HealthCarePayload(payload=transaction.payload)

            healthcare_state = HealthCareState(context)

            if healthcare_payload.is_create_clinic():
                clinic = healthcare_payload.create_clinic()

                cl = healthcare_state.get_clinic(signer)
                if cl is not None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic already exists: ' + clinic.name)

                healthcare_state.create_clinic(clinic)
            elif healthcare_payload.is_create_doctor():
                doctor = healthcare_payload.create_doctor()

                do = healthcare_state.get_doctor(doctor.public_key)
                if do is not None:
                    raise InvalidTransaction(
                        'Invalid action: Doctor already exists: ' + doctor.name)

                healthcare_state.create_doctor(doctor)
            elif healthcare_payload.is_create_patient():
                patient = healthcare_payload.create_patient()

                pat = healthcare_state.get_patient(signer)
                if pat is not None:
                    raise InvalidTransaction(
                        'Invalid action: Patient already exists: ' + patient.name)

                healthcare_state.create_patient(patient)
            elif healthcare_payload.is_create_lab():
                lab = healthcare_payload.create_lab()

                lb = healthcare_state.get_lab(signer)
                if lb is not None:
                    raise InvalidTransaction(
                        'Invalid action: Lab already exists: ' + lb.name)

                healthcare_state.create_lab(lab)
            elif healthcare_payload.is_create_claim():

                claim = healthcare_payload.create_claim()
                cl = healthcare_state.get_claim2(claim.id)
                if cl is not None:
                    raise InvalidTransaction(
                        'Invalid action: Claim already exist: ' + cl.id)

                healthcare_state.create_claim(claim)
            elif healthcare_payload.is_close_claim():

                claim = healthcare_payload.close_claim()
                original_claim = healthcare_state.get_claim2(claim.id)
                if original_claim is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + claim.id)
                if original_claim.state == Claim.CLOSED:
                    raise InvalidTransaction(
                        'Invalid action: Claim already closed: ' + claim.id)
                original_claim.provided_service = claim.provided_service
                original_claim.state = Claim.CLOSED
                healthcare_state.close_claim(original_claim)
            elif healthcare_payload.is_update_claim():

                claim = healthcare_payload.update_claim()
                original_claim = healthcare_state.get_claim2(claim.id)
                if original_claim is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + claim.id)
                if original_claim.state == Claim.CLOSED:
                    raise InvalidTransaction(
                        'Invalid action: Can not update closed claim: ' + claim.id)
                original_claim.provided_service = claim.provided_service
                # original_claim.state = Claim.CLOSED
                healthcare_state.update_claim(original_claim)
            elif healthcare_payload.is_assign_doctor():
                assign = healthcare_payload.assign_doctor()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(assign.claim_id, assign.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + assign.claim_id + '; clinic: ' + clinic.public_key)

                healthcare_state.assign_doctor(assign.claim_id, assign.clinic_pkey, assign.description,
                                               assign.event_time)
            elif healthcare_payload.is_first_visit():
                visit = healthcare_payload.first_visit()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(visit.claim_id, visit.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + visit.claim_id)

                healthcare_state.first_visit(visit.claim_id, visit.clinic_pkey,
                                             visit.description, visit.event_time)
            elif healthcare_payload.is_pass_tests():
                tests = healthcare_payload.pass_tests()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(tests.claim_id, tests.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + tests.claim_id)

                healthcare_state.pass_tests(tests.claim_id, tests.clinic_pkey, tests.description, tests.event_time)
            elif healthcare_payload.is_attend_procedures():
                procedures = healthcare_payload.attend_procedures()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(procedures.claim_id, procedures.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + procedures.claim_id)

                healthcare_state.attend_procedures(procedures.claim_id, procedures.clinic_pkey, procedures.description,
                                                   procedures.event_time)
            elif healthcare_payload.is_eat_pills():
                pills = healthcare_payload.eat_pills()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(pills.claim_id, pills.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + pills.claim_id)

                healthcare_state.eat_pills(pills.claim_id, pills.clinic_pkey, pills.description,
                                           pills.event_time)
            elif healthcare_payload.is_next_visit():
                examination = healthcare_payload.next_visit()

                clinic = healthcare_state.get_clinic(signer)
                if clinic is None:
                    raise InvalidTransaction(
                        'Invalid action: Clinic does not exist: ' + signer)

                cl = healthcare_state.get_claim(examination.claim_id, examination.clinic_pkey)
                if cl is None:
                    raise InvalidTransaction(
                        'Invalid action: Claim does not exist: ' + examination.claim_id)

                healthcare_state.next_visit(examination.claim_id, examination.clinic_pkey,
                                            examination.description,
                                            examination.event_time)
            elif healthcare_payload.is_lab_test():
                lab_test = healthcare_payload.lab_test()

                # clinic = healthcare_state.get_clinic(signer)
                # if clinic is None:
                #     raise InvalidTransaction(
                #         'Invalid action: Clinic does not exist: ' + signer)

                # healthcare_state.add_lab_test(signer, lab_test.height, lab_test.weight, lab_test.gender,
                #                               lab_test.a_g_ratio, lab_test.albumin, lab_test.alkaline_phosphatase,
                #                               lab_test.appearance, lab_test.bilirubin, lab_test.casts,
                #                               lab_test.color, lab_test.event_time)
                healthcare_state.add_lab_test(lab_test)
            elif healthcare_payload.is_pulse():
                pulse = healthcare_payload.pulse()

                # patient = healthcare_state.get_patient(signer)
                # if patient is None:
                #     raise InvalidTransaction(
                #         'Invalid action: Patient does not exist: ' + signer)

                healthcare_state.add_pulse(pulse)
            else:
                raise InvalidTransaction('Unhandled action: {}'.format(healthcare_payload.transaction_type()))
        except Exception as e:
            print("Error: {}".format(e))
            logging.exception(e)
            raise InvalidTransaction(repr(e))
Beispiel #19
0
    def apply(self, transaction, context):

        header = transaction.header

        signer = header.signer_public_key

        hm_payload = HmPayload.from_bytes(transaction.payload)

        hm_state = HmState(context)

        if hm_payload.action == "create":
            # Game creation was requested
            LOGGER.debug("Action: create")
            game = hm_state.get_game(hm_payload.name)
            if game:
                raise InvalidTransaction("Game '{}' already exists".format(
                    hm_payload.name))
            game = Game(name=hm_payload.name,
                        word=hm_payload.guess,
                        misses="",
                        hits="",
                        host=signer,
                        guesser="",
                        state=GAME_STATE_ONGOING)
            hm_state.set_game(hm_payload.name, game)
            LOGGER.info("Player '{}' created game '{}'".format(
                signer, hm_payload.name))
        elif hm_payload.action == "delete":
            # Game deletion was requested
            LOGGER.debug("Action: delete")
            try:
                hm_state.delete_game(hm_payload.name)
                LOGGER.info("Player '{}' deleted game '{}'".format(
                    signer, hm_payload.name))
            except KeyError:
                raise InvalidTransaction("Game '{}' doesn't exist".format(
                    hm_payload.name))
        elif hm_payload.action == "guess":
            # Someone is guessing
            LOGGER.debug("Action: guess")
            guess = hm_payload.guess.lower()
            # Game doesn't exist
            game = hm_state.get_game(hm_payload.name)
            if not game:
                raise InvalidTransaction("Game '{}' doesn't exists".format(
                    hm_payload.name))
            # Game has ended
            if game.state != GAME_STATE_ONGOING:
                raise InvalidTransaction("Game '{}' has already ended".format(
                    hm_payload.name))
            # Guess already in hits
            if guess in game.hits:
                raise InvalidTransaction(
                    "You already guessed '{}' and it was successful".format(
                        guess))
            # Guess already in misses
            if guess in game.misses:
                raise InvalidTransaction(
                    "You already guessed '{}' and it was not successful".
                    format(guess))
            LOGGER.debug("Error handling completed")
            # Compute new game
            new_misses = game.misses + guess if guess not in game.word.lower(
            ) else game.misses
            new_hits = game.hits + guess if guess in game.word.lower(
            ) else game.hits
            if set(game.word.lower()) == set(new_hits):
                new_state = GAME_STATE_WON
            elif len(new_misses) >= MAX_GUESSES:
                new_state = GAME_STATE_LOST
            else:
                new_state = GAME_STATE_ONGOING
            new_game = Game(name=game.name,
                            word=game.word,
                            misses=new_misses,
                            hits=new_hits,
                            host=game.host,
                            guesser=game.guesser,
                            state=new_state)
            LOGGER.debug("New game computation completed")
            hm_state.set_game(hm_payload.name, new_game)
            LOGGER.info("""Game stats:
                Name: '{}'
                Word: '{}'
                Misses: '{}'
                Hits: '{}'
                Host: '{}'
                Guesser: '{}'
                State: '{}'
                """.format(game.name, game.word, new_misses, new_hits,
                           game.host, game.guesser, new_state))
        else:
            raise InvalidTransaction("Unknown action '{}'".format(
                hm_payload.action))
Beispiel #20
0
    def _store_pub_key(self, context, signer_pubkey, transaction_payload):
        address = self.make_address_from_data(transaction_payload.public_key)
        LOGGER.info('Pub key address {}'.format(address))
        data = get_data(context, PubKeyStorage, address)
        if data:
            raise InvalidTransaction('This pub key is already registered.')

        cert_signer_pubkey = load_pem_public_key(
            transaction_payload.public_key.encode('utf-8'),
            backend=default_backend())
        try:
            ehs_bytes = binascii.unhexlify(
                transaction_payload.entity_hash_signature)
            eh_bytes = binascii.unhexlify(transaction_payload.entity_hash)
        except binascii.Error:
            LOGGER.debug(
                f'entity_hash_signature {transaction_payload.entity_hash_signature}'
            )
            LOGGER.debug(f'entity_hash {transaction_payload.entity_hash}')
            raise InvalidTransaction(
                'Entity hash or signature not a hex format')

        # FIXME: For support PKCS1v15 and PSS
        LOGGER.warn('HAZARD: Detecting padding for verification')
        sigerr = 0
        pkcs = padding.PKCS1v15()
        pss = padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                          salt_length=padding.PSS.MAX_LENGTH)
        for _padding in (pkcs, pss):
            try:
                cert_signer_pubkey.verify(ehs_bytes, eh_bytes, _padding,
                                          hashes.SHA512())
                LOGGER.warn('HAZARD: Padding found: %s', _padding.name)
            except InvalidSignature:
                sigerr += 1

        if sigerr == 2:
            raise InvalidTransaction('Invalid signature')

        valid_from = datetime.fromtimestamp(transaction_payload.valid_from)
        valid_to = datetime.fromtimestamp(transaction_payload.valid_to)

        if valid_to - valid_from > PUB_KEY_MAX_VALIDITY:
            raise InvalidTransaction(
                'The public key validity exceeds the maximum value.')

        data = PubKeyStorage()
        data.owner = signer_pubkey
        data.payload.CopyFrom(transaction_payload)
        data.revoked = False

        account_address = AccountHandler.make_address_from_data(signer_pubkey)
        account = get_account_by_address(context, account_address)
        if ENABLE_ECONOMY:
            if account.balance < PUB_KEY_STORE_PRICE:
                raise InvalidTransaction(
                    'Not enough tokens to register a new pub key. Current balance: {}'
                    .format(account.balance))
            account.balance -= PUB_KEY_STORE_PRICE

        if address not in account.pub_keys:
            account.pub_keys.append(address)

        return {address: data, account_address: account}
Beispiel #21
0
    def apply(self, transaction, state_store):

        # Deserialize the transaction and verify it is valid
        pt_id, pt_name, checksum, version, src_uri, licensing, label, description, action, envelope_id, category_id, supplier_id, signer = extract_transaction(
            transaction)

        if pt_id == "":
            raise InvalidTransaction("part Data is required")

        if action == "":
            raise InvalidTransaction("Action is required")

        # Checks to see if the action is valid or not
        if action not in ("create", "list-part", "show-part", "AddEnvelope",
                          "AddCategory", "AddSupplier"):
            raise InvalidTransaction("Invalid Action '{}'".format(action))

        data_address = self._namespace_prefix \
            + hashlib.sha512(pt_id.encode("utf-8")).hexdigest()

        # Retrieve data from address
        state_entries = state_store.get([data_address])

        # Checks to see if the list is not empty
        if len(state_entries) != 0:
            try:

                stored_pt_id, stored_pt_str = \
                state_entries[0].data.decode().split(",",1)
                stored_pt = json.loads(stored_pt_str)
            except ValueError:
                raise InternalError("Failed to deserialize data.")

        else:
            stored_pt_id = stored_pt = None

        if action == "create" and stored_pt_id is not None:
            raise InvalidTransaction("Invalid Action-part already exists.")

        if action == "create":
            pt = create_part(pt_id, pt_name, checksum, version, src_uri,
                             licensing, label, description)
            stored_pt_id = pt_id
            stored_pt = pt
            _display("Created a part.")

        if action == "AddEnvelope":
            if envelope_id not in stored_pt_str:
                pt_env = add_envelope(envelope_id, stored_pt)
                stored_pt = pt_env

        if action == "AddSupplier":
            if supplier_id not in stored_pt_str:
                pt_supp = add_supplier(supplier_id, stored_pt)
                stored_pt = pt_supp

        if action == "AddCategory":
            if category_id not in stored_pt_str:
                pt_cat = add_category(category_id, stored_pt)
                stored_pt = pt_cat

        stored_pt_str = json.dumps(stored_pt)
        addresses = state_store.set([
            StateEntry(address=data_address,
                       data=",".join([stored_pt_id, stored_pt_str]).encode())
        ])

        if len(addresses) < 1:
            raise InternalError("State Error")
Beispiel #22
0
def _validate_verb(verb):
    if verb not in VALID_VERBS:
        raise InvalidTransaction('Verb must be "set", "inc", or "dec"')
 def validate_output_holding_exists(self):
     if self._offer.target and self._accept_offer.source:
         if self._offerer.target and not self._receiver.source:
             raise InvalidTransaction(
                 "Failed to accept offer, holding specified as source,{},"
                 " does not exist.".format(self._accept_offer.source))