Exemple #1
0
def main():

    # create the APIs
    txs = TransactionApi(HOST, PORT)
    tokens = TokenApi(HOST, PORT)

    # generate a random identity
    identity = Identity()

    print('Balance Before:', tokens.balance(identity.public_key))

    # create and send the transaction to the ledger capturing the tx hash
    tx = tokens.wealth(identity.private_key_bytes, 1000)

    # wait while we poll to see when this transaction has been completed
    prev_status = None
    while True:
        status = txs.status(tx)

        # print the changes in tx status
        if status != prev_status:
            print('Current Status:', status)
            prev_status = status

        # exit the wait loop once the transaction has been executed
        if status == "Executed":
            break

        time.sleep(1)

    # check the balance now
    print('Balance After:', tokens.balance(identity.public_key))
 def __init__(self, public_key: str, oef_addr: str, oef_port: int = 3333):
     super().__init__(public_key, oef_addr, oef_port)
     self.identity = Identity()
     self.txs = TransactionApi("ledger.economicagents.com" , 80)
     self.tokens = TokenApi("ledger.economicagents.com" , 80)
     print('Submitting wealth creation...')
     self.wait_for_tx(self.txs, self.tokens.wealth(self.identity.private_key_bytes, 1000))
     self.cost = 0
     self.pending_cfp = 0
     self.received_proposals = []
     self.received_declines = 0
Exemple #3
0
 def track_cost(self, api: TokenApi, entity: Entity, message: str):
     """
     Context manager for recording the change in balance over a set of actions.
     Will be inaccurate if other factors change an account balance.
     """
     if isinstance(entity, Entity):
         entity = Address(entity)
     elif not isinstance(entity, Address):
         raise TypeError("Expecting Entity or Address")
     balance_before = api.balance(entity)
     yield
     if not message:
         message = "Actions cost: "
     print(message + "{} TOK".format(api.balance(entity) - balance_before))
Exemple #4
0
    def setUp(self) -> None:
        self.entity = Entity()
        self.address = Address(self.entity)
        self.to_address = Address(Entity())

        with patch('requests.session') as mock_session:
            self.api = TokenApi('127.0.0.1', 8000)
Exemple #5
0
    def __init__(self,
                 public_key: str,
                 oef_addr: str,
                 db_source: str,
                 oef_port: int = 3333):
        super().__init__(public_key, oef_addr, oef_port)

        self.scheme = {}
        self.scheme['country'] = None
        self.scheme['city'] = None
        self.description = None
        self.db = db_communication.Db_communication(db_source)
        self.identity = Identity()
        self.tokens = TokenApi("ledger.economicagents.com", 80)
        self.balance = self.tokens.balance(self.identity.public_key)
        self.fetched_data = None
        self.price_per_row = 0.02
        self.totalPrice = 0
Exemple #6
0
def main():
    # create the APIs
    txs = TransactionApi(HOST, PORT)
    tokens = TokenApi(HOST, PORT)

    # generate a random identity
    identity1 = Identity()
    identity2 = Identity()

    # create the balance
    print('Submitting wealth creation...')
    wait_for_tx(txs, tokens.wealth(identity1.private_key_bytes, 1000))

    # submit and wait for the transfer to be complete
    print('Submitting transfer...')
    wait_for_tx(
        txs,
        tokens.transfer(identity1.private_key_bytes,
                        identity2.public_key_bytes, 250))

    print('Balance 1:', tokens.balance(identity1.public_key))
    print('Balance 2:', tokens.balance(identity2.public_key))
Exemple #7
0
class WeatherAgent(OEFAgent):
    def __init__(self,
                 public_key: str,
                 oef_addr: str,
                 db_source: str,
                 oef_port: int = 3333):
        super().__init__(public_key, oef_addr, oef_port)

        self.scheme = {}
        self.scheme['country'] = None
        self.scheme['city'] = None
        self.description = None
        self.db = db_communication.Db_communication(db_source)
        self.identity = Identity()
        self.tokens = TokenApi("ledger.economicagents.com", 80)
        self.balance = self.tokens.balance(self.identity.public_key)
        self.fetched_data = None
        self.price_per_row = 0.02
        self.totalPrice = 0

    def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int,
               query: CFP_TYPES):
        """Send a simple Propose to the sender of the CFP."""
        print("[{0}]: Received CFP from {1}".format(self.public_key, origin))

        print(query.constraints[0].constraint.values)

        self.fetched_data = self.db.specific_dates(
            query.constraints[0].constraint.values[0],
            query.constraints[0].constraint.values[1])
        if len(self.fetched_data) >= 1:
            print(len(self.fetched_data))
            self.totalPrice = self.price_per_row * len(self.fetched_data)
            proposal = Description({
                "Rows": len(self.fetched_data),
                "Price": self.totalPrice
            })
            print("[{}]: Sending propose at price: {}".format(
                self.public_key, self.totalPrice))
            self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                              [proposal])
        else:
            #self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [])
            self.send_decline(msg_id + 1, dialogue_id, origin, target + 1)

    def on_accept(self, msg_id: int, dialogue_id: int, origin: str,
                  target: int):
        """Once we received an Accept, send the requested data."""
        print("[{0}]: Received accept from {1}.".format(
            self.public_key, origin))

        command = {}
        command['Public_Key'] = binascii.hexlify(
            self.identity.public_key_bytes).decode()
        msg = json.dumps(command)
        self.send_message(0, dialogue_id, origin, msg.encode())

    def on_decline(self, msg_id: int, dialogue_id: int, origin: str,
                   target: int):
        print("declined")

    def on_message(self, msg_id: int, dialogue_id: int, origin: str,
                   content: bytes):
        data = json.loads(content.decode())

        if data['Command'] == "Executed":
            correct_balance = self.balance + int(self.totalPrice)

            if correct_balance == self.tokens.balance(
                    self.identity.public_key):
                print("Success")
                self.balance = correct_balance
                print(self.balance)
                command = {}
                command['Command'] = "success"
                command['fetched_data'] = []

                for items in self.fetched_data:
                    dict_of_data = {}
                    dict_of_data['abs_pressure'] = items[0]
                    dict_of_data['delay'] = items[1]
                    dict_of_data['hum_in'] = items[2]
                    dict_of_data['hum_out'] = items[3]
                    dict_of_data['idx'] = time.ctime(int(items[4]))
                    dict_of_data['rain'] = items[5]
                    dict_of_data['temp_in'] = items[6]
                    dict_of_data['temp_out'] = items[7]
                    dict_of_data['wind_ave'] = items[8]
                    dict_of_data['wind_dir'] = items[9]
                    dict_of_data['wind_gust'] = items[10]
                    command['fetched_data'].append(dict_of_data)

                msg = json.dumps(command)
                print("Sending Data")
                self.send_message(0, dialogue_id, origin, msg.encode())
            else:
                print("Fail")
                command = {}
                command['Command'] = "fail"
                msg = json.dumps(command)
                self.send_message(0, dialogue_id, origin, msg.encode())
class ClientAgent(OEFAgent):
    """
    The class that defines the behaviour of the echo client agent.
    """
    def __init__(self, public_key: str, oef_addr: str, oef_port: int = 3333):
        super().__init__(public_key, oef_addr, oef_port)
        self.identity = Identity()
        self.txs = TransactionApi("ledger.economicagents.com" , 80)
        self.tokens = TokenApi("ledger.economicagents.com" , 80)
        print('Submitting wealth creation...')
        self.wait_for_tx(self.txs, self.tokens.wealth(self.identity.private_key_bytes, 1000))
        self.cost = 0
        self.pending_cfp = 0
        self.received_proposals = []
        self.received_declines = 0
    
    def wait_for_tx(self, txs: TransactionApi, tx: str):
        while True:
            if txs.status(tx) == "Executed":
                break
        time.sleep(1)  



    def on_message(self, msg_id: int, dialogue_id: int, origin: str, content: bytes):
        #print("Received message: origin={}, dialogue_id={}, content={}".format(origin, dialogue_id, content))
        data = json.loads(content.decode())
        #print(data)
        if "Public_Key" in data.keys():
            self.make_the_payment(data, origin, dialogue_id)
        if "Command" in data.keys() :
            if data['Command'] == "success" :
                for items in data['fetched_data'] :
                    #print(items)
                    pass
                #print(data['fetched_data'])
                self.stop()

            if "fail" in data.keys() :
                pass
                self.stop()
                

    def make_the_payment(self, data, origin,dialogue_id) :
        print("sending the correct amount")
        self.wait_for_tx(self.txs, self.tokens.transfer(self.identity.private_key_bytes,
                                               binascii.unhexlify(data['Public_Key'].encode()),
                                               self.cost))

        print("Sending executed command")
                
        command = {}
        command['Command'] = "Executed"

        print(self.tokens.balance(self.identity.public_key))
        msg = json.dumps(command)
        self.send_message(0,dialogue_id,origin,msg.encode())
       

    def on_search_result(self, search_id: int, agents: List[str]):
        """For every agent returned in the service search, send a CFP to obtain resources from them."""
        if len(agents) == 0:
            print("[{}]: No agent found. Stopping...".format(self.public_key))
            self.stop()
            return

        print("[{0}]: Agent found: {1}".format(self.public_key, agents))

        for agent in agents:
            
            print("[{0}]: Sending to agent {1}".format(self.public_key, agent))
            # we send a 'None' query, meaning "give me all the resources you can propose."
            query = Query([Constraint("Date", Range( ("20/3/2019","21/3/2019") ))])
            self.pending_cfp += 1
            self.send_cfp(1, 0, agent, 0, query)

    def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES):
        """When we receive a Propose message, answer with an Accept."""
        print("[{0}]: Received propose from agent {1}".format(self.public_key, origin))
       #print(dialogue_id)
       
        for i,p in enumerate(proposals):
            self.received_proposals.append({"agent" : origin, 
                                            "proposal":p.values})
        received_cfp = len(self.received_proposals) + self.received_declines 
        print(received_cfp)
        print(received_cfp == self.pending_cfp)
        print(self.pending_cfp)


        if received_cfp == self.pending_cfp :
            print("I am here")
            if len( self.received_proposals) >= 1 :
                self.received_proposals = sorted(self.received_proposals, key= lambda i : int(i['proposal']['Price']))
            
                
                for i in range(1 , len(self.received_proposals)) :
                    print("Sending decline !")
                    self.send_decline(msg_id,dialogue_id, self.received_proposals[i]['agent'],msg_id + 1)
               
                self.cost = int(self.received_proposals[0]['proposal']['Price'])    
                self.send_accept(msg_id,dialogue_id,self.received_proposals[0]['agent'],msg_id + 1)
            else : 
                print("They don't have data")
                self.stop()

    def on_decline(self, msg_id: int, dialogue_id: int, origin: str, target: int) :
        print("Received a decline!")
        self.received_declines += 1