Exemplo n.º 1
0
    def setUp(self):

        # Set blockcahin provider
        self.w3 = Web3(HTTPProvider('http://10.10.10.61:7545'))

        self.contract_dir = os.path.abspath('./contracts/')

        self.greeter_interface = ContractInterface(self.w3, 'Greeter',
                                                   self.contract_dir)
Exemplo n.º 2
0
    def _on_packet_action(self, packet):
        """ Function that we'll execute to examine the packets we're receiving 
        The proxy will only receive packets from legacy devices, so he can keep his own database 
        of devices """

        # Get the mac address
        mac_address = packet[Ether].src
        # Añadir comprobación de si está en la red

        # If the mac address is not in macs but the ip is in our network
        # that means that the sender is one of the legacy devices
        if packet[IP].src in self.network and mac_address not in self.macs:
            packet.summary()
            # Add it to our mac address set
            self.macs.add(mac_address)
            print('Added', mac_address, 'to the list of addresses')

            # Create a new account using mac as password
            account_num = self.w3.personal.newAccount(mac_address)
            ip_addr = packet[IP].src
            print('Cuenta del cliente', account_num)

            # Unlock account forever
            self.w3.personal.unlockAccount(account_num, mac_address, 0)
            print('Account unlocked')

            # Create a new client
            # Since the client won't even know that we're in an
            # ethereum environment, we have to set the proxy's w3 as the client's
            # so we can do transactions quickly
            new_client = Client(account=account_num,
                                w3=self.w3,
                                ip_address=ip_addr,
                                mac_address=mac_address)
            # Register the client
            print('Registering client with address:', account_num)
            print('Proxy address', self.account)
            print('Default Account:', new_client.w3.eth.defaultAccount)

            # Register the new client
            new_client.register()
            print('Registered new client')

            # Set the dictionary so we relate mac_addresses to the clients' interface
            self.clients[mac_address] = new_client
            print('New dictionary:', self.clients)

            # Add it to the database
            with self.conn as conn:
                command = """
                INSERT INTO devices(account, mac_address, ip_address) values ('{}','{}','{}')
                """.format(account_num, mac_address, ip_addr)
                conn.execute(command)
Exemplo n.º 3
0
def free_cpu(client: ContractInterface):
    print("Seleccione la entrada que desea liberar ")
    # Enumerate posibilities
    posibilities = list(enumerate(client.remoteCPU.items()))
    for posib in posibilities:
        entry, (id, value) = posib
        print("{}) {} -> {}%".format(entry, id, value))

    # for i, (k,v) in enumerate(client.remoteStorage.items()):
    #  print("{}) {} -> {} MB".format(i, k, v))

    choice = int(input(':'))

    # Get the values
    entry, (id, amount) = posibilities[choice]
    print('Selected entry: {} -> {} {} MB'.format(entry, id, amount))
    client.free_computing_power(id)
Exemplo n.º 4
0
def main():

    print('Instantiating ContractInterface')
    client = ContractInterface()

    print('Registering...')
    client.register()
    '''
    print("Transfering 50 IoT's")
    client.transfer(client.w3.eth.accounts[2], 50)'''

    # Request 5 GB. This one should be accepted
    print('Request 5 GB (even)')
    client.request_storage(5000)

    input('Press enter for freeing')
    id, _ = client.remoteStorage.popitem()
    client.free_storage(id)
import os
from interface import ContractInterface

class TEMP(object):
    def __init__(self):
        max_deploy_gas = 0


# Initialize web3 object
web3 = Web3(HTTPProvider('http://localhost:8545')) #Ganache default host + port

# Path for Solidity source files
contract_dir = os.path.abspath('./contracts')

# Initialize interface
interface = ContractInterface(web3, 'TEST', contract_dir)

# Compile contracts & deploy
interface.compile_source_files()
interface.deploy_contract()

# Estimate gas usage. Can be used to deploy if it's below X value
# TODO What class is this in?
deployment_estimate = deployment.constructor().estimateGas(transaction = deployment_params)
if deployment_estimate < self.max_deploy_gas:
    tx_hash = deployment.constructor().transact(transaction = deployment_params)


tx_receipt = self.web3.eth.waitForTransactionReceipt(tx_hash)
contract_address = tx_receipt['contractAddress']
Exemplo n.º 6
0
class TestInterface(unittest.TestCase):
    def setUp(self):

        # Set blockcahin provider
        self.w3 = Web3(HTTPProvider('http://10.10.10.61:7545'))

        self.contract_dir = os.path.abspath('./contracts/')

        self.greeter_interface = ContractInterface(self.w3, 'Greeter',
                                                   self.contract_dir)

    def test_1_init(self):

        self.assertEqual(self.greeter_interface.web3.eth.defaultAccount,
                         self.w3.eth.accounts[0],
                         'Default account not set correctly')

    def test_2_compile(self):

        self.greeter_interface.compile_source_files()

        self.assertEqual(len(self.greeter_interface.all_compiled_contracts), 3)

    def test_3_deploy(self):

        self.greeter_interface.deploy_contract()

        self.assertTrue(
            os.path.isfile(self.greeter_interface.deployment_vars_path))

    def test_4_get_instance(self):

        self.greeter_interface.get_instance()

        self.assertEqual(self.greeter_interface.contract_instance.address,
                         self.greeter_interface.contract_address)

    def test_5_change_greeting(self):

        event = 'GreetingChange'
        new_greeting = 'Hola'.encode('utf-8')

        expected_logs = {
            'changer': self.w3.eth.accounts[0],
            '_from': 'Hello',
            '_to': new_greeting,
            'event': event
        }

        self.greeter_interface.get_instance()
        receipt, indexed_events = self.greeter_interface.send('setGreeting',
                                                              new_greeting,
                                                              event=event)

        self.assertTrue(receipt['blockNumber'] > 0)

        self.assertEqual(
            indexed_events['changer'], expected_logs['changer'],
            "Logging output for {} inconsistent".format('changer'))
        self.assertEqual(indexed_events['_from'], expected_logs['_from'],
                         "Logging output for {} inconsistent".format('_from'))
        self.assertEqual(
            indexed_events['changer'], expected_logs['changer'],
            "Logging output for {} inconsistent".format('changer'))

    def test_6_call_greeting(self):

        expected_greeting = 'Hola'
        # Although the test suite starts with a clean state, the test above
        # changes the contract's greeting on the blockchain, which is what
        # is fetched.

        self.greeter_interface.get_instance()
        actual_greeting = self.greeter_interface.retrieve('greeting')

        self.assertEqual(expected_greeting, actual_greeting,
                         'Unexpected greeting returned')
Exemplo n.º 7
0
# Put your imports here
import os
import serial
from web3 import Web3, HTTPProvider
from interface import ContractInterface

# Initialize your web3 object
w3 = Web3(HTTPProvider('http://127.0.0.1:8545'))
ser = serial.Serial('/dev/ttyUSB1', 115200)
ser.flushInput()

print("from:", w3.eth.accounts[0])
# Create a path object to your Solidity source files
contract_dir = os.path.abspath('./contracts/')
greeter_interface = ContractInterface(w3, 'Greeter', contract_dir)

# Initialize your interface
greeter_interface.compile_source_files()
greeter_interface.deploy_contract()
instance = greeter_interface.get_instance()


def strToHex32(zBytes):

    len1 = len(zBytes)
    if len1 > 32:
        zBytes32 = zBytes[:32]
    else:
        zBytes32 = zBytes.ljust(32, '0')
    return bytes(zBytes32, 'utf-8')
def load_contracts():
    contract_dir = PATH + "/deployment_vars"
    deploy_dir = PATH + "/deployment_vars"

    # setup fake stablecoin
    path = PATH + "/contracts/TestContracts.sol:FakeUSD"
    StableCoin = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    StableCoin.deploy_contract(path)

    # setup price feed
    path = PATH + "/contracts/TestContracts.sol:FakePriceProvider"
    PriceProvider = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    PriceProvider.deploy_contract(path, [20000000000])

    # setup exchange
    path = PATH + "/contracts/TestContracts.sol:FakeExchange"
    Exchange = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    Exchange.deploy_contract(
        path,
        [PriceProvider.vars["contract_address"], StableCoin.vars["contract_address"]],
    )

    # setup CallOptions
    path = PATH + "/contracts/HegicCallOptions.sol:HegicCallOptions"
    HegicCallOptions = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    HegicCallOptions.deploy_contract(path, [PriceProvider.vars["contract_address"]])

    # setup PutOptions
    path = PATH + "/contracts/HegicPutOptions.sol:HegicPutOptions"
    HegicPutOptions = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    HegicPutOptions.deploy_contract(
        path,
        [
            StableCoin.vars["contract_address"],
            PriceProvider.vars["contract_address"],
            Exchange.vars["contract_address"],
        ],
    )

    # setupERCPool
    path = PATH + "/contracts/HegicERCPool.sol:HegicERCPool"
    HegicERCPool = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    HegicERCPool.deploy_contract(path, [StableCoin.vars["contract_address"]])

    # setupETHPool
    path = PATH + "/contracts/HegicETHPool.sol:HegicETHPool"
    HegicETHPool = ContractInterface(
        w3, path, contract_dir, deployment_vars_path=deploy_dir
    )
    HegicETHPool.deploy_contract(path, [StableCoin.vars["contract_address"]])

    print("All Deployed!")
    return {
        "StableCoin": StableCoin,
        "PriceFeed": PriceProvider,
        "Exchange": Exchange,
        "HegicCallOptions": HegicCallOptions,
        "HegicPutOptions": HegicPutOptions,
        "HegicERCPool": HegicERCPool,
        "HegicETHPool": HegicETHPool,
    }
# -*- coding: utf-8 -*-
"""
Created on Sun Mar  1 17:06:31 2020

@author: peter
"""

import os
from web3 import Web3, HTTPProvider
from interface import ContractInterface

w3 = Web3(HTTPProvider("http://127.0.0.1:8545"))

contractDir = os.path.abspath("./contracts/")

soapBoxInterface = ContractInterface(w3, "SoapBox", contractDir)

soapBoxInterface.compile_source_files()

soapBoxInterface.deploy_contract()

instance = soapBoxInterface.get_instance()
print("before we pay:",
      instance.functions.isApproved(w3.eth.accounts[0]).call())
instance.functions.pay().transact({'value': w3.toWei(0.03, 'ether')})
print("after we pay:",
      instance.functions.isApproved(w3.eth.accounts[0]).call())
instance.functions.broadcastOpinion(
    'You can never be overdressed or overeducated.').transact()
print(instance.functions.getCurrentOpinion().call())
Exemplo n.º 10
0
def menu():

    client_registered = False
    """ Show interactive menu for more convenient testing """
    # Create the client interface
    client_number = int(argv[1])

    client = ContractInterface(client_number=client_number)
    #if client_number > 1:
    #    # Tenemos que inventarnos la IP y la MAC
    #    client.IP = ips[client_number - 2]
    #    client.MAC = macs[client_number -2]

    print('Initialized contract interface for client')

    menu = """
    SELECCIONE UNA ACCION QUE EL CLIENTE DEBE REALIZAR:

    1) Registrarse  
    2) Realizar transferencia
    3) Peticion de almacenamiento
    4) Liberar almacenamiento
    5) Peticion de CPU
    6) Liberar CPU
    7) Listar reservas
    8) Force error
    9) Get balances

    """
    # Show the menu
    while True:
        choice = int(input(menu))
        # Registrar al usuario
        if choice == 1:
            if not client_registered:
                register_client(client)
                client_registered = True
            else:
                print('El cliente ya está registrado')
        # Realizar transferencia
        elif choice == 2:
            amount = int(input('Seleccione la cantidad a transferir: '))
            transfer_amount(client, amount)
        # Peticion de almacenamiento
        elif choice == 3:
            amount = int(input('Seleccione la cantidad a pedir: '))
            request_storage(client, amount)
        # Liberar almacenamiento
        elif choice == 4:
            free_storage(client)
        # Pedir cpu
        elif choice == 5:
            amount = int(input('Seleccione la cantidad a pedir: '))
            request_cpu(client, amount)
        # Liberar cpu
        elif choice == 6:
            free_cpu(client)
        # Listar reservas
        elif choice == 7:
            list_reservations(client)
        elif choice == 8:
            force_error(client)
        elif choice == 9:
            get_balances(client)
        else:
            print('Opción invalida')

        print()
Exemplo n.º 11
0
def force_error(client: ContractInterface):
    client.force_error()
Exemplo n.º 12
0
def register_client(client: ContractInterface):
    client.register()
Exemplo n.º 13
0
def request_cpu(client: ContractInterface, amount: int):
    client.request_computing_power(amount)
Exemplo n.º 14
0
def request_storage(client: ContractInterface, amount: int):
    client.request_storage(amount)
Exemplo n.º 15
0
def transfer_amount(client: ContractInterface, amount: int):
    client.transfer(to=client.w3.eth.accounts[2], amount=amount)