Пример #1
0
    def __init__(self):
        username = "******" # could override at the command line
        password = getpass.getpass("Enter password for {}: ".format(username))
        bank_client = BankClientProtocol(bank_cert, username, password) 
        self.bank_client = bank_client
        self.instruction_counter = 0
        self.instructions = [
                            "look mirror", 
                            "get hairpin",
                            "unlock chest with hairpin",
                            "open chest",
                            "look in chest",
                            "get hammer from chest",
                            "hit flyingkey with hammer",
                            "get key",
                            "unlock door with key",
                            "open door"]

        self.paid = False # make sure we don't overpay 
Пример #2
0
def main():
    from OnlineBank import BankClientProtocol, BANK_FIXED_PLAYGROUND_ADDR, BANK_FIXED_PLAYGROUND_PORT
    from CipherUtil import loadCertFromFile
    #logctx = LoggingContext()
    #logctx.nodeId = "parallelTSP_"+myAddr.toString()

    # set this up as a configuration option
    #logctx.doPacketTracing = True
    #playground.playgroundlog.startLogging(logctx)

    # Having placeHolders for asyncio

    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    ptspArgs = {}
    
    #from playground.common.logging import EnablePresetLogging, PRESET_VERBOSE, PRESET_DEBUG
    #EnablePresetLogging(PRESET_VERBOSE)
    import OnlineBank
    OnlineBank.DEBUG = 0
        
    args= sys.argv[1:]
    i = 0
    for arg in args:
        if arg.startswith("-"):
                k,v = arg.split("=")
                ptspArgs[k]=v
        else:
                ptspArgs[i] = arg
                i+=1
    stack = ptspArgs.get("-stack","default")
    bankAddress = ptspArgs.get("-bankaddr", BANK_FIXED_PLAYGROUND_ADDR)
    bankPort = ptspArgs.get("-bankport", BANK_FIXED_PLAYGROUND_PORT)
            
    tracker = MobileCodeServerTracker()
    tracker.startScan()

    bankcert = loadCertFromFile(ptspArgs[0])
    payeraccount = ptspArgs[2]
    username = args[1]
    pw = getpass.getpass("Enter bank password for {}: ".format(username))

    bankstackfactory = lambda: BankClientProtocol(bankcert, username, pw)
    wallet = PayingClientWallet(stack, bankstackfactory, username, pw, payeraccount,
                                bankAddress, bankPort)

    clientAuth = SimplePayingClientAuth()
    PTSP = ParallelTSP(tracker, clientAuth, wallet, n=50)        
    def initShell():
        uiFactory = ParallelTSPCLI(PTSP)
        uiFactory.registerExitListener(lambda reason: loop.call_later(2.0, loop.stop))
        a = AdvancedStdio(uiFactory)

    # loop.set_debug(enabled=True)
    loop.call_soon(initShell)

    
    # TODO - Will switchAddr be changed to "localhost" ?
    # stack can be "default" or user provided stack from ~/.playgroun/connector
    
    
    #parallelMaster = MobileCodeClient(stack, switchAddr, port, samplecode, NullClientAuth(), NullClientWallet())
    #coro = playground.getConnector(stack).create_playground_connection(lambda: TwistedStdioReplacement.StandardIO(ParallelTSPCLI(configOptions, parallelMaster)),switchAddr, port)
    #transport, protocol = loop.run_until_complete(coro)
    loop.run_forever()
    tracker.stopScan()
    loop.close()
Пример #3
0
    return True


async def Payment_Init(src, dst, amount, memo):
    amount = int(amount)
    username = bank_username  # could override at the command line
    password = getpass.getpass("Enter password for {}: ".format(username))
    bank_client = BankClientProtocol(bank_cert, username, password)
    result = await example_transfer(bank_client, src, dst, amount, memo)

    if result:
        example_verify(bank_client, result.Receipt, result.ReceiptSignature,
                       dst, amount, memo)
        print("Receipt verified.")
        return result.Receipt, result.ReceiptSignature


if __name__ == "__main__":
    src, dst, amount, memo = sys.argv[1:5]
    amount = int(amount)
    username = bank_username  # could override at the command line
    password = getpass.getpass("Enter password for {}: ".format(username))
    bank_client = BankClientProtocol(bank_cert, username, password)
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(
        example_transfer(bank_client, src, dst, amount, memo))
    if result:
        example_verify(bank_client, result.Receipt, result.ReceiptSignature,
                       dst, amount, memo)
        print("Receipt verified.")
Пример #4
0
 def setBankClient(self):
     password = getpass.getpass("Enter password for {}: ".format(
         self.bank_username))
     self.bank_client = BankClientProtocol(self.bank_cert,
                                           self.bank_username, password)
Пример #5
0
class BankManager:
    def __init__(self):
        bankconfig = OnlineBankConfig()
        self.bank_addr = bankconfig.get_parameter("CLIENT", "bank_addr")
        self.bank_port = int(bankconfig.get_parameter("CLIENT", "bank_port"))
        # bank_stack = bankconfig.get_parameter("CLIENT", "stack", "default")
        self.bank_username = bankconfig.get_parameter("CLIENT", "username")
        self.certPath = os.path.join(bankconfig.path(), BANK_CERT_FILE_NAME)
        self.bank_cert = loadCertFromFile(self.certPath)
        self.bank_client = None

    async def connectToBank(self):
        if self.bank_client == None:
            self.setBankClient()
        await playground.create_connection(lambda: self.bank_client,
                                           self.bank_addr,
                                           self.bank_port,
                                           family='default')
        printx("bank manager connected to bank with username: {}".format(
            self.bank_client._BankClientProtocol__loginName))

    def setBankClient(self):
        password = getpass.getpass("Enter password for {}: ".format(
            self.bank_username))
        self.bank_client = BankClientProtocol(self.bank_cert,
                                              self.bank_username, password)

    async def transfer(self, src, dst, amount, memo):
        # 0. connect to bank
        await self.connectToBank()
        # 1. bank_client login
        try:
            await self.bank_client.loginToServer()
        except Exception as e:
            printError("Login error. {}".format(e))
            return (None, None)

        # 2. bank_client swtch account
        try:
            await self.bank_client.switchAccount(MY_ACCOUNT)
        except Exception as e:
            printError("Could not set source account as {} because {}".format(
                src, e))
            return (None, None)

        # 3. get transfer result
        try:
            result = await self.bank_client.transfer(dst, amount, memo)
        except Exception as e:
            printError("Could not transfer because {}".format(e))
            return (None, None)

        return (result.Receipt, result.ReceiptSignature)

    def receipt_verify(self, receipt_bytes, signature_bytes, dst, amount,
                       memo):
        self.bank_client = BankClientProtocol(self.bank_cert,
                                              self.bank_username, "testpass")
        # self.setBankClient()
        if not self.bank_client.verify(receipt_bytes, signature_bytes):
            # TODO: this func is not working as execpted
            printError("Bad receipt. Not correctly signed by bank")
            return False

        ledger_line = LedgerLineStorage.deserialize(receipt_bytes)
        if ledger_line.getTransactionAmount(dst) != amount:
            printError("Invalid amount. Expected {} got {}".format(
                amount, ledger_line.getTransactionAmount(dst)))
            return False
        elif ledger_line.memo(dst) != memo:
            printError("Invalid memo. Expected {} got {}".format(
                memo, ledger_line.memo()))
            return False
        printx('confirmed a receipt')
        return True
Пример #6
0
def main(args):
    EnablePresetLogging(PRESET_VERBOSE)

    team_list = []
    '''
    commands to win team to:
    1) "enter code to the coded lock"
    2) enter current time on your laptop
    3) "open chest"
    4) "get hammer from chest"
    5) "hit flyingkey with hammer" (do it till you hit it)
    6) "get key"
    7) "unlock door with key"
    8) "open door"
    '''
    commands = [
        "enter code to the coded lock",
        datetime.datetime.now().strftime("%H%M"), "open chest",
        "get hammer from chest", "hit flyingkey with hammer", "get key",
        "unlock door with key", "open door"
    ]
    team_list.append(
        Team(team_number='2', host='20194.2.57.98', port=2222, commands=None))
    '''
    commands to win team to:
    1) "look mirror"
    2) "look puzzle"
    3) "answer 368.2"
    4) "look mirror"
    5) "get hairpin"
    6) "unlock chest with hairpin"
    7) "open chest"
    8) "get hammer from chest"
    9) "get spear from chest"
    10) "hit flyingkey with hammer" (do it till you hit it)
    11) "hit flyingring with spear" (do it till you hit it)
    12) "get flyingkey"
    13) "get flyingring"
    14) "get glue"
    15) "combine flyingkey with flyingring using glue"
    16) "get key"
    17) "unlock door with key"
    18) "hit monster with hammer"
    19) "open door"
    
    '''
    commands = [
        "look mirror", "look puzzle", "answer 368.2", "look mirror",
        "get hairpin", "unlock chest with hairpin", "open chest",
        "get hammer from chest", "get spear from chest",
        "hit flyingkey with hammer", "hit flyingring with spear",
        "get flyingkey", "get flyingring", "get glue",
        "combine flyingkey with flyingring using glue", "get key",
        "unlock door with key", "hit monster with hammer", "open door"
    ]
    team_list.append(
        Team(team_number='3', host='20194.3.6.9', port=333, commands=None))
    '''
    commands to win team to:
    1) "look mirror"
    2) "get hairpin"
    3) "unlock chest with hairpin"
    4) "open chest"
    5) "get hammer from chest"
    6) "hit flyingkey with hammer" (do it till you hit it)
    7) "get key"
    8) "unlock door with key"
    9) "open door"

    '''
    team_list.append(Team(team_number='4', host='20194.4.4.4', port=8666))
    '''
    commands to win team to:
    1) "look mirror"
    2) "get hairpin"
    3) "unlock chest with hairpin"
    4) "open chest"
    5) "get hammer from chest"
    6) "hit flyingkey with hammer" (do it till you hit it)
    7) "get key"
    8) "unlock door with key"
    9) "open door"

    '''
    commands = [
        "look mirror", "get hairpin", "unlock chest with hairpin",
        "open chest", "get hammer from chest", "hit flyingkey with hammer",
        "get key", "unlock door with key", "open door"
    ]
    team_list.append(
        Team(team_number='5', host='20194.5.20.30', port=8989, commands=None))
    '''
    commands to win team to:
    1) "hit flyingkey with hammer" (do it till you hit it)
    2) "get key"
    3) "unlock door with key"
    4) "open door"

    '''
    commands = [
        "hit flyingkey with hammer", "get key", "unlock door with key",
        "open door"
    ]
    team_list.append(
        Team(team_number='6', host='20194.6.20.30', port=16666, commands=None))
    '''
    commands to win team to:
    0) "get shield"
    1) "look mirror"
    2) "get hairpin"
    3) "unlock chest with hairpin"
    4) "open chest"
    5) "get hammer from chest"
    6) "hit flyingkey with hammer" (do it till you hit it)
    7) "get key"
    8) "unlock door with key"
    9) "open door"

    '''
    commands = [
        "get shield", "look mirror", "get hairpin",
        "unlock chest with hairpin", "open chest", "get hammer from chest",
        "hit flyingkey with hammer", "get key", "unlock door with key",
        "open door"
    ]
    team_list.append(
        Team(team_number='9', host='20194.9.1.1', port=7826, commands=None))

    while True:
        team_number = input("Enter team number escaperoom you want to play: ")
        if team_number not in ['2', '3', '4', '5', '6', '9']:
            print('Invalid team number!')
            continue
        break

    for i in team_list:
        if team_number == i.team_number:
            host = i.host
            port = i.port
            commands = i.commands
            break

    print('host:', host)
    print('port:', port)
    bank_addr = '20194.0.1.1'
    bank_port = 888
    # username = input('Enter username: '******'Enter password for {}: '.format(username))
    # user_acct = input('Enter account name: ')
    user_acct = "sabdous1_account"
    bank_client = BankClientProtocol(bank_cert, username, password)
    loop = asyncio.get_event_loop()

    coro = playground.create_connection(
        lambda: GameClientProtocol(loop,
                                   bank_client,
                                   bank_addr,
                                   bank_port,
                                   username,
                                   user_acct,
                                   commands=commands,
                                   team_number=team_number),
        host=host,
        port=port,
        family=STACK)
    client = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    loop.close()
Пример #7
0
    def data_received(self, data):
        print('something received: ' + str(data))
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            print('Packet Received: ' + str(packet))

            if isinstance(packet, AutogradeTestStatus):
                # AutogradeTestStatus
                print('Packet Info: AutogradeTestStatus\n' + 'test_id: ' +
                      str(packet.test_id) + ' - ' + str(type(packet.test_id)) +
                      '\nsubmit_status: ' + str(packet.submit_status) + ' - ' +
                      str(type(packet.submit_status)) + '\nclient_status: ' +
                      str(packet.client_status) + ' - ' +
                      str(type(packet.client_status)) + '\nserver_status: ' +
                      str(packet.server_status) + ' - ' +
                      str(type(packet.server_status)) + '\nerror: ' +
                      str(packet.error) + ' - ' + str(type(packet.error)))
                if packet.submit_status == 1 and packet.client_status == 0:
                    new_packet = create_game_init_packet(username="******")
                    self.send_packet(packet=new_packet)

            elif isinstance(packet, GameRequirePayPacket):
                unique_id, dst, amount = process_game_require_pay_packet(
                    packet)
                print('Packet Info: CreateGameRequirePayPacket\n' +
                      '\nunique_id: ' + str(unique_id) + ' - ' +
                      str(type(packet.unique_id)) + '\naccount: ' + str(dst) +
                      ' - ' + str(type(packet.account)) + '\namount: ' +
                      str(amount) + ' - ' + str(type(packet.amount)))
                src = src_account
                username = bank_username  # could override at the command line
                password = getpass.getpass(
                    "Enter password for {}: ".format(username))
                bank_client = BankClientProtocol(bank_cert, username, password)
                self.loop.create_task(
                    self.transfer(bank_client=bank_client,
                                  src=src,
                                  dst=dst,
                                  amount=amount,
                                  memo=str(unique_id),
                                  transport=self.transport))

            elif isinstance(packet, GameResponsePacket):
                data, status = process_game_response(packet)
                print('Packet Info:\n' + 'response: ' + str(data) +
                      '\nstatus: ' + str(status))

                lines = data.split('\n')

                print('Data received: ' + str(lines))

                if not self.start_requesting:
                    self.start_requesting = True
                    self.loop.create_task(self.createAndSendCommand())
                if self.got_hammer and (not self.flying_key_is_hit) and all(
                        x in lines[0] for x in ["to the wall", "flyingkey"]):
                    self.flying_key_is_hit = True
                    command = "hit flyingkey with hammer"
                    new_packet = create_game_command(command=command)
                    self.send_packet(packet=new_packet)
            else:
                raise Exception()
Пример #8
0
    def data_received(self, data):
        print("client")
        self.deserializer.update(data)
        #print(self.deserializer.update(data))
        for pk in self.deserializer.nextPackets():
            print(pk)
            if pk.DEFINITION_IDENTIFIER == autograder.AutogradeTestStatus.DEFINITION_IDENTIFIER:
                print(pk.test_id)
                print(pk.submit_status)
                print(pk.client_status)
                print(pk.server_status)
                print(pk.error)
                stop = input()
                if pk.submit_status == autograder.AutogradeTestStatus.PASSED:
                    print("create init")
                    startpacket = gamepacket.create_game_init_packet(
                        self.username)
                    self.transport.write(startpacket.__serialize__())
                else:
                    print("no success create init")

            elif pk.DEFINITION_IDENTIFIER == gamepacket.GameRequirePayPacket.DEFINITION_IDENTIFIER:
                print(pk.unique_id)
                print(pk.account)
                print(pk.amount)
                self.unique_id = pk.unique_id  #memo
                self.dst_account = pk.account
                self.payment = int(pk.amount)
                password = "******"  #getpass.getpass("Enter password for {}: ".format(username))
                bank_client = BankClientProtocol(bhw.bank_cert, self.username,
                                                 password)
                print("trying connect bank")
                loop = asyncio.get_event_loop()

                task = loop.create_task(
                    bhw.example_transfer(bank_client, self.src_account,
                                         self.dst_account, self.payment,
                                         self.unique_id))
                task.add_done_callback(self.finish)
                '''
                if result:
                    print("get receipt")
                    receipt = result.Receipt
                    receipt_signature= result.ReceiptSignature
                    print(receipt)
                    print(receipt_signature)
                    receipt_packet = create_game_pay_packet(receipt,receipt_signature)
                    self.transport.write(receipt_packet.__serialize__())
                    print("send receipt!")
                    #bhw.example_verify(bank_client, result.Receipt, result.ReceiptSignature, dst, amount, memo)
                    #print("Receipt verified.")

                #create_game_require_pay_packet
                #get receipt
                '''
            elif pk.DEFINITION_IDENTIFIER == gamepacket.GameResponsePacket.DEFINITION_IDENTIFIER:
                #print(pk.gameover)
                #self.printpacket(pk)
                #print(pk.status())
                print(pk.response)
                if self.session < 9 and self.session != 5:
                    self.send_gamepacket()
                elif self.session == 5:
                    if pk.response.split(" ")[-1] == "wall":
                        self.send_gamepacket()
                    else:
                        pass
            else:
                for field in pkt.FIELDS:
                    fname = field[0]
                    print(fname + str(pkt._fields[fname]._data))
                print("what's that?")
Пример #9
0
 def __init__(self):
     #username = "******" # could override at the command line
     #password = getpass.getpass("Enter password for {}: ".format(username))
     bank_client = BankClientProtocol(bank_cert, "", "")
     self.bank_client = bank_client
     self.verification = False
Пример #10
0
    def data_received(self, data):
        #print(data)
        dd = PacketType.Deserializer()
        dd.update(data)
        for recvpack in dd.nextPackets():
            #print(recvpack.DEFINITION_IDENTIFIER)
            if recvpack.DEFINITION_IDENTIFIER == '20194.exercise6.autogradesubmitresponse':
                print(recvpack.test_id, recvpack.submit_status,
                      recvpack.client_status, recvpack.server_status,
                      recvpack.error)
                if (self.fla == 0):
                    pack1 = create_game_init_packet(self.username)
                    self.transport.write(pack1.__serialize__())
                    print('Sent username packet.')
                    self.fla = 1
                continue

            if process_game_require_pay_packet(recvpack):
                #if recvpack.DEFINITION_IDENTIFIER=='20194.requirepaypacket':
                print('Received Required Payment meg: ', recvpack.unique_id,
                      recvpack.account, recvpack.amount)
                password = getpass.getpass("Enter password for {}: ".format(
                    self.username))
                bank_client = BankClientProtocol(bank_cert, self.username,
                                                 password)
                # result=loop.run_until_complete(example_transfer(bank_client, self.useraccount,
                # 	 recvpack.account, recvpack.amount, recvpack.unique_id, self.transport))
                asyncio.ensure_future(
                    example_transfer(bank_client, self.useraccount,
                                     recvpack.account, recvpack.amount,
                                     recvpack.unique_id, self.transport))
                print('BBBBBBBBBBBBBB.')
                # pack1= create_game_pay_packet(result.Receipt, result.ReceiptSignature)
                # self.transport.write(pack1.__serialize__())
                # print('Sent payment proof packet.')
                # if result:
                # 	print('BBBBBBBBBBBBBB.')
                # 	pack1= create_game_pay_packet(result.Receipt, result.ReceiptSignature)
                # 	self.transport.write(pack1.__serialize__())
                # 	print('Sent payment proof packet.')
                # else:
                # 	print('EEfffEeeee.')
                continue

            if (recvpack.DEFINITION_IDENTIFIER
                    == 'gamecommunication') and (recvpack.zenith_nadir == 1):
                print('Received game response: ', recvpack.gameresponse,
                      '\t  ', recvpack.statusgame)
                if (recvpack.gameresponse != '') and (recvpack.statusgame !=
                                                      'dead'):
                    if self.es_iter < len(self.escapestep):
                        if self.es_iter != self.es_itst:
                            packk = create_game_command(
                                self.escapestep[self.es_iter])
                            print('Sent game command: ',
                                  self.escapestep[self.es_iter])
                            self.transport.write(packk.__serialize__())
                            self.es_iter += 1
                        else:
                            seli = recvpack.gameresponse.split(' ')
                            if (seli[-1] == 'wall'):
                                packk = create_game_command(
                                    self.escapestep[self.es_iter])
                                print('Sent game command: ',
                                      self.escapestep[self.es_iter])
                                self.transport.write(packk.__serialize__())
                                self.es_iter += 1
                continue

            print('Warning: None of the packet Type fits.')