Exemplo n.º 1
0
def Main(operation, args):
    Log(args)

    trigger = GetTrigger()

    storage = StorageAPI()

    arg_error = 'Incorrect Arg Length'

    if trigger == Verification():
        # todo maybe implement later
        return True

    elif trigger == Application():
        if operation != None:
            if operation == "balance":
                if len(args) == 1:
                    account = args[0]
                    balance = storage.get(account)
                    return balance
                Log(arg_error)
                return arg_error
            if operation == "accrue":
                if len(args) == 2:
                    account = args[0],
                    gain = args[1]
                    new_balance = storage.get(account) + gain
                    return storage.put(account, new_balance)
                Log(arg_error)
            return arg_error
        return False
Exemplo n.º 2
0
def Main(a, b, c, d):
    """

    :param a:
    :param b:
    :param c:
    :param d:
    :return:
    """
    print("Executing Four Param Verification code")
    trigger = GetTrigger()

    if trigger == Verification():

        print("Running verification")
        is_owner = CheckWitness(OWNER)
        Notify(is_owner)
        return is_owner

    print("runnig app routine")

    result = a + b - c + d

    Notify(result)

    return result
Exemplo n.º 3
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():

        if CheckWitness(owner):
            return True

        return False

    storage = StorageAPI()

    questions = Questions()
    questions.owner = owner

    if operation == 'get_clue':
        addr = get_addr(clue_gas_req)
        cluenum = args[0]
        return questions.get_clue(storage, cluenum, addr)

    elif operation == 'set_clue':
        cluenum = args[0]
        clueval = args[1]
        return questions.set_clue(storage, cluenum, clueval)

    elif operation == 'set_answer':
        cluenum = args[0]
        answer = args[1]
        return questions.set_answer(storage, cluenum, answer)

    elif operation == 'submit_answer':
        addr = get_addr(answer_gas_req)
        if len(args) < 2:
            return b'Not enough arguments'
        cluenum = args[0]
        answer = args[1]
        return questions.submit_answer(storage, cluenum, answer, addr)

    elif operation == 'total_questions':
        return total_q

    elif operation == 'progress':
        addr = get_addr(progress_gas_req)
        key = concat('progress_', addr)
        return storage.getitem(key)

    elif operation == 'total_winners':
        return storage.getitem('total_winners')

    elif operation == 'first_place':
        return storage.getitem('first_place')

    elif operation == 'second_place':
        return storage.getitem('second_place')

    elif operation == 'third_place':
        return storage.getitem('third_place')

    return b'Method not found'
Exemplo n.º 4
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == b'\x00':

        print("doing verification")

        # always allow owner to withdraw
        # this should be changed
        # to not allow the owner to withdraw from
        # vins that are earmarked for others
        if CheckWitness(OWNER):
            return True
        else:

            # if it is not the owner, we need to verify a few things
            can_widthraw = CanWithdraw()

            return can_widthraw

    elif trigger == b'\x10':

        if operation == 'deposit':

            deposit = DepositNeo()
            return deposit

        elif operation == 'withdrawalRequest':

            withdrawable_txs = VerifyWithdrawalRequest(args)
            return withdrawable_txs

        elif operation == 'getPending':
            account = args[0]
            withdrawable_txs = GetPendingWithdrawal(account)
            return withdrawable_txs

        elif operation == 'clearPending':
            account = args[0]
            result = DeletePendingWithdrawal(account)
            return result

        elif operation == 'balanceOf':
            account = args[0]
            result = BalanceOf(account)
            return result

        else:

            return 'unknown operation'

    return False
Exemplo n.º 5
0
def Main(operation, args):
    trigger = GetTrigger()
    token = Token()

    if trigger == Verification:

        is_owner = CheckWitness(token.owner)
        if is_owner:
            return True

        attachments = get_asset_attachments()
        storage = StorageAPI()
        crowdsale = Crowdsale()

        return crowdsale.can_exchange(token, attachments, storage, True)

    elif trigger == Application:

        if operation != None:
            nep = NEP5Handler()

            for op in nep.get_methods():
                if operation == op:
                    return nep.handle_nep51(operation, args, token)

            if operation == 'deploy':
                return deploy(token)

            if operation == 'circulation':
                storage = StorageAPI()
                return token.get_circulation(storage)

            sale = Crowdsale()

            if operation == 'mintTokens':
                return sale.exchange(token)

            if operation == 'crowdsale_register':
                return sale.kyc_register(args, token)

            if operation == 'crowdsale_status':
                return sale.kyc_status(args)

            if operation == 'crowdsale_available':
                return token.crowdsale_available_amount()

            return 'unknown operation'

    return False
Exemplo n.º 6
0
def Main(operation):
    """
    :param operation: get or put
    :param args: optional arguments
    :return: Bool
    """

    trigger = GetTrigger()
    if trigger == Application:
        Log("trigger: Application")
        height = GetHeight()
        hdr = GetHeader(height)
        ts = GetTimestamp(hdr)
        Log(ts)
        return True
    return False
Exemplo n.º 7
0
def Main(operation):

    print('entered main, getting trigger')
    trigger = GetTrigger()
    print('got trigger')
    print(trigger)

    # current bug with Verification()
    if trigger == b'\x00':

        print("doing verification!")
        owner_len = len(OWNER)
        print('owner len has been found')
        if owner_len == 20:
            print('checking witness')
            res = CheckWitness(OWNER)
            print("owner verify result")
            print(res)
            return res

    # current bug with Verification()
    elif trigger == b'\x10':
        print('doing application')
        if operation == 'getTotal':
            print("Getting Time!")
            total = GetTotal()
            return total
        elif operation == 'timeLeft':
            print("Getting time left")
            time = TimeLeft()
            return time
        elif operation == 'deploy':
            print("Deploying contract")
            deploy = Deploy()
            return deploy
        elif operation == 'getEntries':
            print('Getting Entries')
            entries = GetEntries()
            return entries
        elif operation == 'pickWinner':
            print('Picking a winner')
            winner = PickWinner()
            return winner
        else:
            print('simulating gas transaction')
            entry = AddEntry()
            return entry
Exemplo n.º 8
0
def Main(operation, args, sender=None):

    trigger = GetTrigger()

    if trigger == Application():

        exchange = Exchange()
        """
            Standard Operations

            No Permissions Required
        """

        if operation == "depositFunds":
            return DepositFunds()

        elif operation == "distributeBetWinnings":
            return exchange.DistributeBetWinnings(args)

        elif operation == "processBetQueue":
            return exchange.ProcessBetQueue(args)
        """
            User Operations

            Requires Sender to be the User 
        """

        if operation == "placeBet":
            return exchange.PlaceBet(args, sender)

        elif operation == "cancelBet":
            return exchange.CancelBet(args, sender)
        """ 
            Admin Operations

            Requires Owner Permissions
        """

        admin = Admin()

        if operation == 'killAdmin':
            return False

        elif operation == 'initContract':
            return admin.InitialiseContract()

    return False
Exemplo n.º 9
0
def Main(operation, args):
    trigger = GetTrigger()
    OWNER = b'6b1410519d09f00bde5121bab0b56a6c916095b2'

    if trigger == Verification():

        print("doing verification!")
        owner_len = len(OWNER)

        if owner_len == 20:
            res = CheckWitness(OWNER)
            print("owner verify result")
            return res

    elif trigger == Application():
        if operation == 'name':
            n = Name()
            return n
    return False
Exemplo n.º 10
0
def Main(args):

    print("Do Withdraw Test")

    trigger = GetTrigger()

    if trigger == Verification():

        print("doing verification")

        return True

        # check to see if the withdrawer is the owner

        is_owner = CheckWitness(OWNER)

        # always allow owner to withdraw

        if is_owner:
            can_widthraw = CanClaimGas()
            return can_widthraw

        else:
            can_widthraw = CanWithdrawNeo()
            return can_widthraw

    elif trigger == Application():
        print("doing application")

        operation = args[0]

        if operation == 'hodl':
            print("Hodling engaged!")
            deposit = DepositNeo()

            return deposit

        elif operation == 'info':
            print("Info requested")
            return Description()

    return False
Exemplo n.º 11
0
def Main():
    """

    :return:
    """
    trigger = GetTrigger()

    Notify(trigger)

    if trigger == Application():
        print("application!")

    elif trigger == Verification():
        print("verification!")

    k = 10

    print("hello")

    return k
Exemplo n.º 12
0
def Main(bytes):

    trigger = GetTrigger()

    if trigger == Verification():
        print("Verification!")
        return False

    elif trigger == Application():
        print("Application!")
        i = 0
        l = len(bytes)
        while i < l:
            c = substr(bytes, i, 1)
            i = i + 1
            if c == 0:
                print("Null")
            else:
                print("Not null")
                return True
Exemplo n.º 13
0
def Main(operation, args):
    trigger = GetTrigger()

    if trigger == Verification:
        print("doing verification!")
        Notify("doing verification notify!")

        # is_owner = CheckWitness(OWNER)
        # if is_owner:
        #     return True

        # Check that at least 1 GAS is attached
        attachment = get_asset_attachments()
        if attachment.gas_attached >= 1:
            return True
        return False

    elif trigger == Application:
        print("doing application!")

    return 1
Exemplo n.º 14
0
def Main(a):

    trigger = GetTrigger()

    if trigger == Verification():

        if not CheckWitness(owner):

            print("not owner!!")
            return False

        return True

    elif trigger == Application():

        print("do some other thing")

        m = 3

        j = a + m

        return j

    return 3
Exemplo n.º 15
0
def Main(operation, args):
    """
    This is the main entry point for the Smart Contract

    :param operation: the operation to be performed ( eg `balanceOf`, `transfer`, etc)
    :type operation: str

    :param args: an optional list of arguments
    :type args: list

    :return: indicating the successful execution of the smart contract
    :rtype: bool
    """

    # The trigger determines whether this smart contract is being
    # run in 'verification' mode or 'application'

    trigger = GetTrigger()

    # 'Verification' mode is used when trying to spend assets ( eg NEO, Gas)
    # on behalf of this contract's address
    if trigger == Verification():

        # if the script that sent this is the owner
        # we allow the spend
        is_owner = CheckWitness(OWNER)

        if is_owner:

            return True

        return False

    # 'Application' mode is the main body of the smart contract
    elif trigger == Application():

        if operation == 'name':
            n = TOKEN_NAME
            return n

        elif operation == 'decimals':
            d = DECIMALS
            return d

        elif operation == 'symbol':
            sym = SYMBOL
            return sym

        elif operation == 'totalSupply':
            supply = TOTAL_SUPPLY
            return supply

        elif operation == 'balanceOf':
            if len(args) == 1:
                account = args[0]
                balance = BalanceOf(account)
                return balance
            return 0

        elif operation == 'transfer':
            if len(args) == 3:
                t_from = args[0]
                t_to = args[1]
                t_amount = args[2]
                transfer = DoTransfer(t_from, t_to, t_amount)
                return transfer
            else:
                return False

        elif operation == 'transferFrom':
            if len(args) == 3:
                t_from = args[0]
                t_to = args[1]
                t_amount = args[2]
                transfer = DoTransferFrom(t_from, t_to, t_amount)
                return transfer
            return False

        elif operation == 'approve':
            if len(args) == 3:
                t_owner = args[0]
                t_spender = args[1]
                t_amount = args[2]
                approve = DoApprove(t_owner, t_spender, t_amount)
                return approve
            return False

        elif operation == 'allowance':
            if len(args) == 2:
                t_owner = args[0]
                t_spender = args[1]
                amount = GetAllowance(t_owner, t_spender)
                return amount
            return False

        # The following method is not a part of the NEP5 Standard
        # But is used to 'mint' the original tokens
        elif operation == 'deploy':
            result = Deploy()
            return result

        result = 'unknown operation'

        return result

    return False
Exemplo n.º 16
0
def Main(operation, args):
    """
    :param operation
    :param args: optional arguments (up to 3 max)
    :return: Object: Bool (success or failure) or Prediction
    """

    Log("NEO-FUTURES - Oracle Judge Smart Contract")
    trigger = GetTrigger()
    arg_len = len(args)
    if arg_len > 5:
        # Only 5 args max
        return False

    if trigger == Verification():
        Log("trigger: Verification")
        is_owner = CheckWitness(Game_rules.owner)
        if is_owner:
            return True
    elif trigger == Application():
        Log("trigger: Application")
        Log(operation)

        # create_new_game {{client}} {{game_type}}
        if operation == 'create_new_game':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            client_hash = args[0]
            game_type = args[1]
            if not CheckWitness(client_hash):
                Log("Unauthorised hash")
                return False
            return CreateNewGame(client_hash, game_type)

        # submit_prediction {{oracle}} {{game_type}} {{instance_ts}} {{prediction}} {{gas-submission}}
        if operation == 'submit_prediction':
            if arg_len != 5:
                Log("Wrong arg length")
                return False
            oracle = args[0]
            game_type = args[1]
            instance_ts = args[2]
            prediction = args[3]
            gas_submission = args[4]
            if not CheckWitness(oracle):
                Log("Unauthorised hash")
                return False

            # Check instance_ts is correctly timestepped
            if not CheckTimestamp(instance_ts):
                Log("Not correct timestamp format")
                return False
            return client_hash.SubmitPrediction(oracle, game_type, instance_ts, prediction, gas_submission)

        # judge_instance {{game_type}} {{instance_ts}}
        if operation == 'judge_instance':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            if client_hash.isGameInstanceJudged(game_type, instance_ts):
                Log("Already Judged")
                return False
            return client_hash.JudgeInstance(game_type, instance_ts)

        # get_prediction {{game_type}} {{instance_ts}}
        if operation == 'get_prediction':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            # Try judging to make sure judged
            client_hash.JudgeInstance(game_type, instance_ts)
            return client_hash.GetPrediction(game_type, instance_ts)

        # get_available_balance_oracle {{oracle}}
        if operation == 'get_available_balance_oracle':
            if arg_len != 1:
                Log("Wrong arg length")
                return False
            oracle = args[0]
            return client_hash.GetOracleBalance(oracle)

        # get_correct_oracles_for_instance {{game_type}} {{instance_ts}}
        if operation == 'get_correct_oracles_for_instance':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            # Try judging to make sure judged
            client_hash.JudgeInstance(game_type, instance_ts)
            return client_hash.GetCorrectOracleCountForInstance(game_type, instance_ts)

        # debug_get_value {{key}}
        if operation == 'debug_get_value':
            if arg_len != 1:
                Log("Wrong arg length")
                return False
            key = args[0]
            context = GetContext()
            return Get(context, key)
        else:
            Log("unknown op")
            return False
def Main(operation, args):
    """
    This is the main entry point for the dApp
    :param operation: the operation to be performed
    :type operation: str
    :param args: an optional list of arguments
    :type args: list
    :return: indicating the successful execution of the dApp
    :rtype: string
    """
    trigger = GetTrigger()

    if trigger == Verification():
        is_owner = CheckWitness(BCSCHAIN)

        if is_owner:
            return True

        return False

    elif trigger == Application():
        # Check the version for compatability
        if operation == 'ownArea':
            if (len(args) == 3):
                addr = args[0]
                lat = args[1]
                lon = args[2]
                width = args[3]
                length = args[4]
                height = args[5]

                Log('Owning_Area')
                res = own_area(addr,lat,lon,width,length,height)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'regisProduct':
            if (len(args) == 3):
                seller_addr = args[0]
                product_hash = args[1]

                Log('Registering_Product')
                res = create_product(seller_addr,product_hash)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False
                
        elif operation == 'activateProduct':
            if (len(args) == 2):
                seller_addr = args[0]
                product_hash = args[1]

                Log('Activating_Product')
                res = activate_product(seller_addr ,product_hash)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False
        
        elif operation == 'setPrice':
            if (len(args) == 3):
                seller_addr = args[0]
                product_hash = args[1]
                price = args[2]

                Log('Setting_Price')
                res = set_price(seller_addr,product_hash,price)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False


        elif operation == 'buyProduct':
            if (len(args) == 2):
                buyer_addr = args[0]
                product_hash = args[1]

                Log('Buying_Product')
                res = buy_product(buyer_addr,product_hash)
                return res

            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'deactivateProduct':
            if (len(args) == 2):
                seller_addr = args[0]
                product_hash = args[1]

                Log('Deactivating_Product')
                res = deactivate_product(seller_addr,product_hash)
                return res

            else:
                Log('INVALID_ARGUMENTS')
            return False

        Log('INVALID_FUNCTION')
        return False

    Log('FORBIDDEN')
    return False
Exemplo n.º 18
0
def Main(operation, args):
    trigger = GetTrigger()

    if trigger == Verification():
        # Verification is done when sending money out of the contract.
        #
        # We need to check the sender's balance to make sure they have enough to allow them
        # to send what they're trying to send
        #
        # Note: Contract owner has no special privileges here.

        tx = GetScriptContainer()

        valid = False

        # Go through all the outputs and make sure there's only one output destination.
        # This will be used if we're auto-rescinding the assets (ie sending back to the original
        # sender after a week goes by without the recipient picking up). We'll make sure there's only
        # one output script hash and it matches the stored script hash of the original sender
        #
        # Also we make sure not outputs are going to the contract script hash because we don't support
        # change.
        output_script_hash = None
        contract_script_hash = GetExecutingScriptHash()
        for output in tx.Outputs:
            shash = GetScriptHash(output)
            if shash == contract_script_hash:
                return False

            if output_script_hash == None:
                output_script_hash = shash
            elif shash != output_script_hash:
                return False

        for input in tx.Inputs:
            hash = InputGetHash(input)
            context = GetContext()
            tx_info_serialized = Get(context, hash)
            tx_info = deserialize_bytearray(tx_info_serialized)

            escrow = tx_info[0]
            sender = tx_info[1]
            time = tx_info[2]

            is_escrow = CheckWitness(escrow)

            if is_escrow != True:
                if sender != output_script_hash:
                    return False

                current_time = GetCurrentTimestamp()
                seven_days = 604800
                minimum_time = time + seven_days
                if current_time < minimum_time:
                    return False

            # We have at least one. We'll keep checking if there are more.
            print('That input was valid')
            valid = True

        print('All good')
        return valid

    elif trigger == Application():
        if operation == 'name':
            n = "Sendeo"
            return n

        elif operation == 'deposit':
            if len(args) != 2:
                return False

            recipient = args[0]
            note = args[1]

            deposit = Deposit(recipient, note)

            return deposit

    return False
Exemplo n.º 19
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        return CheckWitness(OWNER)

    elif trigger == Application():
        context = GetContext()
        l = len(args)
        if l == 1:
            key = args[0]
        elif l == 2:
            key = args[0]
            value = args[1]
        else:
            Log("Bad invocation argument count")
            Log(l)
            return False

        if operation == 'getvalue':
            return Get(context, key)
  
        elif operation == 'putvalue':
            prefix = take(key, 6)
            if BADPREFIX == prefix:
                Log("Hacking attempt!")
                return False

            if CheckWitness(OWNER):
                Log("Owner found, bypassing payment")
                Put(context, key, value)
                return True
            else:
                # check if we got paid
                tx = GetScriptContainer()
                refs = tx.References
                if len(refs) < 1:
                    Log("No payment sent in transaction")
                    return False
                ref = refs[0]
                sentAsset = GetAssetId(ref)
                if sentAsset == GAS_ASSET_ID:
                    sender = GetScriptHash(ref)
                    receiver = GetExecutingScriptHash();
                    totalGasSent = 0
            
                    for output in tx.Outputs:
                        shash = GetScriptHash(output)
                        if shash == receiver:
                            totalGasSent = totalGasSent + output.Value

                    Log ("Total GAS sent:")
                    Log (totalGasSent)
                    pkey = concat('price/', key)
                    keyprice = Get(context, pkey)

                    if totalGasSent == keyprice:
                        Log("Price met, setting value and sending notification")
                        notification=[sender,key,value]
                        Notify(notification)
                        Put(context, key, value)
                        return True
                   
                    Log("Price not met!")
                    return False
            
            return False
        elif operation == 'getprice':
            key = concat('price/', key)
            return Get(context, key)

        elif operation == 'putprice':
            if CheckWitness(OWNER):
                key = concat('price/', key)
                Put(context, key, value)
                return True
            else:
                Log("Access denied")
                return False
        else:
            Log("Invalid operation")
            return False
    return False
Exemplo n.º 20
0
def Main(operation_string_para, args):
    trigger = GetTrigger()

    if trigger == Verification:
        # all the hashes, which were found in the transaction outputs
        script_hashes = getOutputScriptHashes()

        if not script_hashes:
            return False

        withdrawal_controller = WithdrawalController()

        for script_hash in script_hashes:
            # these are all the assets, which were created by requesting withdrawals
            released_assets = withdrawal_controller.getReleasedAssets(
                script_hash)

            if released_assets:
                attachment = getAttachedAssets(script_hash)
                # if the requestes asset value is not higher than the stored asset value, allow withdrawal
                if attachment.gas_attached <= released_assets:
                    SpentReleasedAssets(script_hash, attachment.gas_attached)
                    return True
            else:
                n = 0

        return False

    elif trigger == Application:

        if operation_string_para != None:

            args_count = len(args)

            if args_count < 1:
                return 'error: please provide operation arguments'

            # the operation controller check for arguments count and operation string matches
            operations_controller = OperationsController()
            # the withdrawal controller is reponsible for handling the withdrawal requests from the contracts receiver
            withdrawal_controller = WithdrawalController()

            init_operation_strings = operations_controller.validInitOperationStrings(
            )

            # after the receiver has transferred assets from the smart contract, the amount of his released assets has to be reduced.
            if operations_controller.isSpentAssets(operation_string_para):
                if not operations_controller.operationArgsAreValid(
                        operation_string_para, args):
                    return 'error: operation arguments count invalid'

                address = args[0]
                spent_assets = args[1]
                return withdrawal_controller.spentAssets(address, spent_assets)

            # the uid is the identifier for every payment contract between two partys
            uid = args[0]
            payment = Payment()
            payment_in_use = payment.isInUse(uid)

            # only handle init operations at this point
            for init_operation_string in init_operation_strings:
                if operation_string_para == init_operation_string:

                    if not operations_controller.operationArgsAreValid(
                            operation_string_para, args):
                        return 'error: operation arguments count invalid'

                    if payment_in_use:
                        return 'error: cant initialize payment contract. uid is in use'

                    principal = args[1]
                    receiver = args[2]
                    withdrawal_controller.initialize(uid, receiver)

                    if operations_controller.isInitTimeContract(
                            operation_string_para):
                        return payment.initializeTimeContract(args)

                    if operations_controller.isInitUnitsContract(
                            operation_string_para):
                        return payment.initializeUnitsContract(args)

            # all remaining operations need an initialized payment contract
            if not payment_in_use:
                return 'error: operation invalid. payment contract not in use'

            if not operations_controller.operationArgsAreValid(
                    operation_string_para, args):
                return 'error: operation arguments count invalid'

            payment_has_started = payment.hasStarted(uid)

            if not payment_has_started:
                return 'error: operation invalid. payment contract not in use yet'

            # the balance is the available amount, minus spent units and those, which are currently
            if operations_controller.isGetBalance(operation_string_para):
                return payment.getBalance(uid)

            principal = payment.getPrincipalAddress(uid)
            receiver = payment.getReceiverAddress(uid)

            is_principal = CheckWitness(principal)
            is_receiver = CheckWitness(receiver)

            # only the receiver can claim units, which he worked for in a UnitsContract
            if operations_controller.isClaimUnits(operation_string_para):
                if not is_receiver:
                    return 'error: not authorized'

                units_to_claim = args[1]
                units_to_claim = payment.claimUnits(uid, units_to_claim)

                if units_to_claim:
                    OnClaimUnits(uid, units_to_claim)

                return units_to_claim

            # only the owner can authorized units, which the receiver claimed
            if operations_controller.isAuthorizeUnits(operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                units_to_authorize = args[1]
                return payment.authorizeOpenUnits(uid, units_to_authorize)

            # this will return the total amount of available assets transferred by withdrawal requests
            # the receiver can use this, to get the amount of assets he can spent from the smart-contract
            if operations_controller.isGetAvailableAssets(
                    operation_string_para):
                if is_receiver:
                    return withdrawal_controller.getReleasedAssets(receiver)

                return False

            # this will return the amount of assets, which the receiver has requested
            #  the owner can use this, to deposit assets for the receiver
            if operations_controller.isGetOpenWithdrawalValue(
                    operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                return withdrawal_controller.getOpenWithdrawalValue(uid)

            payment_type = payment.getType(uid)

            # only the receiver can request withdrawals from the smart-contract
            if operations_controller.isRequestWithdrawal(
                    operation_string_para):
                if not is_receiver:
                    return "error: not authorized"

                existing_withdrawal_request = withdrawal_controller.getWithdrawalRequest(
                    uid)

                if existing_withdrawal_request:
                    return 'error: withdrawal request in progress. please wait until it finishes'

                units_balance = payment.getUnitsBalance(uid)

                if units_balance == 0:
                    return 'error: withdrawal request invalid. nothing to withdraw'

                current_value = payment.getBalance(uid)

                # if this payment contract was created with all assets deposited up front, there is no need to trigger an event.
                # The withdrawal amount is released immediately
                if payment_type == payment.PAYMENT_TYPE_UP_FRONT:
                    payment.spentUnitsAfterWithdrawalAuthorize(
                        uid, current_value, False)
                    withdrawal_controller.releaseAttachedAssets(
                        receiver, current_value)

                    return current_value
                # all the assets for a withdrawal requests within a just-in-time contract need to deposited manually by the owner
                elif payment_type == payment.PAYMENT_TYPE_JUST_IN_TIME:
                    withdrawal_controller.createNewWithdrawalRequest(
                        uid, units_balance, current_value)
                    payment.reserveUnitsForWithdrawal(uid, units_balance)
                    OnWithdrawalRequest(uid, current_value)

                    return current_value

                return False
            # this operation is used by the owner to deposit assets for the requested amount
            if operations_controller.isDepositWithdrawalsRequest(
                    operation_string_para):
                if not is_principal:
                    return "error: not authorized"

                if payment_type == payment.PAYMENT_TYPE_UP_FRONT:
                    Notify(
                        'error: you cant deposit assets for an up-front contract'
                    )
                    return False

                existing_withdrawal_request = withdrawal_controller.getWithdrawalRequest(
                    uid)

                if not existing_withdrawal_request:
                    return 'error: there is no pending withdrawal request'

                # we get all the assets, which are attached and are ment for the smart-contracts script hash
                contract_script_hash = GetExecutingScriptHash()
                attached_assets = getAttachedAssets(contract_script_hash)
                attached_gas = attached_assets.gas_attached

                if attached_gas == 0:
                    return 'error: no gas attached'

                open_withdrawal_value = withdrawal_controller.getOpenWithdrawalValue(
                    uid)

                # One can never deposit more assets than the requested amount
                if attached_gas != open_withdrawal_value:
                    return 'error: attached gas amount has to match withdrawal requests value'

                payment.spentUnitsAfterWithdrawalAuthorize(
                    uid, attached_gas, True)
                withdrawal_controller.releaseAttachedAssets(
                    receiver, attached_gas)
                withdrawal_controller.clearWithdrawalRequest(uid)

                return attached_gas

        return 'error: no operation string provided'

    return 'error: unknown triger'
Exemplo n.º 21
0
def Main(operation, args):
    """
    :param operation: new, submit, judge, getvalue
    :param args: optional arguments
    :return: Bool
    """

    trigger = GetTrigger()
    if trigger == Application:
        Log("trigger: Application")
        context = GetContext()

        if operation == 'getvalue':
            Log("op: getvalue")
            key = args[0]
            return Get(context, key)

        if operation == 'new':
            id = args[0]
            Put(context, "current_game", id)
            Log("Created a new game")

        elif operation == 'submit':
            id = args[0]
            price = args[1]
            Log(id)
            Log(price)

            # Only allow submissions for the current game
            current_game = Get(context, "current_game")
            if current_game != id:
                Log("Not the correct game")
                return False

            tx = GetScriptContainer()
            refs = tx.References
            nRef = len(refs)
            Log(nRef)
            ref = refs[0]
            sender = GetScriptHash(ref)
            Log(sender)
            key = concat(sender, id)
            Log(key)
            oldprice = Get(context, key)
            if oldprice == 0:
                Append(context, sender, id)
            Put(context, key, price)  # Update if already exists

        elif operation == 'judge':
            id = args[0]
            playerkey = concat("players::", id)
            curr_list = Get(context, playerkey)
            nplayers = len(curr_list) // 20
            max = 0
            best_price = -1
            for i in range(0, nplayers):
                start = 20 * i
                player = substr(curr_list, start, 20)
                Log(player)
                key = concat(player, id)
                price = Get(context, key)
                price_key = concat(id, price)
                count = Increment(context, price_key)
                if count > max:
                    max = count
                    best_price = price
            if max == 0:
                Log("No entries")
                return False
            else:
                Log(max)
                Log(best_price)
                Put(context, id, best_price)
                return True
        return True
    return False
Exemplo n.º 22
0
def Main(operation, args):
    """
    :param operation
    :param args: optional arguments (up to 3 max)
    :return: Object: Bool (success or failure) or Prediction
    """

    Log("ORACLE JUDGE")
    trigger = GetTrigger()
    arg_len = len(args)
    if arg_len > 5:
        # Only 5 args max
        return False

    if trigger == Verification():
        Log("trigger: Verification")
        is_owner = CheckWitness(owner)
        if is_owner:
            return True
    elif trigger == Application():
        Log("trigger: Application")
        Log(operation)

        # create_new_game {{client}} {{game_type}}
        if operation == 'create_new_game':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            client_hash = args[0]
            game_type = args[1]
            if not CheckWitness(client_hash):
                Log("Unauthorised hash")
                return False
            return CreateNewGame(client_hash, game_type)

        # create_new_game_instance {{client}} {{game_type}} {{instance_ts}}
        if operation == 'create_new_game_instance':
            if arg_len != 3:
                Log("Wrong arg length")
                return False
            client_hash = args[0]
            game_type = args[1]
            instance_ts = args[2]
            if not CheckWitness(client_hash):
                Log("Unauthorised hash")
                return False
            return CreateNewGameInstance(client_hash, game_type, instance_ts)

        # submit_prediction {{oracle}} {{game_type}} {{instance_ts}} {{prediction}} (--attach-gas=5)
        if operation == 'submit_prediction':
            if arg_len != 4:
                Log("Wrong arg length")
                return False
            oracle = args[0]
            game_type = args[1]
            instance_ts = args[2]
            prediction = args[3]
            if not CheckWitness(oracle):
                Log("Unauthorised hash")
                return False
            return SubmitPrediction(oracle, game_type, instance_ts, prediction)

        # judge_instance {{game_type}} {{instance_ts}}
        if operation == 'judge_instance':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            if isGameInstanceJudged(game_type, instance_ts):
                Log("Already Judged")
                return False
            return JudgeInstance(game_type, instance_ts)

        # get_prediction_for_instance {{game_type}} {{instance_ts}}
        if operation == 'get_prediction_for_instance':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            if not isGameInstanceJudged(game_type, instance_ts):
                JudgeInstance(game_type, instance_ts)
            return GetPrediction(game_type, instance_ts)

        # get_available_balance_oracle {{oracle}}
        if operation == 'get_available_balance_oracle':
            if arg_len != 1:
                Log("Wrong arg length")
                return False
            oracle = args[0]
            return GetOracleBalance(oracle)

        # get_correct_oracles_for_instance {{game_type}} {{instance_ts}}
        if operation == 'get_correct_oracles_for_instance':
            if arg_len != 2:
                Log("Wrong arg length")
                return False
            game_type = args[0]
            instance_ts = args[1]
            if not isGameInstanceJudged(game_type, instance_ts):
                Log("Game not yet Judged")
                return False
            return GetCorrectOracleCountForInstance(game_type, instance_ts)

        # debug_get_value {{key}}
        if operation == 'debug_get_value':
            if arg_len != 1:
                Log("Wrong arg length")
                return False
            key = args[0]
            return Get(GetContext(), key)
        else:
            Log("unknown op")
            return False
Exemplo n.º 23
0
def Main(operation, args):
    trigger = GetTrigger()

    if trigger == Verification():
        is_owner = CheckWitness(OWNER)
        if is_owner:
            return True
        return False

    elif trigger == Application():
        # seller action
        if operation == 'create':
            if len(args) == 8:
                creator = args[0]  # public key
                promo_id = args[1]
                title = args[2]
                description = args[3]
                price_per_person = args[4]  # price in GAS
                expiration = args[5]
                min_count = args[6]
                max_count = args[7]

                success = CreatePromo(creator, promo_id, title, description,
                                      price_per_person, expiration, min_count,
                                      max_count)

                if success:
                    Log('Promo created successfully')
                    return True
                else:
                    Log('Error in creating promo')
                    return False
            else:
                Log('incorrect number of arguments')
                return False

        # seller action
        elif operation == 'delete':
            if len(args) == 1:
                promo_id = args[0]

                authorize = IsPromoCreator(promo_id)
                if authorize:
                    success = DeletePromo(promo_id)
                    if success:
                        Log('Promo deleted successfully')
                        return True
                    else:
                        Log('Error in deleting promo')
                        return False
                else:
                    Log('Permission denied')
                    return False
            else:
                Log('incorrect number of arguments')
                return False

        # seller action
        elif operation == 'claim':
            if len(args) == 1:
                promo_id = args[0]

                authorize = IsPromoCreator(promo_id)
                if authorize:
                    success = ClaimFunds(promo_id)
                    if success:
                        Log('Promo funds claimed successfully')
                    else:
                        Log('Error in claiming funds')
                        return False
                else:
                    Log('Permission denied')
                    return False
            else:
                Log('incorrect number of arguments')
                return False

        # buyer action
        elif operation == 'buy':
            if len(args) == 3:
                buyer = args[0]
                promo_id = args[1]
                quantity = args[2]

                success = BuyPromo(buyer, promo_id, quantity)

                if success:
                    Log('Promo purchased successfully')
                    return True
                else:
                    Log('Error in purchasing promo')
                    return False
            else:
                Log('incorrect number of arguments')
                return False

        # buyer action
        elif operation == 'refund':
            if len(args) == 2:
                buyer = args[0]
                promo_id = args[1]

                authorize = CheckWitness(buyer)
                if authorize:
                    success = RefundPromo(buyer, promo_id)

                    if success:
                        Log('Promo refunded successfully')
                        return True
                    else:
                        Log('Error in refund')
                        return False
                else:
                    Log('Permission denied')
                    return False
            else:
                Log('incorrect number of arguments')
                return False

        # buyer/seller action
        elif operation == 'details':
            if len(args) == 1:
                promo_id = args[0]
                Details(promo_id)
                return True
            else:
                Log('incorrect number of arguments')
                return False

        else:
            Log('operation not found')
            return False

    return False
Exemplo n.º 24
0
def Main(operation, args):
    """
    This is the main entry point for the dApp
    :param operation: the operation to be performed
    :type operation: str
    :param args: an optional list of arguments
    :type args: list
    :return: indicating the successful execution of the dApp
    :rtype: bool
    """
    trigger = GetTrigger()

    if trigger == Verification():

        # if the script that sent this is the owner
        # we allow the spend
        is_owner = CheckWitness(OWNER)

        if is_owner:

            return True

        return False

    elif trigger == Application():

        if operation == 'deploy':
            if len(args) == 6:
                dapp_name = args[0]
                oracle = args[1]
                time_margin = args[2]
                min_time = args[3]
                max_time = args[4]
                fee = args[5]
                d = Deploy(dapp_name, oracle, time_margin, min_time, max_time)

                Log("Dapp deployed")
                return d
            else:
                return False

        elif operation == 'name':
            context = GetContext()
            n = Get(context, 'dapp_name')
            return n

        elif operation == 'updateName':
            if len(args) == 1:
                new_name = args[0]
                n = UpdateName(new_name)
                Log("Name updated")
                return n

            else:
                return False

        elif operation == 'oracle':
            context = GetContext()
            o = Get(context, 'oracle')

            return o

        elif operation == 'updateOracle':
            if len(args) == 1:
                new_oracle = args[0]
                o = UpdateOracle(new_oracle)
                Log("Oracle updated")
                return o

            else:
                return False

        elif operation == 'time_margin':
            context = GetContext()
            time_margin = Get(context, 'time_margin')

            return time_margin

        elif operation == 'min_time':
            context = GetContext()
            min_time = Get(context, 'min_time')

            return min_time

        elif operation == 'max_time':
            context = GetContext()
            max_time = Get(context, 'max_time')

            return max_time

        elif operation == 'updateTimeLimits':
            if len(args) == 2:
                time_variable = args[0]
                value = args[1]
                t = UpdateTimeLimits(time_variable, value)
                Log("Time limits updated")
                return t

            else:
                return False

        elif operation == 'agreement':
            if len(args) == 10:
                agreement_key = args[0]
                customer = args[1]
                insurer = args[2]
                location = args[3]
                timestamp = args[4]
                utc_offset = args[5]
                amount = args[6]
                premium = args[7]
                dapp_name = args[8]
                fee = args[9]
                a = Agreement(agreement_key, customer, insurer, location,
                              timestamp, utc_offset, amount, premium,
                              dapp_name, fee)

                Log("Agreement added!")
                return a

            else:
                return False

        elif operation == 'resultNotice':
            if len(args) == 3:
                agreement_key = args[0]
                weather_param = args[1]
                oracle_cost = args[2]
                return ResultNotice(agreement_key, weather_param, oracle_cost)

            else:
                return False

        elif operation == 'claim':
            if len(args) == 1:
                agreement_key = args[0]
                return Claim(agreement_key)

            else:
                return False

        elif operation == 'transfer':
            if len(args) == 3:
                t_from = args[0]
                t_to = args[1]
                t_amount = args[2]
                return DoTransfer(t_from, t_to, t_amount)

            else:
                return False

        elif operation == 'refundAll':
            if len(args) == 1:
                agreement_key = args[0]
                return RefundAll(agreement_key)

            else:
                return False

        elif operation == 'deleteAgreement':
            if len(args) == 1:
                agreement_key = args[0]
                return DeleteAgreement(agreement_key)

            else:
                return False

        result = 'unknown operation'

        return result

    return False
Exemplo n.º 25
0
def Main(operation, args):
    """

    :param operation: str Der Name der Aufgabe die ausgeführt werden soll
    :param args: list Eine Liste der Argumente für die Ausführung
    :return:
        bytearray: Das Ergebnis der Ausführung
    """

    trigger = GetTrigger()
    token = Token()

    #print("Executing ICO Template")

    # Dies wird in der Verification portion des Contract benutzt
    # um festzustellen ob ein Transfer System Assets ( NEO/GAS) beinhaltet.
    # Diese Contract´s Adresse kann fortfahren
    if trigger == Verification:

        # Überprüfen Sie ob die aufrufende Instanz der Besitzer des Contracs ist
        is_owner = CheckWitness(token.owner)

        # Wenn Besitzer, fortfahren
        if is_owner:

            return True

        # Andernfalls, müssen Sie einen Lookup der Adresse machen und feststellen
        # ob der Anhang des Assets okay ist
        attachments = get_asset_attachments()  # type:Attachments

        storage = StorageAPI()

        crowdsale = Crowdsale()

        return crowdsale.can_exchange(token, attachments, storage)

    elif trigger == Application:

        if operation != None:

            nep = NEP5Handler()

            for op in nep.get_methods():
                if operation == op:
                    return nep.handle_nep51(operation, args, token)

            if operation == 'deploy':
                return deploy(token)

            if operation == 'circulation':
                storage = StorageAPI()
                return token.get_circulation(storage)

            # Das folgende wird von Crowdsale verarbeitet

            sale = Crowdsale()

            if operation == 'mintTokens':
                return sale.exchange(token)

            if operation == 'crowdsale_register':
                return sale.kyc_register(args, token)

            if operation == 'crowdsale_status':
                return sale.kyc_status(args)

            if operation == 'crowdsale_available':
                return token.crowdsale_available_amount()

            return 'unknown operation'

    return False
Exemplo n.º 26
0
def Main(operation, args):
    """
    :param operation: new, submit, judge, getvalue
    :param args: optional arguments
    :return: Bool
    """

    trigger = GetTrigger()
    if trigger == Application:
        Log("trigger: Application")
        context = GetContext()

        if operation == 'getvalue':
            Log("op: getvalue")
            key = args[0]
            return Get(context, key)

        if operation == 'new':
            Log("op: new")
            id = args[0]
            Put(context, "current_game", id)
            Put(context, "max", 0)
            Log("Created a new game")
            Notify(id)

        elif operation == 'submit':
            id = args[0]
            price = args[1]
            sender = args[2]
            Log(id)
            Log(price)
            Log(sender)

            # Only allow submissions for the current game
            current_game = Get(context, "current_game")
            if current_game != id:
                Log("Not the correct game")
                return False

            if not CheckWitness(sender):
                Log("Oracle is not the right person")
                return False

            Log(sender)
            key = concat(sender, id)
            Log(key)
            oldprice = Get(context, key)
            if oldprice != 0:
                # Too late you've already submitted
                Log("Error: cannot submit twice for the same game")
                return False
            Append(context, sender, id)
            Put(context, key, price)  # Update if already exists
            max = Get(context, 'max')
            price_key = concat(id, price)
            count = Increment(context, price_key)
            if count > max:
                Put(context, 'max', count)
                Put(context, id, price)
                Log("Updated best price")
            return True

        elif operation == 'judge':
            id = args[0]
            playerkey = concat("players::", id)
            curr_list = Get(context, playerkey)
            nplayers = len(curr_list) // 20
            decided_price = Get(context, id)
            for i in range(0, nplayers):
                start = 20 * i
                player = substr(curr_list, start, 20)
                Log(player)
                Log("Checking if player lied")
                key = concat(player, id)
                price = Get(context, key)
                if decided_price != price:
                    Log("Player did LIE!")
                else:
                    Log("Player told the TRUTH!")
            return True
        return True
    return False
Exemplo n.º 27
0
def Main(operation, args):
    """

    :param operation: str The name of the operation to perform
    :param args: list A list of arguments along with the operation
    :return:
        bytearray: The result of the operation
    """

    trigger = GetTrigger()
    token = Token()

    #print("Executing ICO Template")

    # This is used in the Verification portion of the contract
    # To determine whether a transfer of system assets ( NEO/Gas) involving
    # This contract's address can proceed
    if trigger == Verification:

        # check if the invoker is the owner of this contract
        is_owner = CheckWitness(token.owner)

        # If owner, proceed
        if is_owner:

            return True

        # Otherwise, we need to lookup the assets and determine
        # If attachments of assets is ok
        attachments = get_asset_attachments()  # type:Attachments

        storage = StorageAPI()

        crowdsale = Crowdsale()

        return crowdsale.can_exchange(token, attachments, storage, True)


    elif trigger == Application:

        if operation != None:

            nep = NEP5Handler()

            for op in nep.get_methods():
                if operation == op:
                    return nep.handle_nep51(operation, args, token)

            if operation == 'deploy':
                return deploy(token)

            if operation == 'circulation':
                storage = StorageAPI()
                return token.get_circulation(storage)

            # the following are handled by crowdsale

            sale = Crowdsale()

            if operation == 'mintTokens':
                return sale.exchange(token)

            if operation == 'crowdsale_register':
                return sale.kyc_register(args, token)

            if operation == 'crowdsale_status':
                return sale.kyc_status(args)

            if operation == 'crowdsale_available':
                return token.crowdsale_available_amount()

            return 'unknown operation'

    return False
def Main(operation, args):
    """

    :param operation: str The name of the operation to perform
    :param args: list A list of arguments along with the operation
    :return:
        bytearray: The result of the operation
    """

    trigger = GetTrigger()
    token = Token()

    #print("Executing ICO Template")

    # This is used in the Verification portion of the contract
    # To determine whether a transfer of system assets ( NEO/Gas) involving
    # This contract's address can proceed
    if trigger == Verification:

        # check if the invoker is the owner of this contract
        is_owner = CheckWitness(token.owner)

        # If owner, proceed
        if is_owner:

            return True

        # Otherwise, we need to lookup the assets and determine
        # If attachments of assets is ok
        attachments = get_asset_attachments()  # type:Attachments

        storage = StorageAPI()

        crowdsale = Crowdsale()

        return crowdsale.can_exchange(token, attachments, storage, True)


    elif trigger == Application:

        if operation != None:

            nep = NEP5Handler()

            for op in nep.get_methods():
                if operation == op:
                    return nep.handle_nep51(operation, args, token)

            if operation == 'deploy':
                return deploy(token)

            if operation == 'circulation':
                storage = StorageAPI()
                return token.get_circulation(storage)

            # the following are handled by crowdsale

            sale = Crowdsale()

            if operation == 'mintTokens':
                return sale.exchange(token)

            # if operation == 'crowdsale_register':
            #     return sale.kyc_register(args, token)

            # if operation == 'crowdsale_status':
            #     return sale.kyc_status(args)

            if operation == 'crowdsale_available':
                return token.crowdsale_available_amount()

            if operation == 'crowdfunding_create':
                return crowdfunding_create(args)

            if operation == 'crowdfunding_total':
                storage = StorageAPI()
                crowdfunding_address = args[0]
                crowdfunding_total_key = storage.get_crowdfunding_total_key(crowdfunding_address)
                crowdfunding_total = storage.get(crowdfunding_total_key)
                msg = ["crowdfunding_total", crowdfunding_total]
                Notify(msg)
                return crowdfunding_total

            if operation == 'crowdfunding_numcontrib':
                storage = StorageAPI()
                crowdfunding_address = args[0]
                crowdfunding_numcontrib_key = storage.get_crowdfunding_numcontrib_key(crowdfunding_address)
                crowdfunding_numcontrib = storage.get(crowdfunding_numcontrib_key)
                msg = ["crowdfunding_numcontrib", crowdfunding_numcontrib]
                Notify(msg)
                return crowdfunding_numcontrib

            if operation == 'crowdfunding_test':
                crowdfunding_address = args[0]
                member_addresses = crowdfunding_get_members(crowdfunding_address)
                if not member_addresses:
                    return False

                Notify("Member addresses:")
                Notify(member_addresses)
                return True

            if operation == 'level':
                address = args[0]
                level = level_of(address)
                Notify("Level:")
                Notify(level)
                return level

            if operation == 'reward_user':
                address = args[0]
                success = reward_user(address)
                if success:
                    Notify("User was rewarded:")
                    Notify(address)
                return success

            return 'unknown operation'

    return False
Exemplo n.º 29
0
def Main(operation, args):
    """
    Main definition for the KRYPTON smart contact

    :param operation: the operation to be performed
    :type operation: str

    :param args: an optional list of arguments
    :type args: list

    :return: indicating the successful execution of the smart contract
    :rtype: bool
    """

    trigger = GetTrigger()

    if trigger == Verification():
        is_owner = CheckWitness(KRYPTON)

        if is_owner:
            return True

        return False

    elif trigger == Application():
        # Check the version for compatability
        if operation == 'version':
            version = VERSION
            Notify(version)
            return version

        # Let the provider deploy on the blockchain
        elif operation == 'deploy':
            if (len(args) == 2):
                # Read arguments
                provider = args[0]
                location = args[1]

                # Deploy the provider
                Log('FUNC_DEPLOY')
                deploy = Deploy(provider, location)
                return deploy

            else:
                Log('INVALID_ARGUMENTS')
                return False

        # Let the provider undeploy on the blockchain
        elif operation == 'undeploy':
            if (len(args) == 1):
                # Read arguments
                provider = args[0]

                # Undeploy the provider
                Log('FUNC_UNDEPLOY')
                undeploy = Undeploy(provider)
                return undeploy

            else:
                Log('INVALID_ARGUMENTS')
                return False

        # Let the user register to a provider
        elif operation == 'register':
            if (len(args) == 3):
                # Read arguments
                user = args[0]
                provider = args[1]
                uuid = args[2]

                # Register the user
                Log('FUNC_REGISTER')
                register = Register(user, provider, uuid)
                return register

            else:
                Log('INVALID_ARGUMENTS')
                return False

        # Let the user unregister to a provider
        elif operation == 'unregister':
            if (len(args) == 1):
                user = args[0]

                # Unregister the user
                Log('FUNC_UNREGISTER')
                unregister = Unregister(user)
                return unregister

            else:
                Log('INVALID_ARGUMENTS')
                return False

        # Query a user for UUID or provider
        elif operation == 'query':
            if (len(args) == 2):
                # Read arguments
                query = args[0]
                user = args[1]

                # Query the user for UUID or provider
                Log('FUNC_QUERY')
                queryuser = QueryUser(query, user)
                return queryuser

            else:
                Log('INVALID_ARGUMENTS')
                return False

        Log('INVALID_FUNCTION')
        return False

    Log('FORBIDDEN')
    return False
Exemplo n.º 30
0
def Main(operation, args):

    trigger = GetTrigger()

    if trigger == Verification():
        is_owner = CheckWitness(BCSCHAIN)

        if is_owner:
            return True

        return False

    elif trigger == Application():
        # Check the version for compatability
        if operation == 'ownArea':
            if (len(args) == 3):
                addr = args[0]
                lat = args[1]
                lon = args[2]

                Log('Owning_Area')
                res = own_area(addr, lat, lon)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'createProduct':
            if (len(args) == 3):
                addr = args[0]
                uuid = args[1]
                p_name = args[2]

                Log('Creating_Product')
                res = create_product(addr, uuid, p_name)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'activateProduct':
            if (len(args) == 2):
                addr = args[0]
                uuid = args[1]

                Log('Activating_Product')
                res = activate_product(addr, uuid)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'setPrice':
            if (len(args) == 3):
                addr = args[0]
                uuid = args[1]
                price = args[2]

                Log('Setting_Price')
                res = set_price(addr, uuid, price)
                return res
            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'buyProduct':
            if (len(args) == 2):
                addr = args[0]
                uuid = args[1]

                Log('Buying_Product')
                res = buy_product(addr, uuid)
                return res

            else:
                Log('INVALID_ARGUMENTS')
                return False

        elif operation == 'deactivateProduct':
            if (len(args) == 2):
                addr = args[0]
                uuid = args[1]

                Log('Deactivating_Product')
                res = deactivate_product(addr, uuid)
                return res

            else:
                Log('INVALID_ARGUMENTS')
            return False

        Log('INVALID_FUNCTION')
        return False

    Log('FORBIDDEN')
    return False