Example #1
0
def test_eth_account_recover_message(acct):
    v, r, s = (
        28,
        '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3',
        '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce',
    )
    message = "I♥SF"
    message_hash = defunct_hash_message(text=message)
    from_account = acct.recoverHash(message_hash, vrs=(v, r, s))
    assert from_account == '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
Example #2
0
def test_eth_account_sign(acct, message, key, expected_bytes, expected_hash, v, r, s, signature):
    message_hash = defunct_hash_message(text=message)
    assert message_hash == expected_hash

    signed = acct.signHash(message_hash, private_key=key)
    assert signed.messageHash == expected_hash
    assert signed.v == v
    assert signed.r == r
    assert signed.s == s
    assert signed.signature == signature

    account = acct.privateKeyToAccount(key)
    assert account.signHash(message_hash) == signed
Example #3
0
 def owner(self):
     # defunct_hash_message prepends `\x19Ethereum Signed Message:\n32`
     message_hash = defunct_hash_message(primitive=self.safe_tx_hash)
     return get_signing_address(message_hash, self.v - 4, self.r, self.s)
Example #4
0
    def generate_signature(self, message):
        signature = bytes(self.sdk_web3.eth.account.signHash(defunct_hash_message(message),
                                                             self.account.signer_private_key).signature)

        return signature
Example #5
0
 def sign_message_after_soliditySha3(self, message):
     h = defunct_hash_message(message)
     return self.w3.eth.account.signHash(h, self.private_key).signature
Example #6
0
 def __sign(self, json):
     msg = dumps(json)
     message_hash = defunct_hash_message(text=msg)
     signature = self.__account.signHash(message_hash)['signature']
     return "{}\n---\n{}".format(msg, w3.toHex(signature))
def ecVerify(message, signature):
    message_hash = defunct_hash_message(text=message)
    return w3.eth.account.recoverHash(message_hash, signature=signature)
 def sign_hash(self, text: str = None, hexstr: str = None) -> str:
     msg_hash: str = defunct_hash_message(hexstr=hexstr, text=text)
     signature_dict: AttributeDict = self._account.signHash(msg_hash)
     signature: str = signature_dict["signature"].hex()
     return signature
Example #9
0
def _eth_hashser(data):
    return _EthHasher(defunct_hash_message(data))
Example #10
0
 def sign_offer(msg):
     msg.nonce = os.urandom(32)
     signed_hash = self.__account.signHash(defunct_hash_message(offer_hash(msg)))
     msg.signature = signed_hash.signature
     rospy.loginfo('bidhash: %s signature: %s', binascii.hexlify(offer_hash(msg)), binascii.hexlify(msg.signature))
     self.signed_offer.publish(msg)
Example #11
0
 def sign_result(msg):
     signed_hash = self.__account.signHash(defunct_hash_message(result_hash(msg)))
     msg.signature = signed_hash.signature
     rospy.loginfo('reshash: %s signature: %s', binascii.hexlify(result_hash(msg)), binascii.hexlify(msg.signature))
     self.signed_result.publish(msg)
Example #12
0
def handle_subdomain_post_request(request, github_handle):
    # setup
    signed_msg = request.POST.get('signedMsg', '')
    signer = request.POST.get('signer', '').lower()
    if signed_msg and signer:
        # validation
        message_hash = defunct_hash_message(
            text=f'Github Username : {github_handle}')
        recovered_signer = w3.eth.account.recoverHash(
            message_hash, signature=signed_msg).lower()
        if recovered_signer != signer:
            return JsonResponse({
                'success': False,
                'msg': _('Sign Mismatch Error')
            })
        if not request.user.profile.trust_profile and request.user.profile.github_created_on > (
                timezone.now() - timezone.timedelta(days=7)):
            return JsonResponse({
                'success':
                False,
                'msg':
                _('For SPAM prevention reasons, you may not perform this action right now.  '
                  'Please contact support if you believe this message is in error.'
                  )
            })

        # actually setup subdomain
        start_nonce = get_nonce()
        nonce = start_nonce
        txn_hash_1 = set_owner(signer, github_handle, nonce)
        nonce += 1
        txn_hash_2 = set_resolver(signer, github_handle, nonce)
        nonce += 1
        txn_hash_3 = set_address_at_resolver(signer, github_handle, nonce)

        gas_price = get_gas_price()
        gas_cost_eth = (RESOLVER_GAS_COST + OWNER_GAS_COST +
                        SET_ADDRESS_GAS_COST) * gas_price / 10**18
        profile = Profile.objects.filter(handle=github_handle.lower()).first()
        if not txn_hash_1 or not txn_hash_2 or not txn_hash_3:
            return JsonResponse({
                'success':
                False,
                'msg':
                _('Your ENS request has failed. Please try again.')
            })
        ENSSubdomainRegistration.objects.create(
            profile=profile,
            subdomain_wallet_address=signer,
            txn_hash_1=txn_hash_1,
            txn_hash_2=txn_hash_2,
            txn_hash_3=txn_hash_3,
            pending=True,
            signed_msg=signed_msg,
            start_nonce=start_nonce,
            end_nonce=nonce,
            gas_cost_eth=gas_cost_eth,
        )
        return JsonResponse({
            'success':
            True,
            'msg':
            _('Your request has been submitted. Please wait for the transaction to mine!'
              )
        })
    return handle_default_response(request, github_handle)
Example #13
0
    def post(self):
        """ Handle POST request """

        if not self.request.body:
            log.warning('Missing body')
            self.set_status(400)
            self.write_json({
                'success': False,
                'clicks': None,
                'token': '',
            })
            return

        req = json.loads(self.request.body)
        token = req.get('token')
        recipient = req.get('recipient')
        contract = req.get('contract')

        invalids = []
        if not is_valid_token(token):
            invalids.append('token')
        if not recipient or not is_address(recipient):
            invalids.append('recipient')
        if not contract or not is_address(contract):
            invalids.append('contract')

        recipient = Web3.toChecksumAddress(recipient)
        contract = Web3.toChecksumAddress(contract)

        if len(invalids) > 0:
            log.warning('Invalid input: {}'.format(', '.join(invalids)))

            self.set_status(400)
            self.write_json({
                'success': False,
                'clicks': None,
                'token': '',
                'message': 'Invalid input'
            })
            return

        # Verify it exists
        clicks = rgetint(self.redis, token, 0)

        if not clicks:
            log.warning('Token has no clicks')
            self.write_json({
                'success': False,
                'clicks': None,
                'token': token,
                'message': 'Try clicking first'
            })
            return

        log.info('create_claim({}, {}, {}, {})'.format(recipient,
                                                       add_0x_prefix(token),
                                                       clicks * int(1e18),
                                                       contract))

        # Assemble claim
        claim = create_claim(recipient, add_0x_prefix(token),
                             clicks * int(1e18), contract)
        prefixed_claim_hash = defunct_hash_message(claim)
        # Docstring for this function sugests this does not prefix messages, so
        # we're prefixing above
        signed = self.accounts.eth_account.signHash(
            prefixed_claim_hash, self.signer_account_privkey)

        self.write_json({
            'success': True,
            'clicks': clicks,
            'token': token,
            'claim': claim.hex(),
            'signature': signed.signature.hex(),
            'contract': contract,
        })
    def device_discovered(self, device):

        mac_address = device.mac_address.replace(':', '_').upper()
        path = '/org/bluez/%s/dev_%s' % (self.adapter_name, mac_address)
        device_object = bus.get_object("org.bluez", path)
        d = dbus.Interface(device_object, "org.bluez.Device1")
        device_properties = dbus.Interface(d,
                                           "org.freedesktop.DBus.Properties")
        uuids = [
            str(x) for x in device_properties.Get("org.bluez.Device1", "UUIDs")
        ]

        if uuids:
            device_uuids[device.mac_address].union(set(uuids))
            for u in uuids:

                # - decrypt with firefly_key
                ack_uuid = uuid.UUID('urn:uuid:{}'.format(u))

                decrypted_payload = decrypt(ack_uuid.bytes)

                # - verify it contains crc24 + data

                pl_crc = decrypted_payload[:3]
                pl_data = decrypted_payload[3:]

                crc_val = crc24(pl_data)
                ver_crc = (crc_val).to_bytes(3, byteorder='big', signed=False)

                if pl_crc != ver_crc:
                    # print("CRC24 mismatch\nCalculated {}\nExpected {}".format(
                    #    [str(sbyte(b)) for b in ver_crc],
                    #    [str(sbyte(b)) for b in pl_crc]
                    #    ))
                    break

                # henceforth we know it's a firefly message

                print('MAC Address ', device.mac_address)
                print('UUID Payload ', u)
                print("Decrypted Payload {}".format(
                    [str(sbyte(b)) for b in decrypted_payload]))

                # - break data based on firefly semantics

                blecast_ctl = pl_data[0].to_bytes(1, byteorder="big")
                firefly_cmd = pl_data[1].to_bytes(1, byteorder="big")
                firefly_data = pl_data[2:]

                # print(blecast_ctl)

                if blecast_ctl != b'\x00':
                    print(
                        'messages dependent on multiple advertisements are not supported yet'
                    )
                    break

                # - sign actual payload

                if firefly_cmd != b'\x02':
                    print('unsupported firefly command {}'.format(firefly_cmd))
                    self.stop()
                    break

                print()
                resp = input('sign "{}"? (y/N) '.format(
                    str(firefly_data))).strip()

                if resp.lower() != 'y' and resp.lower() != 'yes':
                    break

                message_hash = defunct_hash_message(primitive=firefly_data)
                signed_message = w3.eth.account.signHash(
                    message_hash, private_key=eth_account.privateKey)

                recovered = w3.eth.account.recoverHash(
                    message_hash,
                    vrs=(28, hex(signed_message['r']),
                         hex(signed_message['s'])))
                assert (recovered == eth_account.address)

                # print('r\t', hex(signed_message['r']))
                # print('s\t', hex(signed_message['s']))
                # print('v\t', hex(signed_message['v']))
                # print()
                # print(firefly_data)
                # print([str(sbyte(b)) for b in firefly_data])
                # print()
                # print(message_hash.hex())
                # print(len(message_hash))
                # print([str(sbyte(b)) for b in message_hash])
                # print()
                # print(signed_message)
                # print()

                sig_s = 'SIG:S/{}'.format(hex(signed_message['s']))
                sig_r = 'SIG:R/{}'.format(hex(signed_message['r']))

                qr_s = qrcode.make(sig_s)
                qr_r = qrcode.make(sig_r)

                w, h = qr_s.size

                new_im = Image.new('L', (w * 2, h))

                new_im.paste(qr_r)
                new_im.paste(qr_s, (w, 0))
                new_im.show()

                self.stop()
Example #15
0
def test_eth_account_hash_message_hexstr(acct, message, expected):
    assert defunct_hash_message(hexstr=message) == expected
# get the deeID contract
deeIDContract = w3.eth.contract(
    address=address,
    abi=abi,
)

# address of the identity holder
#address = Web3.toChecksumAddress("0xf2beae25b23f0ccdd234410354cb42d08ed54981")

address = Web3.toChecksumAddress(req_data['recDID'])

# the public key we wish to verify
# WE NEED msg AND sig
# NOT SECURE, IN THE FUTURE RUN PROPER MSG PROCESSING
msgHash = defunct_hash_message(text=req_data['msg'])
verPubKey = w3.eth.account.recoverHash(msgHash, signature=req_data['sig'])
#verPubKey = "0x627306090abab3a6e1400e9345bc60c78a8bef57"
"""
# set pre-funded account as sender
w3.eth.defaultAccount = w3.eth.accounts[1]
print(Web3.toChecksumAddress(w3.eth.defaultAccount))

# get the DID contract
DIDContract = w3.eth.contract(
    address=address,
    abi=abi,
)

# search through the keys
def keySearch(DIDContract):
Example #17
0
def hash_message(msg_bytes):
    return defunct_hash_message(msg_bytes)
 def _verify_my_signature(self, signature, mpe_address, channel_id, nonce, amount):
     message      = self._compose_message_to_sign(mpe_address, channel_id, nonce, amount)
     message_hash = defunct_hash_message(message)
     sign_address = self.ident.w3.eth.account.recoverHash(message_hash, signature=signature)
     return sign_address == self.ident.address
Example #19
0
def sign(message, privateKey):
    messageHash = defunct_hash_message(text=message)
    signedMessage = web3.eth.account.signHash(messageHash,
                                              private_key=privateKey)
    return web3.toHex(signedMessage.signature)
Example #20
0
def mission_diplomacy_room_helper(request, game):

    # handle invites
    users_players = GamePlayer.objects.filter(active=True,
                                              profile=request.user.profile)
    users_games = Game.objects.filter(pk__in=users_players.values_list("game"))
    users_player = users_players.first()
    if game not in users_games:
        if request.user.is_authenticated:

            # too many user condition
            if game.active_players.count() >= max_players_per_game:
                messages.info(
                    request,
                    f'There are already {max_players_per_game} in the game.  Wait for someone to leave + try again.'
                )
                return mission_diplomacy_helper(request)

            # show invite
            if request.GET.get('join'):
                game.add_player(request.user.profile.handle)
            else:
                return mission_diplomacy_helper(request, invited_to_game=game)
        else:
            # logged out condition
            messages.info(request, f'Please login to join this game.')

    # in game experience
    is_member = game.is_active_player(request.user.profile.handle)
    is_admin = game.players.filter(admin=True,
                                   profile=request.user.profile).exists()
    if is_admin:
        if request.GET.get('remove'):
            remove_this_fool = request.GET.get('remove')
            for player in game.players.filter(
                    active=True, profile__handle=remove_this_fool):
                game.remove_player(player.profile.handle)
                messages.info(request, f'{remove_this_fool} has been removed')

    # delete game
    if is_member and request.GET.get('delete'):
        game.remove_player(request.user.profile.handle)
        messages.info(request, f'You have left this game.')
        return redirect('/quadraticlands/mission/diplomacy')

    # chat in game
    if is_member and request.POST.get('chat'):
        game.chat(request.user.profile.handle, request.POST.get('chat'))

    # make a move
    if is_member and request.POST.get('signature'):
        package = request.POST.get('package')
        moves = json.loads(package)
        signature = request.POST.get('signature')
        recipient_address = Web3.toChecksumAddress(moves['account'])
        web3 = get_web3('mainnet')
        gtc = web3.eth.contract(address=Web3.toChecksumAddress(
            '0xde30da39c46104798bb5aa3fe8b9e0e1f348163f'),
                                abi=erc20_abi)
        balance = int(
            (gtc.functions.balanceOf(recipient_address).call()) / (10**18))
        claimed_balance = int(moves['balance'])
        signer_address = Web3.toChecksumAddress(
            web3.eth.account.recoverHash(defunct_hash_message(text=package),
                                         signature=signature))
        claimed_address = Web3.toChecksumAddress(moves['account'])

        if claimed_balance != balance:
            return HttpResponse('not authorized - bad balance', status=401)

        if claimed_address != signer_address:
            return HttpResponse('not authorized - bad addr', status=401)

        data = {
            'moves': moves,
            'signature': signature,
        }
        game.make_move(request.user.profile.handle, data)
        return JsonResponse({'msg': 'OK', 'url': game.url})

    # game view
    params = {
        'title': game.title,
        'users_player': users_player,
        'game': game,
        'is_admin': is_admin,
        'max_players': max_players_per_game,
    }
    return TemplateResponse(request,
                            'quadraticlands/mission/diplomacy/room.html',
                            params)
Example #21
0
def buildUnsignedOrder(message):
    message_hash = defunct_hash_message(text=message)
    signed_msg = w3.eth.account.signHash(message_hash, private_key=private_key)
    signed_msg = signed_msg.signature
    signature = w3.toHex(signed_msg)
    return signature
Example #22
0
from web3.auto import w3
from eth_account.messages import defunct_hash_message
import json, binascii
from hexbytes import HexBytes

import asyncio
import websockets

# Acting like the mobile phone
msg = 'bmMfnO5HE2m2'
pk = '0xb50c18d670e82f3f559142d63773b5f60882d337f7d40e78f87973484740ab0d'
msgHash = defunct_hash_message(text=msg)

signedMsg = w3.eth.account.signHash(msgHash, private_key=pk)
#hexdecimal = "".join(["{:02X}".format(b) for b in hb])
#print(hexdecimal)
hexSig = binascii.hexlify(signedMsg.signature)
sig = str(hexSig).split("'")[1]
print('------------------------------')
print(w3.eth.account.recoverHash(msgHash, signature=signedMsg.signature))
print('------------------------------')


v = json.dumps({
			'type' : 'loginSig',
			'host' : msg,
			'signature' : str(sig)
		})

print(v)
Example #23
0
def deploy(ctx_obj):
    """
    Deploys a new instance of ERC20Mintable.sol on MaticVigil.
    When prompted, enter a JSON-compatible list of constructor inputs to be passed on to the ERC20Mintable contract.

    For example, ["My Token", "SYMBOL", 18] corresponding to ERC20 standards: token name, token symbol, token decimals
    NOTE: Enter double quoted strings. Single quoted strings are not supported as JSON serialized.

    Check deploy.py for a code example
    """
    msg = "Trying to deploy"
    message_hash = defunct_hash_message(text=msg)
    private_key = ctx_obj['private_key']
    contract_addr = ctx_obj['contract_address']
    if contract_addr != '':
        if click.confirm(
                'You already have a contract address specified in the settings file. '
                'Do you want to proceed with deploying another contract? '):
            pass
        else:
            return
    click.echo('Enter the list of constructor inputs: ')
    constructor_inputs = input()
    if constructor_inputs.strip() == "":
        if click.confirm(
                'Do you want to use the defaults ["My Token", "SYMBOL", 18]'):
            constructor_inputs = ["My Token", "SYMBOL", 18]
        else:
            return
    else:
        try:
            constructor_inputs = json.loads(constructor_inputs)
        except json.JSONDecodeError:
            click.echo("Enter a valid JSON list for constructor inputs")
            if click.confirm(
                    'Do you want to use the defaults ["My Token", "SYMBOL", 18]'
            ):
                constructor_inputs = ["My Token", "SYMBOL", 18]
            else:
                return
    sig_msg = Account.signHash(message_hash, private_key)
    with open('./ERC20Mintable.sol', 'r') as f:
        contract_code = f.read()
    deploy_params = {
        'msg': msg,
        'sig': sig_msg.signature.hex(),
        'name': 'ERC20Mintable',
        'inputs': constructor_inputs,
        'code': contract_code
    }
    click.echo('Deploying with constructor arguments: ')
    click.echo(constructor_inputs)
    # API call to deploy
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    r = requests.post(ctx_obj['internal_api_endpoint'] + '/deploy',
                      json=deploy_params,
                      headers=headers)
    rj = r.json()
    click.echo('Deployed contract results')
    click.echo(rj)
    if rj['success']:
        click.echo('Copy the contract address into settings.json')
Example #24
0
 def sign_message(self, message, out_f, agent_version=2):
     if agent_version == 1:
         h = defunct_hash_message(hexstr=self.w3.sha3(hexstr=message).hex())
     else:
         h = defunct_hash_message(text=message.lower())
     return self.w3.eth.account.signHash(h, self.private_key).signature
Example #25
0
    def deploy(self, contract_file, contract_name, inputs):
        """
        Deploys a smart contract from the solidity source code specified
        :param contract_file : path to the contract file name
        :param contract_name : the contract name to be deployed from the file
        :param inputs : mapping of constructor arguments
        """
        contract_src = ""
        if self._verbose:
            print('Got unordered constructor inputs: ')
            print(inputs)

        sources = dict()

        if contract_file[0] == '~':
            contract_full_path = os.path.expanduser(contract_file)
        else:
            contract_full_path = contract_file
        resident_directory = ''.join(
            map(lambda x: x + '/',
                contract_full_path.split('/')[:-1]))
        contract_file_name = contract_full_path.split('/')[-1]
        contract_file_obj = open(file=contract_full_path)

        main_contract_src = ''
        while True:
            chunk = contract_file_obj.read(1024)
            if not chunk:
                break
            main_contract_src += chunk
        sources[f'ev-py-sdk/{contract_file_name}'] = {
            'content': main_contract_src
        }
        # loop through imports and add them to sources
        source_unit = parser.parse(main_contract_src)
        source_unit_obj = parser.objectify(source_unit)

        for each in source_unit_obj.imports:
            import_location = each['path'].replace("'", "")
            # TODO: follow specified relative paths and import such files too
            if import_location[:2] != './':
                ev_core_logger.error(
                    'You can only import files from within the same directory as of now'
                )
                raise EVBaseException(
                    'You can only import files from within the same directory as of now'
                )
            # otherwise read the file into the contents mapping
            full_path = resident_directory + import_location[2:]
            imported_contract_obj = open(full_path, 'r')
            contract_src = ''
            while True:
                chunk = imported_contract_obj.read(1024)
                if not chunk:
                    break
                contract_src += chunk
            sources[f'ev-py-sdk/{import_location[2:]}'] = {
                'content': contract_src
            }

        abi_json = extract_abi(self._settings, {
            'sources': sources,
            'sourceFile': f'ev-py-sdk/{contract_file_name}'
        })
        abp = ABIParser(abi_json=abi_json)
        abp.load_abi()
        c_inputs = abp.ordered_map_to_ev_constructor_args(inputs)
        if self._verbose:
            print('Ordered constructor inputs: \n', c_inputs)

        msg = "Trying to deploy"
        message_hash = defunct_hash_message(text=msg)
        signed_msg = Account.signHash(message_hash,
                                      self._settings['PRIVATEKEY'])
        deploy_json = {
            'msg': msg,
            'sig': signed_msg.signature.hex(),
            'name': contract_name,
            'inputs': c_inputs,
            'sources': sources,
            'sourceFile': f'ev-py-sdk/{contract_file_name}'
        }
        # --MATICVIGIL API CALL---
        r = make_http_call(request_type='post',
                           url=self._settings['INTERNAL_API_ENDPOINT'] +
                           '/deploy',
                           params=deploy_json)
        if self._verbose:
            ev_core_logger.debug('MaticVigil deploy response: ')
            ev_core_logger.debug(r)
        return r['data']
Example #26
0
def sign_message_with_private_key(w3, private_key, message):
    h = defunct_hash_message(message)
    return w3.eth.account.signHash(h, private_key).signature
def sign_message(account, message_str):
    msg_hash = defunct_hash_message(text=message_str)
    full_signature = account.sign_message(msg_hash)
    return full_signature.signature.hex()
Example #28
0
def verify_sign(address, signature, primitive=None, hexstr=None, text=None):

    msg_hash = defunct_hash_message(primitive, hexstr, text)
    signature = w3.toBytes(hexstr=signature)
    return address == w3.eth.account.recoverHash(msg_hash, signature=signature)
Example #29
0
def test_commit_access_requested(client):
    expire_seconds = 9999999999
    consumer_account = ocean.web3.eth.accounts[1]
    # consumer_account = '0x009c95E90369bED8ECCD3AA3DFaf0F8a90849b17'
    provider_account = ocean.web3.eth.accounts[0]
    # provider_account = '0x007341576b7F7fB0A135728C1A9DA487b1191124'
    print("Starting test_commit_access_requested")
    print("buyer: %s" % consumer_account)
    print("seller: %s" % provider_account)

    resource_id = market_concise.generateId(
        'resource', transact={'from': provider_account})
    print("recource_id: %s" % resource_id)
    resource_price = 10
    json_consume['assetId'] = ocean.web3.toHex(resource_id)
    client.post(BaseURLs.BASE_PROVIDER_URL + '/assets/metadata',
                data=json.dumps(json_consume),
                content_type='application/json')

    pubprivkey = generate_encryption_keys()
    pubkey = pubprivkey.public_key
    privkey = pubprivkey.private_key

    market_concise.requestTokens(2000, transact={'from': provider_account})
    market_concise.requestTokens(2000, transact={'from': consumer_account})

    # TODO Use the events with the filters intitialized by the application insetad of this
    # filter_access_consent = ocean.watch_event(OceanContracts.OACL, 'AccessConsentRequested',
    #                                           ocean.commit_access_request, 250,
    #                                           fromBlock='latest', filters={"address": provider_account})
    # filter_payment = ocean.watch_event(OceanContracts.OMKT, 'PaymentReceived', ocean.publish_encrypted_token, 2500,
    #                                    fromBlock='latest', filters={"address": provider_account})

    # 1. Provider register an asset
    market_concise.register(resource_id,
                            resource_price,
                            transact={'from': provider_account})
    # 2. Consumer initiate an access request
    expiry = int(time.time() + expire_seconds)
    req = acl_concise.initiateAccessRequest(
        resource_id,
        provider_account,
        pubkey,
        expiry,
        transact={'from': consumer_account})
    receipt = ocean.get_tx_receipt(req)
    send_event = acl.events.AccessConsentRequested().processReceipt(receipt)
    request_id = send_event[0]['args']['_id']

    # events = get_events(filter_access_consent)

    # assert send_event[0] in events
    assert acl_concise.statusOfAccessRequest(
        request_id) == 0 or acl_concise.statusOfAccessRequest(request_id) == 1

    filter_token_published = ocean.watch_event(
        OceanContracts.OACL,
        'EncryptedTokenPublished',
        process_enc_token,
        0.25,
        fromBlock='latest')  # , filters={"id": request_id})

    # 3. Provider commit the request in commit_access_request

    # Verify consent has been emited
    i = 0
    while (acl_concise.statusOfAccessRequest(request_id)
           == 1) is False and i < 100:
        i += 1
        time.sleep(0.1)

    assert acl_concise.statusOfAccessRequest(request_id) == 1

    # 4. consumer make payment after approve spend token
    token.approve(ocean.web3.toChecksumAddress(market_concise.address),
                  resource_price,
                  transact={'from': consumer_account})

    buyer_balance_start = token.balanceOf(consumer_account)
    seller_balance_start = token.balanceOf(provider_account)
    print('starting buyer balance = ', buyer_balance_start)
    print('starting seller balance = ', seller_balance_start)

    send_payment = market_concise.sendPayment(request_id,
                                              provider_account,
                                              resource_price,
                                              expiry,
                                              transact={
                                                  'from': consumer_account,
                                                  'gas': 400000
                                              })

    print('buyer balance = ', token.balanceOf(consumer_account))
    print('seller balance = ', token.balanceOf(provider_account))

    # tx_hashes = set()
    # events = get_events(filter_payment)
    # for ev in events:
    #     tx_hashes.add(ev['transactionHash'])

    # assert events
    # assert send_payment in tx_hashes

    # assert acl_concise.getTempPubKey(request_id, call={"from": provider_account}) == pubkey

    events = get_events(filter_token_published)
    assert events
    assert events[0].args['_id'] == request_id
    on_chain_enc_token = events[0].args["_encryptedAccessToken"]
    on_chain_enc_token2 = acl_concise.getEncryptedAccessToken(
        request_id, call={'from': consumer_account})

    decrypted_token = dec(on_chain_enc_token, privkey)
    # pub_key = ocean.encoding_key_pair.public_key
    access_token = decode(decrypted_token)

    assert pubkey == access_token['temp_pubkey']
    signature = ocean.web3.eth.sign(consumer_account, data=on_chain_enc_token)

    fixed_msg = defunct_hash_message(
        hexstr=ocean.web3.toHex(on_chain_enc_token))

    sig = ocean.split_signature(signature)
    #
    # assert acl_concise.isSigned(consumer_account,
    #                             ocean.web3.toHex(fixed_msg),
    #                             sig.v,
    #                             sig.r,
    #                             sig.s,
    #                             call={'from': provider_account})
    json_request_consume['fixed_msg'] = ocean.web3.toHex(fixed_msg)
    json_request_consume['consumerId'] = consumer_account
    json_request_consume['sigEncJWT'] = ocean.web3.toHex(signature)
    json_request_consume['jwt'] = ocean.web3.toBytes(
        hexstr=ocean.web3.toHex(decrypted_token)).decode('utf-8')

    post = client.post(access_token['service_endpoint'].split('5000')[1] +
                       '/%s' % ocean.web3.toHex(resource_id),
                       data=json.dumps(json_request_consume),
                       content_type='application/json')
    print(post.data.decode('utf-8'))
    assert post.status_code == 200
    assert acl_concise.statusOfAccessRequest(request_id) == 3

    buyer_balance = token.balanceOf(consumer_account)
    seller_balance = token.balanceOf(provider_account)
    print('end: buyer balance -- current %s, starting %s, diff %s' %
          (buyer_balance, buyer_balance_start,
           (buyer_balance - buyer_balance_start)))
    print('end: seller balance -- current %s, starting %s, diff %s' %
          (seller_balance, seller_balance_start,
           (seller_balance - seller_balance_start)))
    assert token.balanceOf(
        consumer_account) == buyer_balance_start - resource_price
    assert token.balanceOf(
        provider_account) == seller_balance_start + resource_price
    print('All good \/')
Example #30
0
def test_eth_account_hash_message_text(message, expected):
    assert defunct_hash_message(text=message) == expected
 def _verify_my_signature(self, signature, mpe_address, channel_id, nonce, amount):
     message      = self._compose_message_to_sign(mpe_address, channel_id, nonce, amount)
     message_hash = defunct_hash_message(message)
     sign_address = self.ident.w3.eth.account.recoverHash(message_hash, signature=signature)
     return sign_address == self.ident.address
 def generate_signature_bytes(self, data_types, values, signer_key):
     signer_key = "0x" + signer_key if not signer_key.startswith("0x") else signer_key
     message = web3.Web3.soliditySha3(data_types, values)
     signature = self.web3_object.eth.account.signHash(defunct_hash_message(message), signer_key)
     return bytes(signature.signature)
Example #33
0
def recover_to_addr(token, signature):
    msghash = defunct_hash_message(text=token)
    address = w3.eth.account.recoverHash(msghash, signature=signature)
    res = is_hex_address(address)
    return address