Example #1
0
def check_signature(data, debug=False):
    '''Check address and signature'''

    _from = data.get('from')
    _to = data.get('to')
    # Check addresses if they are Eth compatible
    if not w3.isAddress(_from) or not w3.isAddress(_to):
        return False

    msg = '{0}-{1}-{2}-{3}-{4}-{5}'.format(data.get('from'), data.get('to'),
                                           data.get('amount'),
                                           data.get('timestamp'),
                                           data.get('fees'), data.get('data'))
    msg_hash = defunct_hash_message(text=msg)
    pub_key = w3.eth.account.recoverHash(  # pylint: disable=no-member
        msg_hash,
        signature=data.get('signature'))
    if debug:
        print('POST: {0} | Check: {1}'.format(data.get('from'), pub_key),
              pub_key == data.get('from'))

    if data.get('from') == pub_key:
        return True

    return False
Example #2
0
def verify(tx_hash, recipient_id):
    w3 = Web3(
        HTTPProvider(
            'https://rinkeby.infura.io/cc1357bd5e1347d3b9a3433085e61ae5'))

    # check the Addresses and the Amount of the Sender
    if w3.isAddress(recipient_id) == False or w3.isAddress(Stamp_id) == False:
        return None

    # wait until the Transaction is finished
#    w3.eth.waitForTransactionReceipt(tx_hash)      # not working unvalid Transactions brings TimeOut
# get the Transaction
    trans = w3.eth.getTransaction(tx_hash)

    # check the existing of the Transaction
    if trans == None:
        return None

    # remove the 0x from the recipient-Address and lowerCase the recipient-Address
    rec_id = recipient_id[2:]
    rec_id = rec_id.lower()

    # check the correct recipient of the transaction
    rec_result = False
    if rec_id in trans['input']:
        rec_result = True

    # check the correct contract of the transaction
    contr_result = False
    if Stamp_id.lower() == trans['to'].lower():
        contr_result = True

    # recipient and contract correct ?
    result = rec_result and contr_result
    return result
Example #3
0
    def list(self, request, address, *args, **kwargs):
        '''GET addresses informations'''

        if not w3.isAddress(address):
            return Response({
                'status': status.HTTP_400_BAD_REQUEST,
                'msg': 'Address not valid'
            })

        query = models.Address.objects.filter(address=address.lower()).first()
        if not query:
            return Response({
                'status': status.HTTP_200_OK,
                'data': {
                    'address': address.lower(),
                    'balance': 0,
                    'transactions': []
                }
            })

        serialized = self.serializer_class(query)
        return Response({
            'status': status.HTTP_200_OK,
            'data': serialized.data
        })
Example #4
0
def amountStamps(sender_id):
    w3 = Web3(
        HTTPProvider(
            'https://rinkeby.infura.io/cc1357bd5e1347d3b9a3433085e61ae5'))

    # check the Addresses and the Amount of the Sender
    if w3.isAddress(sender_id) == False or w3.isAddress(Stamp_id) == False:
        return None

    # load the contract for the Stamp
    address_contract = w3.toChecksumAddress(Stamp_id)
    contract = w3.eth.contract(address=address_contract, abi=EIP20_ABI)

    # load the amount of Stamps for the sender
    address_sender = w3.toChecksumAddress(sender_id)
    stamp_amount = contract.call().balanceOf(address_sender)
    return (stamp_amount)
Example #5
0
def send(sender_id, sender_key, recipient_id):
    w3 = Web3(
        HTTPProvider(
            'https://rinkeby.infura.io/cc1357bd5e1347d3b9a3433085e61ae5'))

    # check the Addresses and the Amount of the Sender
    if w3.isAddress(sender_id) == False or w3.isAddress(
            recipient_id) == False or w3.isAddress(Stamp_id) == False:
        return None
    if amountStamps(sender_id) < 1:
        return None

    # load the contract for the Stamp
    address_contract = w3.toChecksumAddress(Stamp_id)
    contract = w3.eth.contract(address=address_contract, abi=EIP20_ABI)

    # get the nonce for the sender
    nonce = w3.eth.getTransactionCount(sender_id)

    # build the Transaction
    stamp_txn = contract.functions.transfer(
        w3.toChecksumAddress(recipient_id),
        1,
    ).buildTransaction({
        'chainId': 4,
        'gas': 70000,
        'gasPrice': w3.toWei('1', 'gwei'),
        'nonce': nonce,
    })

    # sign the Transaction
    signed_txn = w3.eth.account.signTransaction(stamp_txn,
                                                private_key=sender_key)

    #send the Transaction
    result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    result = w3.toHex(result)

    return result
Example #6
0
def pre_fund(pre_funded_accounts):
    alloc = {}

    for account in pre_funded_accounts:
        if w3.isAddress(account['address']) and int(account['balance']) > 0:
            address = account['address'][2:]

            balance_wei = w3.toWei(account['balance'], 'ether')
            alloc[address] = {
                "balance": w3.toHex(balance_wei)
            }

    return alloc
def Ethertxn():

    if not path.exists('/home/pi/EthereumWallet_local_API/wallet/keystore'):
        return make_response(jsonify({'response': "Address not exists"}))

    data = request.values['data'].split(',')
    print(data)
    nonce = int(data[3].split("\b")[0])
    password = data[0]
    mk = makeTxn(password)
    print('mktxn: ', mk.password)
    if not w3.isAddress(data[1]):
        return make_response(jsonify({'response': "Address Error"}))

    try:
        tmp = mk.EtherTxn(data[1], float(data[2]), nonce, int(data[4]),
                          int(data[5]))
    #tmp = hex(int.from_bytes(tmp,byteorder='big'))
    except:
        return make_response(jsonify({'response': "Value Error"}))
    return make_response(jsonify({'response': str(tmp)}), 200)
Example #8
0
    def post(self, request, *args, **kwargs):
        '''POST method redirects to valid URL'''
        search = request.POST.get('search-input')
        if not search:
            raise Http404('Invalid search argument')

        if w3.isAddress(search):
            return redirect(reverse('address_info', args=[search]))

        if all(k.isdigit() for k in search):
            return redirect(reverse('block_info', args=[search]))

        if search.isalnum():
            if models.BlockStructureDB.objects.filter(
                    block_hash=search).exists():
                return redirect(reverse('block_info', args=[search]))

            elif models.TransactionDB.objects.filter(tx_hash=search).exists():
                return redirect(reverse('transaction_info', args=[search]))
            else:
                raise Http404('Invalid search argument')
Example #9
0
def check_address(address):
    return w3.isAddress(address)
Example #10
0
 def convert(self, value, param, ctx):
     if w3.isAddress(value):
         return value
     else:
         self.fail(f'Wrong Ethereum address provided: {value}', param, ctx)
Example #11
0
localPassword = "******"
ownerAddress = ""
localAccount = ""

if (os.path.exists('auth-a.json') == False):
    authenticationSet = {}
    #generate keys
    localAccount = w3.eth.account.create('seed')

    accountDump = w3.eth.account.encrypt(localAccount.privateKey,
                                         localPassword)

    authenticationSet['keystore'] = accountDump
    ownerAddress = input("Insert the owner address\r\n")
    while (w3.isAddress(ownerAddress) == False):
        ownerAddress = input("Address not valid. Insert the owner address\r\n")
    authenticationSet['ownerAddress'] = ownerAddress
    with open('auth-a.json', 'w') as f:
        json.dump(authenticationSet, f)
else:
    with open('auth-a.json', 'r') as f:
        datastore = json.load(f)
    privateKey = w3.eth.account.decrypt(datastore['keystore'], localPassword)
    localAccount = w3.eth.account.privateKeyToAccount(privateKey)
    ownerAddress = datastore['ownerAddress']
print(localAccount.address)
rules = load_rules(ownerAddress)

while (True):
    try:
Example #12
0
### DEBUG
# enclave private = "0x564a9db84969c8159f7aa3d5393c5ecd014fce6a375842a45b12af6677b12407"
# enclave address = 0x3cB738D98D7A70e81e81B0811Fae2452BcA049Bc
# digest    = w3.soliditySha3([ 'string' ], [ 'iExec the wanderer' ]).hex()

if __name__ == '__main__':

    taskid = os.environ.get(
        'TASKID'
    )  # or '0x8b43265c231bd32d1b249c1ce58bf0c77a9ebc6a30da37e961063a073a921e06'
    worker = os.environ.get(
        'WORKER')  # or '0x748e091bf16048cb5103E0E10F9D5a8b7fBDd860'
    keyfile = os.environ.get('KEYFILE') or '/app/priv_key'

    if not taskid: raise ValueError('Missing TASKID')
    if not w3.isAddress(worker): raise ValueError('Invalid worker address')

    worker = w3.toChecksumAddress(worker)

    print("Genrating result and consensus.iexec in /iexec ...")
    shutil.copy("/app/result.txt", "/iexec/result.txt")
    shutil.copy("/app/result.txt", "/iexec/consensus.iexec")

    with open(keyfile) as f:
        private = f.read().splitlines()[0]

    digest = "0x" + fileChecksum("/iexec/consensus.iexec",
                                 "sha256")  # hexstring
    hash = w3.soliditySha3(['bytes32', 'bytes32'], [taskid, digest])
    seal = w3.soliditySha3(['address', 'bytes32', 'bytes32'],
                           [worker, taskid, digest])
Example #13
0
 def clean_address(self):
     '''Validate an address before saving'''
     if not w3.isAddress(self.address):
         raise ValidationError(
             '{} is not a valid Ethereum address'.format(self.address)
         )
Example #14
0
def validate_address(addr):
    '''Validate Ethereum address'''
    if not w3.isAddress(addr):
        raise ValidationError(
            '{} is not a valid Ethereum address'.format(addr)
        )
Example #15
0
        decimals = underlying.decimals()
        reserve = swap.balances(i) / 1e18 * coin.exchangeRateCurrent() / 10 ** decimals
        return cls(coin=coin, underlying=underlying, decimals=decimals, reserve=reserve)


coins = [Coin.from_index(i) for i in range(2)]

print('Currency reserves:')
for coin in coins:
    print(f'{coin.underlying.symbol()}: {coin.reserve:,.2f}')

fee = swap.fee() / 1e10
admin_fee = swap.admin_fee() / 1e10
print(f'Fee: {fee:.3%}')
print(f'Admin fee: {admin_fee:.3%}')
print(f'Virtual price: {swap.get_virtual_price() / 1e18}')

# show LP stats if address is provided
if len(sys.argv) > 1:
    me = sys.argv[1]
    me = w3.toChecksumAddress(me) if w3.isAddress(me) else me
    print('\nMy share:')

    token_balance = token.balanceOf(me) / 1e18
    token_supply = token.totalSupply() / 1e18
    share = token_balance / token_supply
    print(f'{token.symbol()}: {token_balance:,.2f}')

    for coin in coins:
        print(f'{coin.underlying.symbol()}: {coin.reserve * share:,.2f}')