Exemple #1
0
def main():
    # In examples we use addresses which already have funds
    entity1 = Entity.from_hex(
        '6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b')
    entity2 = Entity.from_hex(
        'e833c747ee0aeae29e6823e7c825d3001638bc30ffe50363f8adf2693c3286f8')

    address1 = Address(entity1)

    # create a second private key pair
    address2 = Address(entity2)

    # build the ledger API
    api = LedgerApi('127.0.0.1', 8000)

    # create the smart contract
    contract = Contract(CONTRACT_TEXT, entity1)

    with track_cost(api.tokens, entity1, "Cost of creation: "):
        api.sync(contract.create(api, entity1, 4000))

    # print the current status of all the tokens
    print('-- BEFORE --')
    print_address_balances(api, contract, [address1, address2])

    # transfer from one to the other using our newly deployed contract
    tok_transfer_amount = 200
    fet_tx_fee = 160
    with track_cost(api.tokens, entity1, "Cost of transfer: "):
        api.sync(
            contract.action(api, 'transfer', fet_tx_fee, entity1, address1,
                            address2, tok_transfer_amount))

    print('-- AFTER --')
    print_address_balances(api, contract, [address1, address2])
Exemple #2
0
def main(source, name):
    # Create keypair for the contract owner
    provider1 = Entity()
    address1 = Address(provider1)
    provider2 = Entity()
    address2 = Address(provider2)

    scooter1 = Entity()
    scooter_address1 = Address(scooter1)

    # Setting API up
    api = LedgerApi('127.0.0.1', 8100)

    # Need funds to deploy contract
    api.sync(api.tokens.wealth(provider1, 59000000))

    # Create contract
    contract = SmartContract(source)

    # Deploy contract
    api.sync(api.contracts.create(provider1, contract, 2456766))

    if name.endswith("contract.etch"):
        contract.action(api, 'addProvider', 2456766, [provider2, provider1], address2, address1)
        contract.action(api, 'addScooter', 2456766, [provider2, provider1], address2, address1, 22, 1)

        print("Wait for txs to be mined ...")
        time.sleep(5)

        # Printing balance of the creating address1
        print(contract.query(api, 'getFleetSize'), " scooter in fleet")
Exemple #3
0
def main():
    # create the API
    api = LedgerApi('127.0.0.1', 8000)

    # create an entity from a private key stored in hex
    entity = Entity.from_hex(
        '6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b')

    # create the contract on the ledger
    synergetic_contract = Contract(CONTRACT_TEXT, entity)
    print('Creating contract..')
    api.sync(api.contracts.create(entity, synergetic_contract, 4096))

    # create a whole series of random data to submit to the DAG
    random_ints = [random.randint(0, 200) for _ in range(10)]
    fee = 100000000
    api.sync(
        [api.contracts.submit_data(entity, synergetic_contract.digest, synergetic_contract.address, fee, value=value) \
         for value in random_ints])
    print('Data submitted.')

    print('Waiting...')
    api.wait_for_blocks(10)

    print('Issuing query...')
    result = synergetic_contract.query(api, 'query_result')
    print('Query result:', result)
def main():
    # load up the previously created private key
    with open('private.key', 'r') as private_key_file:
        entity1 = Entity.prompt_load(private_key_file)

    # load up the deployed contract
    with open('sample.contract', 'r') as contract_file:
        contract = Contract.load(contract_file)

    # for the purposes of this example create a second private key pair to transfer funds to
    entity2 = Entity()

    # build the ledger API
    api = LedgerApi('127.0.0.1', 8000)

    # print the current status of all the tokens
    print('-- BEFORE --')
    print_address_balances(api, contract, [entity1, entity2])

    # transfer from one to the other using our newly deployed contract
    tok_transfer_amount = 200
    fet_tx_fee = 40
    api.sync(
        contract.action(api, 'transfer',
                        fet_tx_fee, [entity1], Address(entity1),
                        Address(entity2), tok_transfer_amount))

    print('-- AFTER --')
    print_address_balances(api, contract, [entity1, entity2])
def run(options, benefactor):
    # Create keypair for the contract owner
    entity = Entity()
    address = Address(entity)

    # build the ledger API
    api = LedgerApi(options['host'], options['port'])

    # Need funds to deploy contract
    api.sync(api.tokens.transfer(benefactor, entity, int(1e7), 1000))

    # Load contract source
    source_file = os.path.join(HERE, "contract.etch")
    with open(source_file, "r") as fb:
        source = fb.read()

    # Create contract
    contract = Contract(source, entity)

    # Deploy contract
    fet_tx_fee = api.tokens.balance(entity)
    api.sync(api.contracts.create(entity, contract, fet_tx_fee))

    # Printing balance of the creating address
    print(contract.query(api, 'balanceOf', owner=address))

    # Getting the 9'th token id.
    token_id = contract.query(api, 'getTokenId', number=9)

    # Testing
    contract.query(api, 'isEqual', number=9, expected=token_id)

    # Locating the owner of a token
    print("Finding the owner of ", token_id)
    print(contract.query(api, 'ownerOf', token_id=token_id))
Exemple #6
0
def run(options, benefactor):
    # Create keypair for the contract owner
    entity = Entity()
    Address(entity)

    host = options['host']
    port = options['port']

    # create the APIs
    api = LedgerApi(host, port)

    # Transfer tokens from benefactor
    api.sync(api.tokens.transfer(benefactor, entity, int(1e7), 1000))

    # Load contract source
    source_file = os.path.join(HERE, "hello_world.etch")
    with open(source_file, "r") as fb:
        source = fb.read()

    # Create contract
    contract = Contract(source, entity)

    # Deploy contract
    api.sync(api.contracts.create(entity, contract, 10000))

    # Printing message
    print(contract.query(api, 'persistentGreeting'))
def create_balance(parameters, test_instance):
    nodes = parameters["nodes"]
    amount = parameters["amount"]

    for node_index in nodes:
        node_host = "localhost"
        node_port = test_instance._nodes[node_index]._port_start

        api = LedgerApi(node_host, node_port)

        # create the entity from the node's private key
        entity = Entity(get_nodes_private_key(test_instance, node_index))

        tx = api.tokens.transfer(test_instance._benefactor_entity, entity,
                                 amount, BASE_TX_FEE)

        for i in range(10):
            output('Create balance of: ', amount)
            api.sync(tx, timeout=120, hold_state_sec=20)
            for j in range(5):
                b = api.tokens.balance(entity)
                output('Current balance: ', b)
                if b >= amount:
                    return
                time.sleep(5)
            time.sleep(5)
        raise Exception("Failed to send funds to node!")
def generate_fetchai_wealth(arguments: argparse.Namespace) -> None:
    """
    Generate tokens to be able to make a transaction.

    :param arguments: the arguments
    :return: None
    """
    try:
        api = LedgerApi(arguments.addr, arguments.port)
    except Exception:
        logging.info("Couldn't connect! Please check your add and port.")
        sys.exit(1)

    try:
        if arguments.private_key is None or arguments.private_key == "":
            raise ValueError
    except ValueError:
        logging.error("Please provide a private key. --private-key .... ")
        sys.exit(1)

    logging.info("Waiting for token wealth generation...")
    entity_to_generate_wealth = Entity.from_hex(
        Path(arguments.private_key).read_text())
    api.sync(api.tokens.wealth(entity_to_generate_wealth, arguments.amount))
    address = Address(entity_to_generate_wealth)
    balance = api.tokens.balance(address)
    logging.info('The new balance of the address {} is : {} FET'.format(
        address, balance))
def call(name: str) -> SmartContract:
    # Create keypair for the contract owner
    provider1 = Entity()
    address1 = Address(provider1)

    # Setting API up
    api = LedgerApi('185.91.52.11', 10002)

    # Need funds to deploy contract
    api.sync(api.tokens.wealth(provider1, 59000000))

    with open(name, "r") as fb:
        source = fb.read()

    # Create contract
    contract = SmartContract(source)

    # Deploy contract
    api.sync(api.contracts.create(provider1, contract, 2456766))

    print("Wait for txs to be mined ...")
    time.sleep(5)

    # Printing balance of the creating address1
    print(contract.query(api, 'getAccountRides', acc_id="1"))
Exemple #10
0
def main(source, name):
    # Constellation
    HOST = '127.0.0.1'
    PORT = 8100

    # deploy the contract to the network
    api = LedgerApi(HOST, PORT)
    # api = LedgerApi(network='alphanet')

    # Create keypair for the contract owner
    owner = Entity()
    owner_addr = Address(owner)
    # print(owner_addr)

    # Need funds to deploy contract
    api.sync(api.tokens.wealth(owner, 20000))

    # Create contract
    contract = Contract(source, owner)

    # Deploy contract
    api.sync(api.contracts.create(owner, contract, 10000))

    # Save the contract to the disk
    with open('sample.contract', 'w') as contract_file:
        contract.dump(contract_file)

    # Save the contract owner's private key to disk
    with open('owner_private.key', 'w') as private_key_file:
        owner.dump(private_key_file)

    print(f"Contract {name}.etch has successfully been deployed.")
def main(source):
    # Create keypair for the contract owner
    entity = Entity()
    address = Address(entity)

    # Setting API up
    api = LedgerApi('127.0.0.1', 8100)

    # Need funds to deploy contract
    api.sync(api.tokens.wealth(entity, 5000000))

    # Create contract
    contract = SmartContract(source)

    # Deploy contract
    api.sync(api.contracts.create(entity, contract, 2456766))

    # Printing balance of the creating address
    print(contract.query(api, 'balanceOf', owner=address))

    # Getting the 9'th token id.
    token_id = contract.query(api, 'getTokenId', number=9)

    # Testing
    contract.query(api, 'isEqual', number=9, expected=token_id)

    # Locating the owner of a token
    print("Finding the owner of ", token_id)
    print(contract.query(api, 'ownerOf', token_id=token_id))
Exemple #12
0
def main():

    print('Loading private key...')

    # load up the previously created private key
    with open('private.key', 'r') as private_key_file:
        entity1 = Entity.load(private_key_file)

    print('Loading private key...complete')

    # build the ledger API
    api = LedgerApi('127.0.0.1', 8000)

    # create the smart contract
    contract = SmartContract(CONTRACT_TEXT)

    print('Deploying contract...')

    # deploy the contract to the network
    api.sync(api.contracts.create(entity1, contract, 2000))

    print('Deploying contract...complete')

    # save the contract to the disk
    with open('sample.contract', 'w') as contract_file:
        contract.dump(contract_file)
class InitLedger(OEFAgent):
    """Class that implements the behaviour of the charger agent."""
    def __init__(self, *args, **kwargs):
        super(InitLedger, self).__init__(*args, **kwargs)

        self._entity = Entity()
        self._address = Address(self._entity)

        with open("../02_full_contract.etch", "r") as fb:
            self._source = fb.read()

        self.prepare_contract()

    def prepare_contract(self):
        # Setting API up
        self._api = LedgerApi('127.0.0.1', 8100)

        # Need funds to deploy contract
        self._api.sync(self._api.tokens.wealth(self._entity, 5000000))

        # Create contract
        self._contract = SmartContract(self._source)

        # Deploy contract
        self._api.sync(
            self._api.contracts.create(self._entity, self._contract, 2456766))

        ff = open('contract.txt', 'w')
        ff.write(str(self._contract._digest) + "\n")
        ff.write(str(Address(self._entity)))
        ff.close()
Exemple #14
0
def releaseEscrew(entity1, contract, entity2):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    api.sync(contract.action(api, 'releaseEscrew', fet_tx_fee,
                             [entity1], entity2,
                             ))
    print("Escrew Released.")
Exemple #15
0
class TransportAgent(OEFAgent):
    """Class that implements the behaviour of the scooter agent."""

    scooter_description = Description(
        {
            "price_per_km": True,
        },
        JOURNEY_MODEL
    )

    def __init__(self, data, *args, **kwargs):
        super(TransportAgent, self).__init__(*args, **kwargs)
        self.data = data
        self._entity = Entity()
        self._address = Address(self._entity)

    #      with open("./full_contract.etch", "r") as fb:
    #          self._source = fb.read()

    #      self.prepare_contract()

    def prepare_contract(self):
        # Setting API up
        self._api = LedgerApi('185.91.52.11', 10002)

        # Need funds to deploy contract
        self._api.sync(self._api.tokens.wealth(self._entity, 5000000))

        # Create contract
        self._contract = SmartContract(self._source)

        # Deploy contract
        self._api.sync(self._api.contracts.create(self._entity, self._contract, 2456766))

    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))

        price = 1

        # prepare the proposal with a given price.
        proposal = Description({"price_per_km": price})
        print("[{}]: Sending propose at price: {}".format(self.public_key, price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])

    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))

        # Preparing contract
        # PLACE HOLDER TO PREPARE AND SIGN TRANSACTION
        contract = {"contract": "data"}

        # Sending contract
        encoded_data = json.dumps(contract).encode("utf-8")
        print("[{0}]: Sending contract to {1}".format(self.public_key, origin))
        self.data['status'] = 'RIDES'
        self.send_message(0, dialogue_id, origin, encoded_data)
Exemple #16
0
def submitSynergy(entity, values):
    api = LedgerApi(HOST, 8100)
    synergy_contract = SynergeticContract(SYNERGYSTIC)
    print(synergy_contract.digest)

    api.sync(api.contracts.create(entity, synergy_contract, 4096))

    api.sync([api.synergetic.submit_data(entity, synergy_contract.digest, value=value) for value in values])

    return synergy_contract
Exemple #17
0
def setEscrew(entity, contract, amount):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    print('-- BEFORE --')
    print_address_balances(api, contract, [entity])
    api.sync(contract.action(api, 'setEscrew', fet_tx_fee,
                              [entity], Address(entity),
                              amount))
    print('-- AFTER --')
    print_address_balances(api, contract, [entity])
Exemple #18
0
def main(source, name):
    # Create keypair for the contract owner
    charge_provider1 = Entity()
    charge_address1 = Address(charge_provider1)
    charge_provider2 = Entity()
    charge_address2 = Address(charge_provider2)

    parking_provider1 = Entity()
    parking_address1 = Address(parking_provider1)
    parking_provider2 = Entity()
    parking_address2 = Address(parking_provider2)

    charge1 = Entity()
    charge_station_address1 = Address(charge1)

    parking1 = Entity()
    parking_place_address1 = Address(parking1)

    # Setting API up
    api = LedgerApi('127.0.0.1', 8100)

    # Need funds to deploy contract
    api.sync(api.tokens.wealth(charge_provider1, 59000000))

    # Create contract
    contract = SmartContract(source)

    # Deploy contract
    api.sync(api.contracts.create(charge_provider1, contract, 2456766))

    if name.endswith("contract.etch"):
        contract.action(api, 'addChargeProvider', 2456766,
                        [charge_provider2, charge_provider1], charge_address2,
                        charge_address1)
        contract.action(api, 'addCharge', 2456766,
                        [charge_provider2, charge_provider1], charge_address2,
                        charge_address1, 22, 1)

        print("Wait for charge txs to be mined ...")
        time.sleep(5)

        # Printing balance of the creating address1
        print(contract.query(api, 'getChargeFleetSize'), " charge in fleet")
        contract.action(api, 'addParkingProvider', 2456766,
                        [parking_provider2, parking_provider1],
                        parking_address2, parking_address1)
        contract.action(api, 'addParking', 2456766,
                        [parking_provider2, parking_provider1],
                        parking_address2, parking_address1, 22, 1)

        print("Wait for parking txs to be mined ...")
        time.sleep(5)

        # Printing balance of the creating address1
        print(contract.query(api, 'getParkingFleetSize'), " parking in fleet")
Exemple #19
0
def create_wealth(parameters, test_instance):
    nodes = parameters["nodes"]
    amount = parameters["amount"]

    for node_index in nodes:
        node_host = "localhost"
        node_port = test_instance._nodes[node_index]._port_start

        api = LedgerApi(node_host, node_port)

        # create the entity from the node's private key
        entity = Entity(get_nodes_private_key(test_instance, node_index))
        api.sync(api.tokens.wealth(entity, amount))
def releaseEscrew(entity1, contract, entity2):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    api.sync(
        contract.action(
            api,
            'releaseEscrew',
            fet_tx_fee,
            [entity1],
            Address(entity2),
        ))
    print("Escrew Released.")
    print_address_balances(api, contract, [entity1, entity2])
Exemple #21
0
def run(options, benefactor):
    entity1 = Entity()
    api = LedgerApi(options['host'], options['port'])

    api.sync(api.tokens.transfer(benefactor, entity1, 100000, 1000))

    contract = Contract(CONTRACT_TEXT, entity1)

    try:
        api.sync([contract.action(api, 'some_action', 100, entity1)])
        assert False, 'Expected action to fail'
    except RuntimeError as e:
        assert 'Contract Lookup Failure' in str(e), \
            'Unexpected error message from server: {}'.format(e)
Exemple #22
0
def deployContract(entity):
    api = LedgerApi(HOST, 8100)

    # create the smart contract
    contract = Contract(CONTRACT_TEXT)

    print('Deploying contract...')

    # deploy the contract to the network
    api.sync(api.contracts.create(entity, contract, 6000))

    print('Deploying contract...complete')

    return contract
Exemple #23
0
def run(options):
    entity1 = Entity()

    # build the ledger API
    api = LedgerApi(options['host'], options['port'])

    # create wealth so that we have the funds to be able to create contracts on the network
    print('Create wealth...')
    api.sync(api.tokens.wealth(entity1, 100000000))

    contract = Contract(CONTRACT_TEXT, entity1)

    # deploy the contract to the network
    print('Create contract...')
    api.sync(api.contracts.create(entity1, contract, 10000))

    api.sync(api.tokens.transfer(entity1, contract.address, 10000, 500))

    submit_synergetic_data(api, contract, [100, 20, 3], entity1)

    print('Query init state...')
    init_result = contract.query(api, 'query_init_test')
    print('Init state: ', init_result)
    assert init_result == 123

    print('Execute action...')
    api.sync(contract.action(api, 'action_test', 10000, [entity1]))

    print('Query action state...')
    action_result = contract.query(api, 'query_action_test')
    print('Action state: ', action_result)
    assert action_result == 456
Exemple #24
0
def run(options):
    entity1 = Entity()

    # create the APIs
    api = LedgerApi(options['host'], options['port'])

    api.sync(api.tokens.wealth(entity1, 1000000))

    contract = Contract(CONTRACT_TEXT, entity1)
    contract2 = Contract(CONTRACT_TEXT2, entity1)

    api.sync(api.contracts.create(entity1, contract, 20000))
    api.sync(api.contracts.create(entity1, contract2, 20000))

    current_block = api.tokens._current_block_number()

    api.sync(
        contract.action(api, 'c2c_call', 40000, [entity1],
                        str(contract2.address)))

    time.sleep(2)

    later_block = contract.query(api, 'query_block_number_state')
    assert later_block > current_block, \
        'Expected number larger than {}, found {}'.format(
            current_block, later_block)
Exemple #25
0
def run(options, benefactor):
    entity1 = Entity()
    api = LedgerApi(options['host'], options['port'])

    api.sync(api.tokens.transfer(benefactor, entity1, 100000, 1000))

    contract = Contract(CONTRACT_TEXT, entity1)

    try:
        contract.query(api, 'some_query')
        assert False, 'Expected query to fail'
    except RuntimeError as e:
        assert 'Unable to look up contract' in str(e), \
            'Unexpected error message from server: {}'.format(e)
Exemple #26
0
def run(options, benefactor):
    entity1 = Entity()
    api = LedgerApi(options['host'], options['port'])
    api.sync(api.tokens.transfer(benefactor, entity1, 100000000, 1000))
    contract = Contract(CONTRACT_TEXT, entity1)

    api.sync(api.contracts.create(entity1, contract, 10000))

    result = contract.query(api, 'check_x_with_default')
    assert result == 999,\
        'Expected to receive default value of 999, got {}'.format(result)
    try:
        contract.query(api, 'check_x')
        assert False, 'Expected query to fail'
    except RuntimeError:
        pass

    api.sync(contract.action(api, 'set_x_to_3', 200, entity1))

    result = contract.query(api, 'check_x_with_default')
    assert result == 3, \
        'Expected to receive value of 3, got {}'.format(result)
    result = contract.query(api, 'check_x')
    assert result == 3, \
        'Expected to receive value of 3, got {}'.format(result)

    api.sync(contract.action(api, 'set_x_to_5', 200, entity1))

    result = contract.query(api, 'check_x_with_default')
    assert result == 5, \
        'Expected to receive value of 5, got {}'.format(result)
    result = contract.query(api, 'check_x')
    assert result == 5, \
        'Expected to receive value of 5, got {}'.format(result)
Exemple #27
0
def run(options):
    ENDPOINT = 'fetch/token/transfer'
    HOST = options['host']
    PORT = options['port']

    # create the APIs
    api = LedgerApi(HOST, PORT)

    # Hardcoded private keys
    id1PrivateKey = "d222867ac019aa7e5b5946ee23100b4437d54ec08db8e89f6e459d497b579a03"
    id2PrivateKey = "499f40c1bf13e7716e62431b17ab668fa2688b7c94a011a3aab595477bc68347"

    # Create identities from the private keys
    id1 = Entity.from_hex(id1PrivateKey)
    id2 = Entity.from_hex(id2PrivateKey)

    # Load 1000 tokens to id1
    api.sync(api.tokens.wealth(id1, 1000))

    # signed transaction that transfers 250 FET from id1 to id2. Signed with (r,s)
    orig_tx = 'a1440000c5ab20e3ab845cb4a1d2c3e4c3b08f5ff42a6ff2a71d7697ba8f32c415b77c7f8d850b3ef025b189a2d9bb4a515a84c3673db6d3ef25385d2c8d1e34b06e2de1c0fac08501140000000000000000040bafbc61a08524372f495d9dee08adbc39824e980506947091395cece16636ddc094b9d409d5b34ef0bbd9c99c5caf21fc373802472cf96a8a280f84e833f992402192a0a125d551b60800d441cb3483cd36573c22a73f22563d6dd7b27e677b98ba4e2f77596888839a3c6f2439c97949ea28923f168d360a6d155c2be79570af'
    # signed Malicious transaction of the previous transaction. Signed with (r,n-s)
    mal_tx = 'a1440000c5ab20e3ab845cb4a1d2c3e4c3b08f5ff42a6ff2a71d7697ba8f32c415b77c7f8d850b3ef025b189a2d9bb4a515a84c3673db6d3ef25385d2c8d1e34b06e2de1c0fac08501140000000000000000040bafbc61a08524372f495d9dee08adbc39824e980506947091395cece16636ddc094b9d409d5b34ef0bbd9c99c5caf21fc373802472cf96a8a280f84e833f99240f1a0311cc9b42edaa41d537e3d1f9d54ac159504276c27be2973cea85c8e8a17148a2b1dc3e188f911c6b05f163d95b964ae594a347870973e59b3c93d35b895'

    # Creating jsons for the above mentioned transactions
    legit_trans = submit_json_transaction(
        host=HOST,
        port=PORT,
        tx_data=dict(ver="1.2",
                     data=base64.b64encode(
                         binascii.unhexlify(orig_tx)).decode()),
        endpoint=ENDPOINT)
    mal_trans = submit_json_transaction(
        host=HOST,
        port=PORT,
        tx_data=dict(ver="1.2",
                     data=base64.b64encode(
                         binascii.unhexlify(mal_tx)).decode()),
        endpoint=ENDPOINT)

    # Sending the transactions to the ledger
    assert legit_trans == mal_trans, "Malleable transactions have different transaction hash"
    api.sync([legit_trans, mal_trans])

    # If transaction malleability is feasible, id2 should have 500 FET.
    # If balance of id2 is more than 250 raise an exception
    assert api.tokens.balance(
        id2) == 250, "Vulnerable to transaction malleability attack"
Exemple #28
0
def run(options, benefactor):
    ENDPOINT = 'fetch/token/transfer'
    HOST = options['host']
    PORT = options['port']

    # create the APIs
    api = LedgerApi(HOST, PORT)

    # Hardcoded private keys
    id1PrivateKey = "d222867ac019aa7e5b5946ee23100b4437d54ec08db8e89f6e459d497b579a03"
    id2PrivateKey = "499f40c1bf13e7716e62431b17ab668fa2688b7c94a011a3aab595477bc68347"

    # Create identities from the private keys
    id1 = Entity.from_hex(id1PrivateKey)
    id2 = Entity.from_hex(id2PrivateKey)

    # Load 100000 tokens to id1
    api.sync(api.tokens.transfer(benefactor, id1, 100000, 1000))

    # signed transaction that transfers 2500 FET from id1 to id2. Signed with (r,s) Fees are 1000
    orig_tx = 'a1640000c5ab20e3ab845cb4a1d2c3e4c3b08f5ff42a6ff2a71d7697ba8f32c415b77c7f8d850b3ef025b189a2d9bb4a515a84c3673db6d3ef25385d2c8d1e34b06e2de1c109c46501c103e8565596cd793442c5040bafbc61a08524372f495d9dee08adbc39824e980506947091395cece16636ddc094b9d409d5b34ef0bbd9c99c5caf21fc373802472cf96a8a280f84e833f99240f1c72a58927153d6fdc19f178f69c5b02db29f33541e2b946c78a54ce693c7c81082f22531b85a1707cf290f73fddd2df88681084b0cc7aff38e977215ae5899'
    # signed Malicious transaction of the previous transaction. Signed with (r,n-s)
    mal_tx = 'a1640000c5ab20e3ab845cb4a1d2c3e4c3b08f5ff42a6ff2a71d7697ba8f32c415b77c7f8d850b3ef025b189a2d9bb4a515a84c3673db6d3ef25385d2c8d1e34b06e2de1c109c46501c103e8565596cd793442c5040bafbc61a08524372f495d9dee08adbc39824e980506947091395cece16636ddc094b9d409d5b34ef0bbd9c99c5caf21fc373802472cf96a8a280f84e833f99240cb13a3a05600cd45c7abe860515801941d6eef439e697ab31015543b515e5b85495f2a3f95a352747eda205cc70e0bca7a4d8b1240dfbd43f3a047a1faad30bd'

    # Creating jsons for the above mentioned transactions
    legit_trans = submit_json_transaction(
        host=HOST,
        port=PORT,
        tx_data=dict(ver="1.2",
                     data=base64.b64encode(
                         binascii.unhexlify(orig_tx)).decode()),
        endpoint=ENDPOINT)
    mal_trans = submit_json_transaction(
        host=HOST,
        port=PORT,
        tx_data=dict(ver="1.2",
                     data=base64.b64encode(
                         binascii.unhexlify(mal_tx)).decode()),
        endpoint=ENDPOINT)

    # Sending the transactions to the ledger
    assert legit_trans == mal_trans, "Malleable transactions have different transaction hash"
    api.sync([legit_trans, mal_trans])

    # If transaction malleability is feasible, id2 should have 500 FET.
    # If balance of id2 is more than 250 raise an exception
    assert api.tokens.balance(
        id2) == 2500, "Vulnerable to transaction malleability attack"
Exemple #29
0
def main():
    # create the APIs
    api = LedgerApi(HOST, PORT)

    # generate identities from hex private keys,
    identity1 = Entity.from_hex('6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b')
    identity2 = Entity.from_hex('e833c747ee0aeae29e6823e7c825d3001638bc30ffe50363f8adf2693c3286f8')

    print('Balance 1 Before:', api.tokens.balance(identity1))
    print('Balance 2 Before:', api.tokens.balance(identity2))

    # submit and wait for the transfer to be complete
    print('Submitting transfer...')
    api.sync(api.tokens.transfer(identity1, identity2, 250, 20))

    print('Balance 1:', api.tokens.balance(identity1))
    print('Balance 2:', api.tokens.balance(identity2))
Exemple #30
0
def run(options, benefactor):
    entity1 = Entity()

    # build the ledger API
    api = LedgerApi(options['host'], options['port'])

    # create funds so that we have the funds to be able to create contracts on the network
    api.sync(api.tokens.transfer(benefactor, entity1, 100000, 1000))

    contract = Contract(CONTRACT_TEXT, entity1)

    # deploy the contract to the network
    status = api.sync(api.contracts.create(entity1, contract, 2000))[0]

    api.sync(api.tokens.transfer(entity1, contract.address, 10000, 500))

    block_number = status.exit_code
    v = contract.query(api, 'get_init_block_number_state')
    assert block_number > 0
    assert block_number == v, \
        'Returned block number by the contract ({}) is not what expected ({})'.format(
            v, block_number)

    api.sync(contract.action(api, 'set_block_number_state', 400, entity1))

    assert block_number <= contract.query(api, 'query_block_number_state')