Ejemplo n.º 1
0
def credits():
    reward = BLOCK_REWARD - FEE
    accounts = {}
    totshare = 0
    worker = {}
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for row in db.execute('SELECT miner, worker FROM share GROUP BY miner'):
        worker[row[0]] = row[1]
    for acc in accounts:
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    return render_template('credits.html',
                           cround=cround,
                           worker=worker,
                           accounts=accounts,
                           posts=posts,
                           totshare=totshare,
                           server=SERVER_POOL)
def main():
    #
    # create rpc interface
    #
    try:
        rpc = EthJsonRpc(RPC_HOST, RPC_PORT)
    except:
        print('unable to connect to rpc server at {}:{}'.format(
            RPC_HOST, RPC_PORT))
        sys.exit(-1)

    method = sys.argv[1]

    if method == "newContract":
        owner = sys.argv[2]
        partner = sys.argv[3]
        text = sys.argv[4]

        tx = rpc.call_with_transaction(owner,
                                       CONTRACT_STORAGE_ADDRESS,
                                       'createNewContract(string,string)',
                                       [partner, text],
                                       gas=GAS)
        print(format(tx))

    elif method == "contractData":
        trans_addr = sys.argv[2]
        trans = rpc.eth_getTransactionByHash(trans_addr)
        res = Decoder.decodeABI(trans['input'],
                                'createNewContract(string,string)',
                                ['string', 'string'])
        print(res)

    elif method == "newUser":
        address = sys.argv[2]
        dataString = sys.argv[3]

        tx = rpc.call_with_transaction(address,
                                       USER_STORAGE_ADDRESS,
                                       'setUserIdentityDocs(string)',
                                       [dataString],
                                       gas=GAS)

    elif method == "identification":
        account_addr = sys.argv[2]
        transactionHashes, identityDocuments = rpc.call(
            USER_STORAGE_ADDRESS, 'getUser(address)', [account_addr],
            ['string', 'string'])
        print(identityDocuments)

    elif method == "accounts":
        account_id = sys.argv[2]
        print(rpc.eth_accounts()[int(account_id)])

    else:
        print("method not recognized!")
Ejemplo n.º 3
0
def miner():
    # ЧТО НЕ СДЕЛАНО!
    # Необходимо вывести количество workers, общий хэшрейт майнера
    # Необходимо сформировать таблицу название workers,, хэшрейт workers, усреднённый хэшрейт workers, шары workers
    address = request.form['address'].replace('0x', '')
    payouts = []
    paylock.acquire()
    reward = BLOCK_REWARD - FEE
    accounts = {}
    totshare = 0
    worker = {}
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for row in db.execute('SELECT miner, worker FROM share GROUP BY miner'):
        worker[row[0]] = row[1]

    for acc in accounts:
        workers = worker[acc]
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    conn2 = sqlite3.connect(DBPAYOUT_FILE)
    db2 = conn2.cursor()

    for row in db2.execute('SELECT * FROM payout WHERE miner=?', [address]):
        payouts.append(row)

    conn2.commit()
    conn2.close()
    paylock.release()

    if address in cround['accounts']:
        rshare = cround['accounts'][address]
    else:
        rshare = 0
    print rshare, cround
    return render_template('miner.html',
                           address=address,
                           workers=workers,
                           payouts=payouts,
                           shares=rshare)
Ejemplo n.º 4
0
def index():
    # price курс BTC_ETH
    ticker = polo.api('returnTicker')
    allprice = (ticker['BTC_ETH'])
    price1 = allprice['last']
    price = price1[0:6]
    # priceUSD курс USDT_ETH
    ticker2 = polo.api('returnTicker')
    allprice2 = (ticker2['USDT_ETH'])
    price2 = allprice2['last']
    priceUSD = price2[0:5]
    accounts = {}
    totshare = 0
    reward = BLOCK_REWARD - FEE
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for acc in accounts:
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    # запрос хэшрейтинга пула и количества блоков сети
    c = EthJsonRpc('localhost', 8545)
    Hashrate = c.eth_hashrate()
    Blocks = c.eth_blockNumber()
    return render_template('index.html',
                           price=price,
                           priceUSD=priceUSD,
                           Blocks=Blocks,
                           accounts=accounts,
                           Hashrate=Hashrate,
                           totshare=totshare,
                           cround=cround,
                           server=SERVER_POOL)
Ejemplo n.º 5
0
def index():
	# price курс BTC_ETH

	# priceUSD курс USDT_ETH

	accounts = {}
	totshare = 0
	reward = BLOCK_REWARD - FEE
	c = EthJsonRpc('172.16.0.7', 8545)
	posts = c.eth_accounts()
	conn = sqlite3.connect(DBSHARE_FILE)
	db = conn.cursor()
	for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
	 	accounts [row [0]] = row [1]
		totshare += row [1]
	for acc in accounts:
		racc = accounts[acc] * reward / float (totshare)
	conn.commit ()
	conn.close ()
	# запрос хэшрейтинга пула и количества блоков сети
	c = EthJsonRpc('172.16.0.7', 8545)
	Hashrate = c.eth_hashrate()
	Blocks = c.eth_blockNumber()
	return render_template('index.html', Blocks=Blocks, accounts=accounts, Hashrate=Hashrate, totshare=totshare, cround=cround, server=SERVER_POOL)
Ejemplo n.º 6
0
#! /bin/env python

#pip install ethjsonrpc

from ethjsonrpc import EthJsonRpc

c = EthJsonRpc('127.0.0.1', 8545)
print c.web3_clientVersion()

accounts = c.eth_accounts()
print c.eth_getBalance(address=accounts[0])
Ejemplo n.º 7
0
class EthDeploy:
    def __init__(self, protocol, host, port, gas, gas_price, contract_dir,
                 optimize, account, private_key_path):
        # establish rpc connection
        self.json_rpc = EthJsonRpc(protocol=protocol, host=host, port=port)
        self._from = None
        self.private_key = None
        # set sending account
        if account:
            self._from = self.add_0x(account)
        elif private_key_path:
            with open(private_key_path, 'r') as private_key_file:
                self.private_key = private_key_file.read().strip()
            self._from = self.add_0x(
                encode(privtoaddr(decode(self.private_key, 'hex')), 'hex'))
        else:
            accounts = self.json_rpc.eth_accounts()['result']
            if len(accounts) == 0:
                raise ValueError('No account unlocked')
            self._from = self.add_0x(accounts[0])
        # account address in right format
        if not self.is_address(self._from):
            raise ValueError('Account address is wrong')
        self.optimize = optimize
        self.contract_dir = contract_dir
        self.gas = gas
        self.gas_price = gas_price
        # references dict maps labels to addresses
        self.references = {}
        # abis dict maps addresses to abis
        self.abis = {}
        # total consumed gas
        self.total_gas = 0
        self.log('Instructions are sent from address: {}'.format(self._from))
        balance = self.hex2int(
            self.json_rpc.eth_getBalance(self._from)['result'])
        self.log('Address balance: {} Ether / {} Wei'.format(
            balance / 10.0**18, balance))

    def is_address(self, string):
        return len(self.add_0x(string)) == 42

    @staticmethod
    def hex2int(_hex):
        return int(_hex, 16)

    @staticmethod
    def add_0x(string):
        if not string.startswith('0x'):
            return '0x' + string
        return string

    @staticmethod
    def strip_0x(string):
        if string.startswith('0x'):
            return string[2:]
        return string

    @staticmethod
    def log(string):
        logger.info(string)

    def format_reference(self, string):
        return self.add_0x(string) if self.is_address(string) else string

    def log_transaction_receipt(self, transaction_receipt):
        gas_used = self.hex2int(transaction_receipt['gasUsed'])
        self.total_gas += gas_used
        self.log(
            'Transaction receipt: {} block number, {} gas used, {} cumulative gas used'
            .format(self.hex2int(transaction_receipt['blockNumber']), gas_used,
                    self.hex2int(transaction_receipt['cumulativeGasUsed'])))

    def get_transaction_receipt(self, transaction_hash):
        return self.json_rpc.eth_getTransactionReceipt(
            transaction_hash)['result']

    def wait_for_transaction_receipt(self, transaction_hash):
        while self.get_transaction_receipt(transaction_hash) is None:
            self.log(
                'Waiting for transaction receipt {}'.format(transaction_hash))
            time.sleep(5)
        return self.get_transaction_receipt(transaction_hash)

    def replace_references(self, a):
        if isinstance(a, list):
            return [self.replace_references(i) for i in a]
        else:
            return self.references[a] if isinstance(
                a, basestring) and a in self.references else a

    def get_nonce(self):
        transaction_count = self.json_rpc.eth_getTransactionCount(
            self._from, default_block='pending')['result']
        return self.hex2int(self.strip_0x(transaction_count))

    def get_raw_transaction(self, to='', value=0, data=''):
        nonce = self.get_nonce()
        tx = Transaction(nonce, self.gas_price, self.gas, to, value,
                         decode(data, 'hex'))
        tx.sign(decode(self.private_key, 'hex'))
        return self.add_0x(encode(rlp.encode(tx), 'hex'))

    def compile_code(self, path):
        # create list of valid paths
        absolute_path = self.contract_dir if self.contract_dir.startswith(
            '/') else '{}/{}'.format(os.getcwd(), self.contract_dir)
        sub_dirs = [x[0] for x in os.walk(absolute_path)]
        extra_args = ' '.join(
            ['{}={}'.format(d.split('/')[-1], d) for d in sub_dirs])
        # compile code
        combined = _solidity.compile_last_contract(path,
                                                   libraries=self.references,
                                                   combined='bin,abi',
                                                   optimize=self.optimize,
                                                   extra_args=extra_args)
        bytecode = combined['bin_hex']
        abi = combined['abi']
        return bytecode, abi

    def deploy(self, _from, file_path, libraries, value, params, label):
        # replace library placeholders
        if libraries:
            for library_name, library_address in libraries.items():
                self.references[library_name] = self.replace_references(
                    self.strip_0x(library_address))
        if self.contract_dir:
            file_path = '{}/{}'.format(self.contract_dir, file_path)
        bytecode, abi = self.compile_code(file_path)
        if not label:
            label = file_path.split("/")[-1].split(".")[0]
        if params:
            translator = ContractTranslator(abi)
            # replace constructor placeholders
            params = [self.replace_references(p) for p in params]
            bytecode += encode(translator.encode_constructor_arguments(params),
                               'hex')
        # deploy contract
        self.log('Deployment transaction for {} sent'.format(
            label if label else 'unknown'))
        tx_response = None
        if self.private_key:
            raw_tx = self.get_raw_transaction(value=value, data=bytecode)
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Deploy failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx)
        else:
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Deploy failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.add_0x(_from if _from else self._from),
                    value=value,
                    data=self.add_0x(bytecode),
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_receipt = self.wait_for_transaction_receipt(
            self.add_0x(tx_response['result']))
        contract_address = self.strip_0x(
            transaction_receipt['contractAddress'])
        self.references[label] = contract_address
        self.abis[contract_address] = abi
        self.log('Contract {} created at address {}'.format(
            label if label else 'unknown', self.add_0x(contract_address)))
        self.log_transaction_receipt(transaction_receipt)

    def send_transaction(self, _from, to, value, name, params, abi):
        reference = to
        to = self.replace_references(to)
        data = ''
        if name or abi:
            if not name:
                name = abi['name']
            abi = self.abis[to] if to in self.abis else [abi]
            translator = ContractTranslator(abi)
            data = encode(
                translator.encode(name, self.replace_references(params)),
                "hex")
        self.log('Transaction to {}{} sent'.format(
            self.format_reference(reference),
            ' calling {} function'.format(name) if name else ''))
        tx_response = None
        if self.private_key:
            raw_tx = self.get_raw_transaction(to=to, value=value, data=data)
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Transaction failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx)
        else:
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Transaction failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.add_0x(_from if _from else self._from),
                    to_address=self.add_0x(to),
                    value=value,
                    data=self.add_0x(data),
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_hash = tx_response['result']
        transaction_receipt = self.wait_for_transaction_receipt(
            self.add_0x(transaction_hash))
        self.log('Transaction to {}{} successful'.format(
            self.format_reference(reference),
            ' calling {} function'.format(name) if name else ''))
        self.log_transaction_receipt(transaction_receipt)

    def call(self, _from, to, value, name, params, label, assertion, abi):
        reference = to
        to = self.replace_references(to)
        if not name:
            name = abi['name']
        abi = self.abis[to] if to in self.abis else [abi]
        translator = ContractTranslator(abi)
        data = encode(translator.encode(name, self.replace_references(params)),
                      'hex')
        response = self.json_rpc.eth_call(
            self.add_0x(to),
            from_address=self.add_0x(_from if _from else self._from),
            value=value,
            data=self.add_0x(data),
            gas=self.gas,
            gas_price=self.gas_price)
        result = translator.decode(
            name, decode(self.strip_0x(response['result']), 'hex'))
        result = result if len(result) > 1 else result[0]
        if label:
            self.references[label] = result
        if assertion:
            expected_result = self.replace_references(assertion)
            if isinstance(expected_result, int) or isinstance(
                    expected_result, long):
                assert result == expected_result
            else:
                assert result.lower() == self.strip_0x(expected_result.lower())
            self.log('Assertion of {} at {} successful'.format(
                name, self.format_reference(reference)))
        else:
            self.log('Call to {} calling function {} successful'.format(
                self.format_reference(reference), name))

    def process(self, f):
        # read instructions file
        with open(f, 'r') as instructions_file:
            instructions = json.load(instructions_file)
        for i in instructions:
            if i['type'] == 'abi':
                for address in i['addresses']:
                    self.abis[self.strip_0x(address)] = i['abi']
            if i['type'] == 'deployment':
                self.deploy(i['from'] if 'from' in i else None,
                            i['file'] if 'file' in i else None,
                            i['libraries'] if 'libraries' in i else None,
                            i['value'] if 'value' in i else 0,
                            i['params'] if 'params' in i else (),
                            i['label'] if 'label' in i else None)
            elif i["type"] == "transaction":
                self.send_transaction(
                    i['from'] if 'from' in i else None,
                    i['to'] if 'to' in i else None,
                    i['value'] if 'value' in i else 0,
                    i['name'] if 'name' in i else None,
                    i['params'] if 'params' in i else (),
                    i['abi'] if 'abi' in i else None,
                )
            elif i["type"] == "call":
                self.call(
                    i['from'] if 'from' in i else None,
                    i['to'] if 'to' in i else None,
                    i['value'] if 'value' in i else 0,
                    i['name'] if 'name' in i else None,
                    i['params'] if 'params' in i else (),
                    i['label'] if 'label' in i else None,
                    i['assertion'] if 'assertion' in i else None,
                    i['abi'] if 'abi' in i else None,
                )
        self.log('-' * 96)
        self.log('Summary: {} gas used, {} Ether / {} Wei spent on gas'.format(
            self.total_gas, self.total_gas * self.gas_price / 10.0**18,
            self.total_gas * self.gas_price))
        for reference, value in self.references.items():
            self.log('{} references {}'.format(
                reference,
                self.add_0x(value) if isinstance(value, unicode) else value))
        self.log('-' * 96)
Ejemplo n.º 8
0
            setCursor(xPos, getCursor()[1])
            if xPos > pwdLen - 1:
                passAsk = False
                lcdClear()
                pwd = ""  #Password buffer

                #Notify user about the ongoing process
                setCursor(0, 0)
                lcdPrint("Please wait..")
                setCursor(0, 1)
                lcdPrint("Authenticating")

                for i in range(0, pwdLen):  #Build String
                    pwd += pwInput[i]
                try:  #Try to unlock account
                    print c.personal_unlockAccount(c.eth_accounts()[1], pwd,
                                                   10)

                    #Reset password variables, for security reasons
                    lcdClear()
                    pwd = 0
                    pwInput = [""] * pwdLen
                    setCursor(0, 0)
                    lcdPrint("Authenticated!")
                    auth = True  #Authentication succesful
                except:
                    #Possibly incorrect password
                    lcdClear()
                    setCursor(0, 0)
                    lcdPrint("Nope...")
                if auth:
Ejemplo n.º 9
0
def runWorker(ID, s, output):

    client = EthJsonRpc('10.64.83.200', 39000 + ID)
    obj = web3.Web3(web3.HTTPProvider('http://10.64.83.200:3900' + str(ID)))
    print(client.eth_accounts()[0])
    #print(client1.eth_accounts()[1])

    print("Worker %d initialized successfully!" % (ID, ))

    all_gas = []
    nu = 0  #iteration count
    itermax = s.admmopt.iterMaxlocal  #get maximum iteration
    flag = False
    new_gas = 0

    start_balance = obj.eth.getBalance(
        obj.toChecksumAddress(client.eth_accounts()[0]))

    j = 0
    s.admmopt.tau = 1
    last_block = obj.eth.blockNumber
    while (1):
        trans_by_block = obj.eth.getBlockTransactionCount(last_block - j)
        if (trans_by_block > 0):
            #dest = list(s.nbor.keys())
            #if(ID==1):getNextValues(ID,s,client,obj,last_block - j, trans_by_block)

            #s.update_z()
            #s.choose_max_rho()
            break

        j = j + 1

    prev_convegenceTable = []
    P_history = []
    Q_history = []
    start_time2 = time()

    while nu <= itermax and not flag:
        if s.recvmsg:
            s.update_z()
            s.choose_max_rho()

            #print(ID,"i have rho", s.var["rho"])

        start_time = time()
        result = s.pipslopf_solver()

        end_time = time()

        if result['eflag'] and nu % 20 == 0:
            print('Subproblem %d at iteration %d solved!' % (ID, nu))
            # print("Time for solving subproblem %d: %ssecs to %ssecs" % (ID, start_time, end_time))

        s.update_x()
        P_history.append(sum(s.var['Pg']))
        Q_history.append(sum(s.var['Qg']))

        if s.recvmsg:  # not the initialization
            s.update_y()
            s.update_rho()

            prev_convegenceTable = s.gapAll[s.ID - 1]

        # check convergence
        #if(nu>10):flag =
        flag = s.converge()
        s.recvmsg = {}  # clear the received messages

        #s.send()

        dest = s.nbor.keys()

        for k in dest:
            # prepare the message to be sent to neighbor k
            #tm.sleep(0.05)
            msg3 = message()
            msg3.config(s.ID, k, s.var, s.nbor[k].tlidx['int'], s.gapAll)
            data2 = json.dumps(msg3.__dict__, cls=MyEncoder)

            json_data = json.JSONEncoder().encode(data2)

            json_data = '0x' + json_data.encode("utf-8").hex()

            sampleDict = obj.txpool.content.pending

            new_gas = new_gas + 18000000000 * obj.eth.estimateGas({
                'to':
                obj.toChecksumAddress(
                    '0xa8085d8331f16a5b76690e665d9f5eaaaa85ee1c'),
                'data':
                json_data
            })

            client.eth_sendTransaction(
                from_address=client.eth_accounts()[0],
                to_address="0xa8085d8331f16a5b76690e665d9f5eaaaa85ee1c",
                gas=0xf4240,
                gas_price=18000000000,
                value=1,  # 2441406250
                data=json_data)

        txpooljson = obj.txpool.content.pending.__dict__

        recvmsg = {}

        twait = s.admmopt.pollWaitingtime
        dest = list(s.nbor.keys())
        recvFlag = [0] * s.region['nnbor']
        arrived = 0  # number of arrived neighbors
        pollround = 0
        while arrived < s.region['nwait'] and pollround < 5:
            #for i in range(len(dest)):
            #k = dest[i]
            #s.recvmsg[k] = recvmsg[k]
            #recvFlag[i] = 1

            for k in txpooljson.keys():

                txpooljson2 = txpooljson[k].__dict__
                last_nonce = max(txpooljson2, key=int)
                #print(ID,", last nonce",last_nonce)
                last_nonce_dict = txpooljson2[last_nonce].__dict__

                hexjson = last_nonce_dict['input'][2:]
                jsonstring = codecs.decode(hexjson, "hex").decode('utf-8')

                jsonvalues = json.JSONDecoder().decode(jsonstring)
                values_dict = json.loads(jsonvalues, cls=MyDecoder)

                temp_msg = message()
                if (values_dict['fID'] in s.nbor.keys()):
                    for last_nonce in range(int(max(txpooljson2, key=int)), 0,
                                            -1):
                        last_nonce_dict = txpooljson2[str(last_nonce)].__dict__

                        hexjson = last_nonce_dict['input'][2:]
                        jsonstring = codecs.decode(hexjson,
                                                   "hex").decode('utf-8')

                        jsonvalues = json.JSONDecoder().decode(jsonstring)
                        values_dict = json.loads(jsonvalues, cls=MyDecoder)
                        if (values_dict['tID'] == s.ID): break

                #print(ID,"last nonce=",last_nonce,"from",values_dict['fID'])
                temp_msg.fID = values_dict['fID']
                temp_msg.tID = values_dict['tID']
                temp_msg.fields['AVmd'] = numpy.asarray(
                    values_dict['fields']['AVmd'])
                temp_msg.fields['AVms'] = numpy.asarray(
                    values_dict['fields']['AVms'])
                temp_msg.fields['AVad'] = numpy.asarray(
                    values_dict['fields']['AVad'])
                temp_msg.fields['AVas'] = numpy.asarray(
                    values_dict['fields']['AVas'])
                temp_msg.fields['ymd'] = numpy.asarray(
                    values_dict['fields']['ymd'])
                temp_msg.fields['yms'] = numpy.asarray(
                    values_dict['fields']['yms'])
                temp_msg.fields['yad'] = numpy.asarray(
                    values_dict['fields']['yad'])
                temp_msg.fields['yas'] = numpy.asarray(
                    values_dict['fields']['yas'])
                temp_msg.fields['rho'] = values_dict['fields']['rho']
                temp_msg.fields['convergeTable'] = values_dict['fields'][
                    'convergeTable']

                if (temp_msg.tID == s.ID):
                    recvmsg[temp_msg.fID] = temp_msg
                    #recvFlag[i] = 1

                arrived = len(recvmsg)
                pollround += 1

        s.recvmsg = copy.deepcopy(recvmsg)

        all_gas.append(new_gas)
        nu += 1

    # record results
    print("Worker %d finished!" % (ID, ))

    for k in dest:

        starting_point = message2()
        starting_point.config(s.ID, k, s.var, s.nbor[k].tlidx['int'], s.gapAll)
        data2 = json.dumps(starting_point.__dict__, cls=MyEncoder)
        json_data = json.JSONEncoder().encode(data2)
        json_data = '0x' + json_data.encode("utf-8").hex()
        sampleDict = obj.txpool.content.pending

        client.eth_sendTransaction(
            from_address=client.eth_accounts()[0],
            to_address="0xa8085d8331f16a5b76690e665d9f5eaaaa85ee1c",
            gas=0xf4240,
            gas_price=18000000000,
            value=1,  # 2441406250
            data=json_data)

    print(starting_point.__dict__)

    x, f, info, lmbda, output2 = result["x"], result["f"], result[
        "eflag"], result["lmbda"], result["output"]
    nx = len(x)
    nb = s.region['nb']
    ng = s.region['ng']
    iv = s.idx['var']
    bus = s.region['bus']
    gen = s.region['gen']
    branch = s.region['branch']
    baseMVA = s.region['baseMVA']
    Ybus = s.region['Ybus']
    ridx = s.idx['rbus']['int']
    # idx ranges
    iVa = iv['iVa']
    iVm = iv['iVm']
    iPg = iv['iPg']
    iQg = iv['iQg']
    # grab Pg and Qg
    gen[:, PG] = x[iPg] * s.region["baseMVA"]
    gen[:, QG] = x[iQg] * s.region["baseMVA"]
    bus[:, PD] = bus[:, PD] * s.region["baseMVA"]
    bus[:, QD] = bus[:, QD] * s.region["baseMVA"]
    # reconstruct V
    Va, Vm = x[iVa], x[iVm]
    V = Vm * exp(1j * Va)

    #print(V)
    nl = shape(branch)[0]  ## number of branches
    bus[:, VA] = Va * 180 / pi
    bus[:, VM] = Vm

    if shape(branch)[1] < MU_ANGMAX + 1:
        branch = c_[branch, zeros((nl, MU_ANGMAX + 1 - shape(branch)[1]))]

    Ybus2, Yf, Yt = makeYbus(baseMVA, bus, branch)
    #print(Yf)
    ## compute branch flows
    Sf = V[branch[:, F_BUS].astype(int)] * conj(
        Yf * V)  ## cplx pwr at "from" bus, p["u"].
    St = V[branch[:, T_BUS].astype(int)] * conj(
        Yt * V)  ## cplx pwr at "to" bus, p["u"].

    branch[:, PF] = Sf.real * baseMVA
    branch[:, QF] = Sf.imag * baseMVA
    branch[:, PT] = St.real * baseMVA
    branch[:, QT] = St.imag * baseMVA

    #gen[:, VG] = Vm[ gen[:, GEN_BUS].astype(int) ]

    nlam = len(lmbda["eqnonlin"]) // 2
    lamP = zeros(nb)  #for non-included pf balances use 0 as multiplier
    lamQ = zeros(nb)
    lamP[s.idx['rbus']['int']] = lmbda["eqnonlin"][:nlam] / s.region["baseMVA"]
    lamQ[s.idx['rbus']['int']] = lmbda["eqnonlin"][nlam:nlam +
                                                   nlam] / s.region["baseMVA"]

    ong = find((gen[:, GEN_STATUS] > 0) & ~isload(gen))
    objValue1 = 0
    objValue2 = 0

    fd = stdout
    fd.write('\n REGION %d' % (s.ID))

    fd.write(
        '\nBus/Area  Voltage          Generation             Load        ')
    fd.write('  Lambda($/MVA-hr)')
    fd.write(
        '\n  #   Mag(pu) Ang(deg)   P (MW)   Q (MVAr)   P (MW)   Q (MVAr)')
    fd.write('     P        Q   ')
    fd.write(
        '\n----- ------- --------  --------  --------  --------  --------')
    fd.write('  -------  -------')
    for i in range(nb):
        for glob, loc in s.idx["mapping"].items():
            if loc == i:
                busid = glob + 1
                #bus[i,BUS_I]=glob+1
                pass
        fd.write('\n%5d/' % busid)
        fd.write('%d%7.3f%9.3f' % tuple(bus[i, [BUS_AREA, VM, VA]]))
        if bus[i, BUS_TYPE] == REF:
            fd.write('*')
        else:
            fd.write(' ')
        g = find((gen[:, GEN_STATUS] > 0) & (gen[:, GEN_BUS] == bus[i, BUS_I])
                 & ~isload(gen))
        ld = find((gen[:, GEN_STATUS] > 0) & (gen[:, GEN_BUS] == bus[i, BUS_I])
                  & isload(gen))
        if any(g + 1):
            fd.write('%9.2f%10.2f' % (sum(gen[g, PG]), sum(gen[g, QG])))
            objValue1 = objValue1 + (lamP[i]) * (sum(gen[g, PG]))
        else:
            fd.write('      -         -  ')
        if logical_or(bus[i, PD], bus[i, QD]) | any(ld + 1):
            if any(ld + 1):
                fd.write('%10.2f*%9.2f*' % (bus[i, PD] - sum(gen[ld, PG]),
                                            bus[i, QD] - sum(gen[ld, QG])))
                objValue2 = objValue2 + (lamP[i]) * (bus[i, PD] -
                                                     sum(gen[ld, PG]))
            else:
                fd.write('%10.2f%10.2f ' % tuple(bus[i, [PD, QD]]))
        else:
            fd.write('       -         -   ')

        fd.write('%9.3f' % lamP[i])

        if abs(lamQ[i]) > 1e-4:
            fd.write('%8.3f' % lamQ[i])
        else:
            fd.write('     -')
    fd.write(
        '\n                        --------  --------  --------  --------')
    nzld = find((bus[:, PD] != 0.0) | (bus[:, QD] != 0.0))
    onld = find((gen[:, GEN_STATUS] > 0) & isload(gen))

    fd.write('\n               Total: %9.2f %9.2f %9.2f %9.2f' %
             (sum(gen[ong, PG]), sum(gen[ong, QG]), sum(bus[nzld, PD]) -
              sum(gen[onld, PG]), sum(bus[nzld, QD]) - sum(gen[onld, QG])))
    fd.write('\n')

    print("Local iteration of worker %d is %d" % (ID, nu))
    # calculate local generation cost
    gencost = s.region['gencost']
    pg = s.var['Pg']
    """
	objValue21=0
	for i in range(ng):
		if(pg[i]>0):
			objValue1 = objValue1 - gencost[i,COST+1]* pg[i]
			print(gencost[i,COST+1]* pg[i])
		else:
			objValue21 = objValue21 + gencost[i,COST+1]* (-pg[i])
			print(gencost[i,COST+1]* (-pg[i]))
	objValue2 = objValue21 - objValue2
	objValue = objValue1 + objValue2
	"""

    objValue = dot(gencost[:, COST], pg**2) + dot(
        gencost[:, COST + 1], pg) + sum(gencost[:, COST + 2])
    print(objValue)

    varDual = {
        'ymd': s.var['ymd'],
        'yad': s.var['yad'],
        'yms': s.var['yms'],
        'yas': s.var['yas']
    }
    varPrimal = {
        'Vm': s.var['Vm'],
        'Va': s.var['Va'],
        'Pg': s.var['Pg'],
        'Qg': s.var['Qg']
    }
    Result = {
        'objValue': objValue,
        'varPrimal': varPrimal,
        'varDual': varDual,
        'localiter': nu,
        'primalgap': s.pb['primalgap'],
        'dualgap': s.pb['dualgap']
    }

    ng = s.region['ng']
    for i in range(ng):
        for glob, loc in s.idx["mapping"].items():
            if gen[i, GEN_BUS] == loc:
                gen[i, GEN_BUS] = glob + 1
                break

    for i in range(nb):
        for glob, loc in s.idx["mapping"].items():
            if loc == i:

                bus[i, BUS_I] = glob + 1

    nl = s.region['nl']
    for i in range(nl):
        for glob, loc in s.idx["mapping"].items():
            #print(glob, loc, branch[i, F_BUS])
            if branch[i, F_BUS] == loc:
                #print(branch[tl1,F_BUS])
                branch[i, F_BUS] = glob + 1
                break
    for i in range(nl):
        for glob, loc in s.idx["mapping"].items():
            #print(glob, loc, branch[i, F_BUS])
            if branch[i, T_BUS] == loc:
                #print(branch[tl1,F_BUS])
                branch[i, T_BUS] = glob + 1
                break

    success = flag
    reg_nb = find(bus[:, BUS_AREA] == ID)

    lamP = lamP[ix_(reg_nb, )]

    lamP2 = numpy.array(lamP)

    reg_bus = bus[ix_(reg_nb, )]
    print(reg_bus[:, BUS_I])
    reg_lam = numpy.array((reg_bus[:, BUS_I], lamP))

    print(reg_lam)

    ppc = {}
    ppc["bus"], ppc["gen"], ppc["branch"] = reg_bus, gen, branch

    ids1 = reg_bus[:, BUS_I]
    ids = numpy.array(ids1)
    #ppc["success"] = success
    #ppc=ext2int(ppc)
    P_history = [i * s.region["baseMVA"] for i in P_history]
    Q_history = [i * s.region["baseMVA"] for i in Q_history]

    #results = int2ext(ppc)
    """
	fig = plt.figure()
	curfig = fig.add_subplot(1, 2, 1)
	curfig.plot(P_history, color = 'red', linewidth = 2.5, label = 'P')
	curfig = fig.add_subplot(1, 2, 2)
	curfig.plot(Q_history, color = 'blue', linewidth = 2.5, label = 'Q')
	curfig.set_yscale('log')
	curfig.legend(loc='upper right')
	"""

    #plt.show()
    """
	
	print(all_gas)
	
	while( obj.txpool.inspect.pending.__dict__): pass
	end_time2 = time()
	final_balance = obj.eth.getBalance(obj.toChecksumAddress(client.eth_accounts()[0]))
	print("sasasa",ID, "    ",start_balance - final_balance , "Time ", end_time2 - start_time2)
	"""

    output.put((ID - 1, Result, ppc["bus"], ppc["gen"], ppc["branch"], success,
                lamP2, ids, P_history, Q_history))
    """
Ejemplo n.º 10
0
from ethjsonrpc import EthJsonRpc
c = EthJsonRpc('127.0.0.1', 8545)
print(c.eth_gasPrice())
addr_list = c.eth_accounts()
print(addr_list)
print(c.eth_getBalance(addr_list[0], 'latest'))
print(c.eth_getBalance(addr_list[1], 'latest'))
print(c.eth_getTransactionCount (addr_list[0], 'latest'))
#c.eth_sendTransaction(addr_list[0], addr_list[1], 30400, c.eth_gasPrice(), 1000000, 0)
#print(c.db_putString('testDB', 'myKey', 'myString'))
#print(c.db_getString('testDB', 'myKey'))