Example #1
0
def wif_checksum_check(wif):

    try:
        decoded = b58decode_check(wif)
    except ValueError:
        return False

    if decoded[:1] in (MAIN_PRIVATE_KEY, TEST_PRIVATE_KEY):
        return True

    return False
Example #2
0
def construct_outputs(outputs):
    outputs_obj = []

    for data in outputs:
        dest, amount = data

        # Segwit address (Bech32)
        if amount and (dest[0:2] == 'bc' or dest[0:2] == 'tb'):
            hrp = dest[0:2]
            witver, witprog = segwit_decode(hrp, dest)

            script = segwit_scriptpubkey(witver, witprog)
            amount = amount.to_bytes(8, byteorder='little')

        # P2SH
        elif amount and (b58decode_check(dest)[0:1] == MAIN_SCRIPT_HASH
                         or b58decode_check(dest)[0:1] == TEST_SCRIPT_HASH):
            script = (OP_HASH160 + OP_PUSH_20 +
                      address_to_public_key_hash(dest) + OP_EQUAL)

            amount = amount.to_bytes(8, byteorder='little')

        # P2PKH
        elif amount:
            script = (OP_DUP + OP_HASH160 + OP_PUSH_20 +
                      address_to_public_key_hash(dest) + OP_EQUALVERIFY +
                      OP_CHECKSIG)

            amount = amount.to_bytes(8, byteorder='little')

        # Blockchain storage
        else:
            script = (OP_RETURN + len(dest).to_bytes(1, byteorder='little') +
                      dest)

            amount = b'\x00\x00\x00\x00\x00\x00\x00\x00'

        outputs_obj.append(TxOut(amount, script))

    return outputs_obj
Example #3
0
def get_version(address):
    version, _ = bech32_decode(address)
    if version is None:
        version = b58decode_check(address)[:1]
    if (version in (MAIN_PUBKEY_HASH, MAIN_SCRIPT_HASH)
            or version in BECH32_MAIN_VERSION_SET):
        return 'main'
    elif (version in (TEST_PUBKEY_HASH, TEST_SCRIPT_HASH)
          or version in BECH32_TEST_VERSION_SET):
        return 'test'
    else:
        raise ValueError('{} does not correspond to a mainnet nor '
                         'testnet address.'.format(version))
Example #4
0
File: format.py Project: xacce/bit
def get_version(address):
    segwit_versions = {'bc': MAIN_PUBKEY_HASH, 'tb': TEST_PUBKEY_HASH}
    version = segwit_versions.get(address[0:2])
    if not version:
        version = b58decode_check(address)[:1]

    if version == MAIN_PUBKEY_HASH or version == MAIN_SCRIPT_HASH:
        return 'main'
    elif version == TEST_PUBKEY_HASH or version == TEST_SCRIPT_HASH:
        return 'test'
    else:
        raise ValueError('{} does not correspond to a mainnet nor '
                         'testnet address.'.format(version))
Example #5
0
def address_to_scriptpubkey(address):
    # Raise ValueError if we cannot identify the address.
    get_version(address)
    try:
        version = b58decode_check(address)[:1]
    except ValueError:
        witver, data = segwit_decode(address)
        return segwit_scriptpubkey(witver, data)

    if version == MAIN_PUBKEY_HASH or version == TEST_PUBKEY_HASH:
        return OP_DUP + OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(
            address) + OP_EQUALVERIFY + OP_CHECKSIG
    elif version == MAIN_SCRIPT_HASH or version == TEST_SCRIPT_HASH:
        return OP_HASH160 + OP_PUSH_20 + address_to_public_key_hash(
            address) + OP_EQUAL
Example #6
0
def wif_to_hex(wif):

    private_key = b58decode_check(wif)

    version = private_key[:1]

    if version == MAIN_PRIVATE_KEY:
        version = 'main'
    elif version == TEST_PRIVATE_KEY:
        version = 'test'
    else:
        raise ValueError('{} does not correspond to a mainnet nor '
                         'testnet address.'.format(private_key[:1]))

    # Remove version byte and, if present, compression flag.
    if len(wif) == 52 and private_key[-1] == 1:
        private_key, compressed = private_key[1:-1], True
    else:
        private_key, compressed = private_key[1:], False

    return bytes_to_hex(private_key), compressed, version
Example #7
0
def address_to_public_key_hash(address):
    return b58decode_check(address)[1:]
Example #8
0
def address_to_public_key_hash(address):
    # Raise ValueError if we cannot identify the address.
    get_version(address)
    return b58decode_check(address)[1:]
Example #9
0
def proccess_create_or_modify_user_request(attribute_dict,
                                           organisation=None,
                                           allow_existing_user_modify=False,
                                           is_self_sign_up=False,
                                           modify_only=False):
    """
    Takes a create or modify user request and determines the response. Normally what's in the top level API function,
    but here it's one layer down because there's multiple entry points for 'create user':
    - The admin api
    - The register api

    :param attribute_dict: attributes that can be supplied by the request maker
    :param organisation:  what organisation the request maker belongs to. The created user is bound to the same org
    :param allow_existing_user_modify: whether to return an error when the user already exists for the supplied IDs
    :param is_self_sign_up: does the request come from the register api?
    :param modify_only: whether to allow the creation of a  new user
    :return: An http response
    """

    if not attribute_dict.get('custom_attributes'):
        attribute_dict['custom_attributes'] = {}

    user_id = attribute_dict.get('user_id')

    email = attribute_dict.get('email')
    phone = attribute_dict.get('phone')

    account_types = attribute_dict.get('account_types', [])
    if isinstance(account_types, str):
        account_types = account_types.split(',')

    referred_by = attribute_dict.get('referred_by')

    blockchain_address = attribute_dict.get('blockchain_address')

    provided_public_serial_number = attribute_dict.get('public_serial_number')

    uuid = attribute_dict.get('uuid')

    require_identifier = attribute_dict.get('require_identifier', True)

    if not user_id:
        # Extract ID from Combined User ID and Name String if it exists
        try:
            user_id_name_string = attribute_dict.get('user_id_name_string')

            user_id_str = user_id_name_string and user_id_name_string.split(
                ':')[0]

            if user_id_str:
                user_id = int(user_id_str)

        except SyntaxError:
            pass

    if not blockchain_address and provided_public_serial_number:

        try:
            blockchain_address = to_checksum_address(
                provided_public_serial_number)

            # Since it's actually an ethereum address set the provided public serial number to None
            # so it doesn't get used as a transfer card
            provided_public_serial_number = None
        except Exception:
            pass

    require_transfer_card_exists = attribute_dict.get(
        'require_transfer_card_exists',
        g.active_organisation.require_transfer_card)

    public_serial_number = (provided_public_serial_number
                            or attribute_dict.get('payment_card_qr_code')
                            or attribute_dict.get('payment_card_barcode'))

    location = attribute_dict.get('location')  # address location

    # Yes, we know "GPS" refers to a technology, but "gps_location" is less ambiguous for end users than "geo_location"
    gps_location = attribute_dict.get(
        'gps_location')  # geo location as str of lat, lng

    use_precreated_pin = attribute_dict.get('use_precreated_pin')
    use_last_4_digits_of_id_as_initial_pin = attribute_dict.get(
        'use_last_4_digits_of_id_as_initial_pin')

    transfer_account_name = attribute_dict.get('transfer_account_name')
    first_name = attribute_dict.get('first_name')
    last_name = attribute_dict.get('last_name')

    business_usage_name = attribute_dict.get('business_usage_name')
    business_usage_id = None
    if business_usage_name:
        usage = TransferUsage.find_or_create(business_usage_name)
        business_usage_id = usage.id

    preferred_language = attribute_dict.get('preferred_language')

    primary_user_identifier = attribute_dict.get('primary_user_identifier')
    primary_user_pin = attribute_dict.get('primary_user_pin')

    initial_disbursement = attribute_dict.get('initial_disbursement', None)
    if not account_types:
        account_types = ['beneficiary']
    roles_to_set = []
    for at in account_types:
        if at not in g.active_organisation.valid_roles:
            raise Exception(
                f'{at} not a valid role for this organisation. Please choose one of the following: {g.active_organisation.valid_roles}'
            )
        roles_to_set.append((ASSIGNABLE_TIERS[at], at))

    chain = get_chain()
    if current_app.config['CHAINS'][chain]['IS_USING_BITCOIN']:
        try:
            base58.b58decode_check(blockchain_address)
        except ValueError:
            response_object = {
                'message':
                'Blockchain Address {} Not Valid'.format(blockchain_address)
            }
            return response_object, 400

    if isinstance(phone, bool):
        phone = None

    if phone and not is_self_sign_up:
        # phone has already been parsed if self sign up
        try:
            phone = proccess_phone_number(phone)
        except NumberParseException as e:
            response_object = {'message': 'Invalid Phone Number: ' + str(e)}
            return response_object, 400

    # Work out if there's an existing transfer account to bind to
    existing_transfer_account = None
    if primary_user_identifier:
        primary_user, _ = find_user_from_public_identifier(
            primary_user_identifier)

        if not primary_user or not primary_user.verify_password(
                primary_user_pin):
            response_object = {'message': 'Primary User not Found'}
            return response_object, 400

        if not primary_user.verify_password(primary_user_pin):
            response_object = {'message': 'Invalid PIN for Primary User'}
            return response_object, 400

        primary_user_transfer_account = primary_user.transfer_account

        if not primary_user_transfer_account:
            response_object = {
                'message': 'Primary User has no transfer account'
            }
            return response_object, 400

    if not (phone or email or public_serial_number or blockchain_address
            or user_id or uuid or not require_identifier):
        response_object = {'message': 'Must provide a unique identifier'}
        return response_object, 400

    if use_precreated_pin and not public_serial_number:
        response_object = {
            'message':
            'Must provide public serial number to use a transfer card or pre-created pin'
        }
        return response_object, 400

    if public_serial_number:
        public_serial_number = str(public_serial_number)

        if use_precreated_pin or require_transfer_card_exists:
            transfer_card = TransferCard.query.filter_by(
                public_serial_number=public_serial_number).first()

            if not transfer_card:
                response_object = {'message': 'Transfer card not found'}
                return response_object, 400

    business_usage = None
    if business_usage_id:
        business_usage = TransferUsage.query.get(business_usage_id)
        if not business_usage:
            response_object = {
                'message':
                f'Business Usage not found for id {business_usage_id}'
            }
            return response_object, 400

    referred_by_user, _ = find_user_from_public_identifier(referred_by)

    if referred_by and not referred_by_user:
        response_object = {
            'message':
            f'Referrer user not found for public identifier {referred_by}'
        }
        return response_object, 400

    existing_user, _ = find_user_from_public_identifier(
        email, phone, public_serial_number, blockchain_address, uuid)

    if not existing_user and user_id:
        existing_user = User.query.get(user_id)

    if modify_only and existing_user is None:
        response_object = {'message': 'User not found'}
        return response_object, 404

    if existing_user:
        if not allow_existing_user_modify:
            response_object = {'message': 'User already exists for Identifier'}
            return response_object, 400

        try:

            user = update_transfer_account_user(
                existing_user,
                first_name=first_name,
                last_name=last_name,
                preferred_language=preferred_language,
                phone=phone,
                email=email,
                public_serial_number=public_serial_number,
                use_precreated_pin=use_precreated_pin,
                existing_transfer_account=existing_transfer_account,
                roles=roles_to_set,
                business_usage=business_usage)

            set_location_conditionally(user, location, gps_location)

            if referred_by_user:
                user.referred_by.clear(
                )  # otherwise prior referrals will remain...
                user.referred_by.append(referred_by_user)

            set_custom_attributes(attribute_dict, user)
            flag_modified(user, "custom_attributes")

            db.session.commit()

            response_object = {
                'message': 'User Updated',
                'data': {
                    'user': user_schema.dump(user).data
                }
            }

            return response_object, 200

        except Exception as e:
            response_object = {'message': str(e)}

            return response_object, 400

    user = create_transfer_account_user(
        first_name=first_name,
        last_name=last_name,
        preferred_language=preferred_language,
        phone=phone,
        email=email,
        public_serial_number=public_serial_number,
        uuid=uuid,
        organisation=organisation,
        blockchain_address=blockchain_address,
        transfer_account_name=transfer_account_name,
        use_precreated_pin=use_precreated_pin,
        use_last_4_digits_of_id_as_initial_pin=
        use_last_4_digits_of_id_as_initial_pin,
        existing_transfer_account=existing_transfer_account,
        roles=roles_to_set,
        is_self_sign_up=is_self_sign_up,
        business_usage=business_usage,
        initial_disbursement=initial_disbursement)

    set_location_conditionally(user, location, gps_location)

    if referred_by_user:
        user.referred_by.append(referred_by_user)

    if attribute_dict.get('gender'):
        attribute_dict['custom_attributes']['gender'] = attribute_dict.get(
            'gender')

    if attribute_dict.get('bio'):
        attribute_dict['custom_attributes']['bio'] = attribute_dict.get('bio')

    set_custom_attributes(attribute_dict, user)

    if is_self_sign_up and attribute_dict.get('deviceInfo', None) is not None:
        save_device_info(device_info=attribute_dict.get('deviceInfo'),
                         user=user)
    send_onboarding_sms_messages(user)
    # Location fires an async task that needs to know user ID
    db.session.flush()

    if phone:
        if is_self_sign_up:
            send_one_time_code(phone=phone, user=user)
            return {
                'message': 'User Created. Please verify phone number.',
                'otp_verify': True
            }, 200

        elif current_app.config['ONBOARDING_SMS']:
            try:
                send_onboarding_sms_messages(user)
            except Exception as e:
                print(e)
                sentry_sdk.capture_exception(e)
                pass

    response_object = {
        'message': 'User Created',
        'data': {
            'user': user_schema.dump(user).data
        }
    }

    return response_object, 200
Example #10
0
def get_version(address, coin=Bitcoin):
    version = b58decode_check(address)[:1]

    if version == coin.MAIN_PUBKEY_HASH:
        return 'main'
Example #11
0
def proccess_create_or_modify_user_request(
    attribute_dict,
    organisation=None,
    allow_existing_user_modify=False,
    is_self_sign_up=False,
    modify_only=False,
):
    """
    Takes a create or modify user request and determines the response. Normally what's in the top level API function,
    but here it's one layer down because there's multiple entry points for 'create user':
    - The admin api
    - The register api

    :param attribute_dict: attributes that can be supplied by the request maker
    :param organisation:  what organisation the request maker belongs to. The created user is bound to the same org
    :param allow_existing_user_modify: whether to return and error when the user already exists for the supplied IDs
    :param is_self_sign_up: does the request come from the register api?
    :return: An http response
    """

    if not attribute_dict.get('custom_attributes'):
        attribute_dict['custom_attributes'] = {}

    user_id = attribute_dict.get('user_id')

    email = attribute_dict.get('email')
    phone = attribute_dict.get('phone')

    referred_by = attribute_dict.get('referred_by')

    blockchain_address = attribute_dict.get('blockchain_address')

    provided_public_serial_number = attribute_dict.get('public_serial_number')

    if not blockchain_address and provided_public_serial_number:

        try:
            blockchain_address = to_checksum_address(
                provided_public_serial_number)

            # Since it's actually an ethereum address set the provided public serial number to None
            # so it doesn't get used as a transfer card
            provided_public_serial_number = None
        except Exception:
            pass

    require_transfer_card_exists = attribute_dict.get(
        'require_transfer_card_exists',
        g.active_organisation.require_transfer_card)

    public_serial_number = (provided_public_serial_number
                            or attribute_dict.get('payment_card_qr_code')
                            or attribute_dict.get('payment_card_barcode'))

    location = attribute_dict.get('location')  # address location
    geo_location = attribute_dict.get(
        'geo_location')  # geo location as str of lat, lng

    if geo_location:
        geo = geo_location.split(' ')
        lat = geo[0]
        lng = geo[1]
    else:
        # TODO: Work out how this passed tests when this wasn't definied properly!?!
        lat = None
        lng = None

    use_precreated_pin = attribute_dict.get('use_precreated_pin')
    use_last_4_digits_of_id_as_initial_pin = attribute_dict.get(
        'use_last_4_digits_of_id_as_initial_pin')

    transfer_account_name = attribute_dict.get('transfer_account_name')
    first_name = attribute_dict.get('first_name')
    last_name = attribute_dict.get('last_name')

    business_usage_name = attribute_dict.get('business_usage_name')
    business_usage_id = None
    if business_usage_name:
        usage = TransferUsage.find_or_create(business_usage_name)
        business_usage_id = usage.id

    preferred_language = attribute_dict.get('preferred_language')

    primary_user_identifier = attribute_dict.get('primary_user_identifier')
    primary_user_pin = attribute_dict.get('primary_user_pin')

    initial_disbursement = attribute_dict.get('initial_disbursement', None)

    is_vendor = attribute_dict.get('is_vendor', None)
    if is_vendor is None:
        is_vendor = attribute_dict.get('vendor', False)

    is_tokenagent = attribute_dict.get('is_tokenagent', False)
    is_groupaccount = attribute_dict.get('is_groupaccount', False)

    # is_beneficiary defaults to the opposite of is_vendor
    is_beneficiary = attribute_dict.get(
        'is_beneficiary', not is_vendor and not is_tokenagent
        and not is_groupaccount)

    if current_app.config['IS_USING_BITCOIN']:
        try:
            base58.b58decode_check(blockchain_address)
        except ValueError:
            response_object = {
                'message':
                'Blockchain Address {} Not Valid'.format(blockchain_address)
            }
            return response_object, 400

    if isinstance(phone, bool):
        phone = None

    if phone and not is_self_sign_up:
        # phone has already been parsed if self sign up
        try:
            phone = proccess_phone_number(phone)
        except NumberParseException as e:
            response_object = {'message': 'Invalid Phone Number: ' + str(e)}
            return response_object, 400

    # Work out if there's an existing transfer account to bind to
    existing_transfer_account = None
    if primary_user_identifier:
        primary_user = find_user_from_public_identifier(
            primary_user_identifier)

        if not primary_user or not primary_user.verify_password(
                primary_user_pin):
            response_object = {'message': 'Primary User not Found'}
            return response_object, 400

        if not primary_user.verify_password(primary_user_pin):
            response_object = {'message': 'Invalid PIN for Primary User'}
            return response_object, 400

        primary_user_transfer_account = primary_user.transfer_account

        if not primary_user_transfer_account:
            response_object = {
                'message': 'Primary User has no transfer account'
            }
            return response_object, 400

    if not (phone or email or public_serial_number or blockchain_address):
        response_object = {'message': 'Must provide a unique identifier'}
        return response_object, 400

    if use_precreated_pin and not public_serial_number:
        response_object = {
            'message':
            'Must provide public serial number to use a transfer card or pre-created pin'
        }
        return response_object, 400

    if public_serial_number:
        public_serial_number = str(public_serial_number)

        if use_precreated_pin or require_transfer_card_exists:
            transfer_card = TransferCard.query.filter_by(
                public_serial_number=public_serial_number).first()

            if not transfer_card:
                response_object = {'message': 'Transfer card not found'}
                return response_object, 400

    business_usage = None
    if business_usage_id:
        business_usage = TransferUsage.query.get(business_usage_id)
        if not business_usage:
            response_object = {
                'message':
                f'Business Usage not found for id {business_usage_id}'
            }
            return response_object, 400

    referred_by_user = find_user_from_public_identifier(referred_by)

    if referred_by and not referred_by_user:
        response_object = {
            'message':
            f'Referrer user not found for public identifier {referred_by}'
        }
        return response_object, 400

    existing_user = find_user_from_public_identifier(email, phone,
                                                     public_serial_number,
                                                     blockchain_address)

    if modify_only:
        existing_user = User.query.get(user_id)

    if modify_only and existing_user is None:
        response_object = {'message': 'User not found'}
        return response_object, 404

    if existing_user:
        if not allow_existing_user_modify:
            response_object = {'message': 'User already exists for Identifier'}
            return response_object, 400

        try:

            user = update_transfer_account_user(
                existing_user,
                first_name=first_name,
                last_name=last_name,
                preferred_language=preferred_language,
                phone=phone,
                email=email,
                location=location,
                public_serial_number=public_serial_number,
                use_precreated_pin=use_precreated_pin,
                existing_transfer_account=existing_transfer_account,
                is_beneficiary=is_beneficiary,
                is_vendor=is_vendor,
                is_tokenagent=is_tokenagent,
                is_groupaccount=is_groupaccount,
                business_usage=business_usage)

            if referred_by_user:
                user.referred_by.clear(
                )  # otherwise prior referrals will remain...
                user.referred_by.append(referred_by_user)

            set_custom_attributes(attribute_dict, user)
            flag_modified(user, "custom_attributes")

            db.session.commit()

            response_object = {
                'message': 'User Updated',
                'data': {
                    'user': user_schema.dump(user).data
                }
            }

            return response_object, 200

        except Exception as e:
            response_object = {'message': str(e)}

            return response_object, 400

    user = create_transfer_account_user(
        first_name=first_name,
        last_name=last_name,
        preferred_language=preferred_language,
        phone=phone,
        email=email,
        public_serial_number=public_serial_number,
        organisation=organisation,
        blockchain_address=blockchain_address,
        transfer_account_name=transfer_account_name,
        lat=lat,
        lng=lng,
        use_precreated_pin=use_precreated_pin,
        use_last_4_digits_of_id_as_initial_pin=
        use_last_4_digits_of_id_as_initial_pin,
        existing_transfer_account=existing_transfer_account,
        is_beneficiary=is_beneficiary,
        is_vendor=is_vendor,
        is_tokenagent=is_tokenagent,
        is_groupaccount=is_groupaccount,
        is_self_sign_up=is_self_sign_up,
        business_usage=business_usage,
        initial_disbursement=initial_disbursement)

    if referred_by_user:
        user.referred_by.append(referred_by_user)

    if attribute_dict.get('gender'):
        attribute_dict['custom_attributes']['gender'] = attribute_dict.get(
            'gender')

    if attribute_dict.get('bio'):
        attribute_dict['custom_attributes']['bio'] = attribute_dict.get('bio')

    set_custom_attributes(attribute_dict, user)

    if is_self_sign_up and attribute_dict.get('deviceInfo', None) is not None:
        save_device_info(device_info=attribute_dict.get('deviceInfo'),
                         user=user)
    send_onboarding_sms_messages(user)
    # Location fires an async task that needs to know user ID
    db.session.flush()

    if location:
        user.location = location

    if phone:
        if is_self_sign_up:
            send_one_time_code(phone=phone, user=user)
            return {
                'message': 'User Created. Please verify phone number.',
                'otp_verify': True
            }, 200

        elif current_app.config['ONBOARDING_SMS']:
            try:
                send_onboarding_sms_messages(user)
            except Exception as e:
                print(e)
                sentry_sdk.capture_exception(e)
                pass

    response_object = {
        'message': 'User Created',
        'data': {
            'user': user_schema.dump(user).data
        }
    }

    return response_object, 200
Example #12
0
 def test_b58decode_check_failure(self):
     with pytest.raises(ValueError):
         b58decode_check(BITCOIN_ADDRESS[:-1])
Example #13
0
 def test_b58decode_check_success(self):
     assert b58decode_check(
         BITCOIN_ADDRESS) == MAIN_PUBKEY_HASH + PUBKEY_HASH
Example #14
0
def proccess_attribute_dict(attribute_dict,
                            force_dict_keys_lowercase=False,
                            allow_existing_user_modify=False,
                            require_transfer_card_exists=False):
    elapsed_time('1.0 Start')

    if force_dict_keys_lowercase:
        attribute_dict = force_attribute_dict_keys_to_lowercase(attribute_dict)

    attribute_dict = strip_kobo_preslashes(attribute_dict)

    attribute_dict = apply_settings(attribute_dict)

    attribute_dict = truthy_all_dict_values(attribute_dict)

    attribute_dict = strip_whitespace_characters(attribute_dict)

    elapsed_time('2.0 Post Processing')

    email = attribute_dict.get('email')
    phone = attribute_dict.get('phone')

    blockchain_address = attribute_dict.get('blockchain_address')

    provided_public_serial_number = attribute_dict.get('public_serial_number')

    if not blockchain_address and provided_public_serial_number:

        try:
            blockchain_address = utils.checksum_encode(
                provided_public_serial_number)

            # Since it's actually an ethereum address set the provided public serial number to None
            # so it doesn't get used as a transfer card
            provided_public_serial_number = None
        except Exception:
            pass

    public_serial_number = (provided_public_serial_number
                            or attribute_dict.get('payment_card_qr_code')
                            or attribute_dict.get('payment_card_barcode'))

    location = attribute_dict.get('location')

    use_precreated_pin = attribute_dict.get('use_precreated_pin')
    use_last_4_digits_of_id_as_initial_pin = attribute_dict.get(
        'use_last_4_digits_of_id_as_initial_pin')

    transfer_account_name = attribute_dict.get('transfer_account_name')
    first_name = attribute_dict.get('first_name')
    last_name = attribute_dict.get('last_name')

    primary_user_identifier = attribute_dict.get('primary_user_identifier')
    primary_user_pin = attribute_dict.get('primary_user_pin')

    custom_initial_disbursement = attribute_dict.get(
        'custom_initial_disbursement', None)

    is_vendor = attribute_dict.get('is_vendor', None)
    if is_vendor is None:
        is_vendor = attribute_dict.get('vendor', False)

    # is_beneficiary defaults to the opposite of is_vendor
    is_beneficiary = attribute_dict.get('is_beneficiary', not is_vendor)

    if current_app.config['IS_USING_BITCOIN']:
        try:
            base58.b58decode_check(blockchain_address)
        except ValueError:
            response_object = {
                'message':
                'Blockchain Address {} Not Valid'.format(blockchain_address)
            }
            return response_object, 400

    if isinstance(phone, bool):
        phone = None

    if phone:
        try:
            phone = proccess_phone_number(phone)
        except NumberParseException as e:
            response_object = {'message': 'Invalid Phone Number: ' + str(e)}
            return response_object, 400

    # Work out if there's an existing transfer account to bind to
    existing_transfer_account = None
    if primary_user_identifier:

        primary_user = find_user_from_public_identifier(
            primary_user_identifier)

        if not primary_user or not primary_user.verify_password(
                primary_user_pin):
            response_object = {'message': 'Primary User not Found'}
            return response_object, 400

        if not primary_user.verify_password(primary_user_pin):

            response_object = {'message': 'Invalid PIN for Primary User'}
            return response_object, 400

        primary_user_transfer_account = primary_user.transfer_account

        if not primary_user_transfer_account:
            response_object = {
                'message': 'Primary User has no transfer account'
            }
            return response_object, 400

    if not (phone or email or public_serial_number or blockchain_address):
        response_object = {'message': 'Must provide a unique identifier'}
        return response_object, 400

    if use_precreated_pin and not public_serial_number:
        response_object = {
            'message':
            'Must provide public serial number to use a transfer card or pre-created pin'
        }
        return response_object, 400

    if public_serial_number:
        public_serial_number = str(public_serial_number)

        if use_precreated_pin or require_transfer_card_exists:
            transfer_card = models.TransferCard.query.filter_by(
                public_serial_number=public_serial_number).first()

            if not transfer_card:
                response_object = {'message': 'Transfer card not found'}
                return response_object, 400

    if custom_initial_disbursement and not custom_initial_disbursement <= current_app.config[
            'MAXIMUM_CUSTOM_INITIAL_DISBURSEMENT']:
        response_object = {
            'message':
            'Disbursement more than maximum allowed amount ({} {})'.format(
                current_app.config['MAXIMUM_CUSTOM_INITIAL_DISBURSEMENT'] /
                100, current_app.config['CURRENCY_NAME'])
        }
        return response_object, 400

    existing_user = find_user_from_public_identifier(email, phone,
                                                     public_serial_number,
                                                     blockchain_address)
    if existing_user:

        if not allow_existing_user_modify:
            response_object = {'message': 'User already exists for Identifier'}
            return response_object, 400

        user = update_transfer_account_user(
            existing_user,
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            email=email,
            public_serial_number=public_serial_number,
            use_precreated_pin=use_precreated_pin,
            existing_transfer_account=existing_transfer_account,
            is_beneficiary=is_beneficiary,
            is_vendor=is_vendor)

        default_attributes, custom_attributes = set_custom_attributes(
            attribute_dict, user)
        flag_modified(user, "custom_attributes")

        db.session.commit()

        response_object = {
            'message': 'User Updated',
            'data': {
                'user': user_schema.dump(user).data
            }
        }

        return response_object, 200

    elapsed_time('3.0 Ready to create')

    user = create_transfer_account_user(
        first_name=first_name,
        last_name=last_name,
        phone=phone,
        email=email,
        public_serial_number=public_serial_number,
        blockchain_address=blockchain_address,
        transfer_account_name=transfer_account_name,
        location=location,
        use_precreated_pin=use_precreated_pin,
        use_last_4_digits_of_id_as_initial_pin=
        use_last_4_digits_of_id_as_initial_pin,
        existing_transfer_account=existing_transfer_account,
        is_beneficiary=is_beneficiary,
        is_vendor=is_vendor)

    elapsed_time('4.0 Created')

    default_attributes, custom_attributes = set_custom_attributes(
        attribute_dict, user)

    if custom_initial_disbursement:
        try:
            disbursement = CreditTransferUtils.make_disbursement_transfer(
                custom_initial_disbursement, user)
        except Exception as e:
            response_object = {'message': str(e)}
            return response_object, 400

    elapsed_time('5.0 Disbursement done')

    db.session.flush()

    if location:
        user.location = location

    if phone and current_app.config['ONBOARDING_SMS']:
        try:
            balance = user.transfer_account.balance
            if isinstance(balance, int):
                balance = balance / 100

            send_onboarding_message(first_name=user.first_name,
                                    to_phone=phone,
                                    credits=balance,
                                    one_time_code=user.one_time_code)
        except Exception as e:
            print(e)
            pass

    if user.one_time_code:
        response_object = {
            'message': 'User Created',
            'data': {
                'user': user_schema.dump(user).data
            }
        }

    else:
        response_object = {
            'message': 'User Created',
            'data': {
                'user': user_schema.dump(user).data
            }
        }

    elapsed_time('6.0 Complete')

    return response_object, 200