Example #1
0
    def __init__(self):
        global Web3
        try:
            from web3 import Web3, HTTPProvider
        except ImportError:
            raise MarketplaceRequiresPython3()

        self.addresses = get_user_pubaddr()

        if self.addresses[0]['pubAddr'] == '':
            raise MarketplacePubAddressEmpty(filename=os.path.join(
                get_marketplace_folder(), 'addresses.json'))
        self.default_account = self.addresses[0]['pubAddr']

        self.web3 = Web3(HTTPProvider(ETH_REMOTE_NODE))

        contract_url = urllib.urlopen(MARKETPLACE_CONTRACT)

        self.mkt_contract_address = Web3.toChecksumAddress(
            contract_url.readline().decode(
                contract_url.info().get_content_charset()).strip())

        abi_url = urllib.urlopen(MARKETPLACE_CONTRACT_ABI)
        abi_url = abi_url.read().decode(abi_url.info().get_content_charset())

        abi = json.loads(abi_url)

        self.mkt_contract = self.web3.eth.contract(
            self.mkt_contract_address,
            abi=abi,
        )

        contract_url = urllib.urlopen(ENIGMA_CONTRACT)

        self.eng_contract_address = Web3.toChecksumAddress(
            contract_url.readline().decode(
                contract_url.info().get_content_charset()).strip())

        abi_url = urllib.urlopen(ENIGMA_CONTRACT_ABI)
        abi_url = abi_url.read().decode(abi_url.info().get_content_charset())

        abi = json.loads(abi_url)

        self.eng_contract = self.web3.eth.contract(
            self.eng_contract_address,
            abi=abi,
        )
Example #2
0
def get_key_secret(pubAddr, wallet='mew'):
    """
    Obtain a new key/secret pair from authentication server

    Parameters
    ----------
    pubAddr: str
    dataset: str

    Returns
    -------
    key: str
    secret: str

    """
    session = requests.Session()
    response = session.get('{}/marketplace/getkeysecret'.format(AUTH_SERVER),
                           headers={
                            'Authorization': 'Digest username="******"'.format(
                                pubAddr)})

    if response.status_code != 401:
        raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                     error='Unexpected response code: '
                                           '{}'.format(response.status_code))

    header = response.headers.get('WWW-Authenticate')
    auth_type, auth_info = header.split(None, 1)
    d = requests.utils.parse_dict_header(auth_info)

    nonce = '0x{}'.format(d['nonce'])

    if wallet == 'mew':
        print('\nObtaining a key/secret pair to streamline all future '
              'requests with the authentication server.\n'
              'Visit https://www.myetherwallet.com/signmsg.html and sign the'
              'following message:\n{}'.format(nonce))
        signature = input('Copy and Paste the "sig" field from '
                          'the signature here (without the double quotes, '
                          'only the HEX value:\n')
    else:
        raise MarketplaceWalletNotSupported(wallet=wallet)

    if signature is None:
        raise MarketplaceEmptySignature()

    signature = signature[2:]
    r = int(signature[0:64], base=16)
    s = int(signature[64:128], base=16)
    v = int(signature[128:130], base=16)
    vrs = [v, r, s]

    response = session.get('{}/marketplace/getkeysecret'.format(AUTH_SERVER),
                           headers={
                'Authorization': 'Digest username="******",realm="{1}",'
                'nonce="{2}",uri="/marketplace/getkeysecret",response="{3}",'
                'opaque="{4}"'.format(pubAddr,
                                      d['realm'],
                                      d['nonce'],
                                      ','.join(str(e) for e in vrs+[wallet]),
                                      d['opaque'])})

    if response.status_code == 200:

        if 'error' in response.json():
            raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                         error=str(response.json()['error']))
        else:
            addresses = get_user_pubaddr()

            match = next((l for l in addresses if
                          l['pubAddr'] == pubAddr), None)
            match['key'] = response.json()['key']
            match['secret'] = response.json()['secret']

            addresses[addresses.index(match)] = match

            save_user_pubaddr(addresses)
            print('Key/secret pair retrieved successfully from server.')

            return match['key'], match['secret']

    else:
        raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                     error=response.status_code)
Example #3
0
def get_key_secret(pubAddr, wallet='mew'):
    """
    Obtain a new key/secret pair from authentication server

    Parameters
    ----------
    pubAddr: str
    dataset: str

    Returns
    -------
    key: str
    secret: str

    """
    session = requests.Session()
    response = session.get(
        '{}/marketplace/getkeysecret'.format(AUTH_SERVER),
        headers={'Authorization': 'Digest username="******"'.format(pubAddr)})

    if response.status_code != 401:
        raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                     error='Unexpected response code: '
                                     '{}'.format(response.status_code))

    header = response.headers.get('WWW-Authenticate')
    auth_type, auth_info = header.split(None, 1)
    d = requests.utils.parse_dict_header(auth_info)

    nonce = '0x{}'.format(d['nonce'])

    if wallet == 'mew':
        print('\nObtaining a key/secret pair to streamline all future '
              'requests with the authentication server.\n'
              'Visit https://www.myetherwallet.com/signmsg.html and sign the '
              'following message:\n{}'.format(nonce))
        signature = input('Copy and Paste the "sig" field from '
                          'the signature here (without the double quotes, '
                          'only the HEX value):\n')
    else:
        raise MarketplaceWalletNotSupported(wallet=wallet)

    if signature is None:
        raise MarketplaceEmptySignature()

    signature = signature[2:]
    r = int(signature[0:64], base=16)
    s = int(signature[64:128], base=16)
    v = int(signature[128:130], base=16)
    vrs = [v, r, s]

    response = session.get(
        '{}/marketplace/getkeysecret'.format(AUTH_SERVER),
        headers={
            'Authorization':
            'Digest username="******",realm="{1}",'
            'nonce="{2}",uri="/marketplace/getkeysecret",response="{3}",'
            'opaque="{4}"'.format(pubAddr, d['realm'], d['nonce'],
                                  ','.join(str(e) for e in vrs + [wallet]),
                                  d['opaque'])
        })

    if response.status_code == 200:

        if 'error' in response.json():
            raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                         error=str(response.json()['error']))
        else:
            addresses = get_user_pubaddr()

            match = next((l for l in addresses if l['pubAddr'] == pubAddr),
                         None)
            match['key'] = response.json()['key']
            match['secret'] = response.json()['secret']

            addresses[addresses.index(match)] = match

            save_user_pubaddr(addresses)
            print('Key/secret pair retrieved successfully from server.')

            return match['key'], match['secret']

    else:
        raise MarketplaceHTTPRequest(request=str('obtain key/secret'),
                                     error=response.status_code)
Example #4
0
    def __init__(self):
        global Web3
        try:
            from web3 import Web3, HTTPProvider
        except ImportError:
            raise MarketplaceRequiresPython3()

        self.addresses = get_user_pubaddr()
        if not self.addresses[0]['accepted_terms']:
            terms_and_conditions_url = urllib.urlopen(TERMS_AND_CONDITIONS)
            terms_and_conditions = terms_and_conditions_url.read()\
                .decode(terms_and_conditions_url.info().get_content_charset())
            print(terms_and_conditions)
            while True:
                accepted_terms = input('Do you accept these terms and '
                                       'conditions? [y, n] ').lower().strip()
                if accepted_terms == 'y':
                    for address in self.addresses:
                        address['accepted_terms'] = True
                    save_user_pubaddr(self.addresses)
                    print()
                    break

        if self.addresses[0]['pubAddr'] == '':
            print('We need to populate a file located at {} to be used for '
                  'future marketplace requests. \n'
                  'You shouldn\'t need to interact with this file from here '
                  'on out, but if you need to, you can go '
                  'ahead and edit this file directly.'
                  .format(os.path.join(get_marketplace_folder(),
                                       'addresses.json')))
            while True:
                pub_addr = input('What is your Ethereum public address? ')\
                    .strip()
                if pub_addr:
                    break
            desc = input('What is a description for this address (optional, '
                         'but helpful to distinguish between '
                         'multiple accounts you may be using)? ')
            while True:
                wallet = input('What wallet type are you using (strongly '
                               'recommend metamask)? [metamask, ledger, '
                               'bitbox, keystore, key] ')
                if wallet in ['metamask', 'ledger', 'bitbox', 'keystore',
                              'key']:
                    break
            self.addresses[0].update({'pubAddr': pub_addr,
                                      'desc': desc, 'wallet': wallet})
            save_user_pubaddr(self.addresses)
            print()

        self.default_account = self.addresses[0]['pubAddr']

        self.web3 = Web3(HTTPProvider(ETH_REMOTE_NODE))

        contract_url = urllib.urlopen(MARKETPLACE_CONTRACT)

        self.mkt_contract_address = Web3.toChecksumAddress(
            contract_url.readline().decode(
                contract_url.info().get_content_charset()).strip())

        abi_url = urllib.urlopen(MARKETPLACE_CONTRACT_ABI)
        abi_url = abi_url.read().decode(
            abi_url.info().get_content_charset())

        abi = json.loads(abi_url)

        self.mkt_contract = self.web3.eth.contract(
            self.mkt_contract_address,
            abi=abi,
        )

        contract_url = urllib.urlopen(ENIGMA_CONTRACT)

        self.eng_contract_address = Web3.toChecksumAddress(
            contract_url.readline().decode(
                contract_url.info().get_content_charset()).strip())

        abi_url = urllib.urlopen(ENIGMA_CONTRACT_ABI)
        abi_url = abi_url.read().decode(
            abi_url.info().get_content_charset())

        abi = json.loads(abi_url)

        self.eng_contract = self.web3.eth.contract(
            self.eng_contract_address,
            abi=abi,
        )