Esempio n. 1
0
def test_wrong_request():
    request = PyledgerRequest()
    response = PyledgerResponse()
    request.request = 'blahblah'
    response.ParseFromString(handle_request(request.SerializeToString()))

    assert response.successful == False
    assert response.data == b'Request type blahblah not available'
def test_0_register_auth_contract():
    class AuthDigitalCurrency(SimpleContract):
        accounts = {}

        @method_allow(Permissions.ROOT)
        def add_account(self, key: str):
            if key in self.accounts:
                raise Exception('Account already exists')

            self.accounts[key] = 0.0
            return key

        @method_allow(Permissions.ROOT)
        def increment(self, key: str, quantity: float):
            if key not in self.accounts:
                raise Exception('Account not found')

            self.accounts[key] += quantity

        @method_allow(Permissions.USER)
        def transfer(self, source: str, dest: str, quantity: float):
            if source not in self.accounts:
                raise Exception('Source account not found')
            if dest not in self.accounts:
                raise Exception('Destination account not found')
            if self.accounts[source] < quantity:
                raise Exception('Not enough funds in source account')
            if quantity < 0:
                raise Exception('You cannot transfer negative currency')

            self.accounts[source] -= quantity
            self.accounts[dest] += quantity

        @method_allow(Permissions.USER)
        def balance(self, key: str):
            if key not in self.accounts:
                print(self.accounts)
                raise Exception('Account not found')

            return str(self.accounts[key])

    register_contract(AuthDigitalCurrency())

    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'call'
    request.contract = 'AuthDigitalCurrency'
    request.call = 'add_account'
    request.data = pickle.dumps({'key': 'new_account'})

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    assert response.successful == False
    assert response.data == b'Not enough permissions'
Esempio n. 3
0
def test_3_create_without_permissions():
    """
    Try to create a user without the permissions
    """
    request = PyledgerRequest()
    request.request = 'new_user'
    request.user = '******'
    request.password = '******'
    request.data = pickle.dumps(('user3', 'new_password'))

    response = PyledgerResponse()
    response.ParseFromString(handle_request(request.SerializeToString()))
    assert response.successful == False
    assert response.data == b'Not enough permissions'
Esempio n. 4
0
def test_call_method():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'call'
    request.contract = 'somecontract'
    request.call = 'somemethod'

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    assert response.successful == False
    assert response.data == b'Contract somecontract not available'
Esempio n. 5
0
def test_status():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'status'
    request.contract = 'DigitalCurrency'

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)
    status = pickle.loads(response.data)

    assert response.successful == True
    assert status == {'accounts': {}}
Esempio n. 6
0
def handle_response(bin_response, callback=None):
    response = PyledgerResponse()
    response.ParseFromString(bin_response)

    if response.successful:
        if callback:
            response_data = pickle.loads(response.data)
            print('Executing callback...')
            callback(response_data)
            return True, response_data
        else:
            return True, pickle.loads(response.data)

    else:
        return False, response.data.decode('utf-8')
Esempio n. 7
0
def test_exception():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'call'
    request.contract = 'DigitalCurrency'
    request.call = 'increment'
    request.data = pickle.dumps({'key': 'another_account', 'quantity': 100.0})

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    assert response.successful == False
    assert response.data == b"Exception in user function: Exception('Account not found',)"
Esempio n. 8
0
def test_contracts():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'contracts'

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    assert response.successful == True

    contracts = pickle.loads(response.data)

    assert set(contracts) == {'MyContract', 'DigitalCurrency'}
Esempio n. 9
0
def test_simple_call():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'call'
    request.contract = 'DigitalCurrency'
    request.call = 'add_account'
    request.data = pickle.dumps({'key': 'new_account'})

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    response_data = pickle.loads(response.data)

    assert response.successful == True
    assert response_data == response_data
Esempio n. 10
0
def test_master_session():
    """
    Get a master session key
    """
    request = PyledgerRequest()
    request.request = 'session'
    request.user = '******'
    request.password = '******'

    response = PyledgerResponse()
    response.ParseFromString(handle_request(request.SerializeToString()))

    assert response.successful == True

    session_key = response.data.decode('utf-8')
    session = Session.from_key(session_key)

    assert session.key == session_key
Esempio n. 11
0
def test_2_create_user():
    """
    Create a user from the API
    """
    request = PyledgerRequest()
    request.request = 'new_user'
    request.user = '******'
    request.password = '******'
    request.session_key = 'test_session'
    request.data = pickle.dumps(('user2', 'new_password'))

    response = PyledgerResponse()
    response.ParseFromString(handle_request(request.SerializeToString()))
    assert response.successful == True
    assert response.data == b'user2'

    user = User.from_name('user2')
    assert user.get_permissions() == Permissions.USER
    assert user.check_password('new_password')
def test_access_contract_as_root():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'call'
    request.contract = 'AuthDigitalCurrency'
    request.call = 'add_account'
    request.user = '******'
    request.password = '******'
    request.data = pickle.dumps({'key': 'new_account'})

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)

    assert response.successful == True

    response_data = pickle.loads(response.data)
    assert response_data == 'new_account'
Esempio n. 13
0
def test_api():
    request = PyledgerRequest()
    response = PyledgerResponse()

    request.request = 'api'
    request.contract = 'DigitalCurrency'

    byte_request = request.SerializeToString()
    byte_response = handle_request(byte_request)
    response.ParseFromString(byte_response)
    api = pickle.loads(response.data)

    assert response.successful == True
    assert api == {
        'add_account': {'key': str},
        'balance': {'key': str},
        'increment': {'key': str, 'quantity': float},
        'transfer': {'dest': str, 'quantity': float, 'source': str}
    }
Esempio n. 14
0
def handle_request(payload: bytes):
    """
    Handle a single request

    :param payload: Serialized PyledgerRequest message
    :return:
    """
    handler = Handler()
    message = PyledgerRequest()
    response = PyledgerResponse()

    try:
        message.ParseFromString(payload)
    except DecodeError:
        response.successful = False
        response.data = b'Message not properly formatted'
        return response.SerializeToString()

    if message.request not in handler_methods(handler):
        response.successful = False
        response.data = 'Request type {} not available'.format(
            message.request).encode()
        return response.SerializeToString()

    else:
        # Handle authentication
        if message.request in permissions_registry:
            user = User.from_name(message.user)
            permission_required = permissions_registry[message.request]

            if not user.check_password(message.password):
                response.successful = False
                response.data = b'Wrong user and/or password'
                return response.SerializeToString()

            if user.get_permissions().value > permission_required.value:
                response.successful = False
                response.data = b'Not enough permissions'
                return response.SerializeToString()

            session = Session.from_key(message.session_key)

            if not session:
                response.successful = False
                response.data = b'Session not available'
                return response.SerializeToString()

            if not session.user == user:
                response.successful = False
                response.data = b'Session not owned by this user'
                return response.SerializeToString()

            if session.until < datetime.datetime.now():
                response.successful = False
                response.data = b'Session expired, restart your client'
                return response.SerializeToString()

        # Select the function from the handler
        try:
            print('Handling message', message)
            successful, result = getattr(handler, message.request)(message)
        except Exception as exc:
            successful = False
            result = b'Exception in user function: ' + repr(exc).encode(
                'utf-8')

        response.successful = successful
        response.data = result
        return response.SerializeToString()
Esempio n. 15
0
def test_failed_message():
    response = PyledgerResponse()
    response.ParseFromString(handle_request(b'xxxyyy'))
    assert response.successful == False
    assert response.data == b'Message not properly formatted'