def create_user(username,
                email,
                mode,
                did='',
                password='',
                firstname=None,
                lastname=None,
                phone=''):

    email = email.lower()

    # Setup user address for repository
    account = mode.w3.eth.account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530' +
                                         email)
    address = account.address
    private_key = account.key.hex()

    # create RSA key as derivative from Ethereum private key
    RSA_key, RSA_private, RSA_public = privatekey.create_rsa_key(
        private_key, mode)

    # Setup a key (symetric) named 'AES' to encrypt private data and to be shared with partnership
    AES_key = get_random_bytes(16)

    # Setup another key named 'SECRET' (symetric) to encrypt secret data
    SECRET_key = get_random_bytes(16)

    # AES key encrypted with RSA key
    cipher_rsa = PKCS1_OAEP.new(RSA_key)
    AES_encrypted = cipher_rsa.encrypt(AES_key)

    # SECRET encrypted with RSA key
    cipher_rsa = PKCS1_OAEP.new(RSA_key)
    SECRET_encrypted = cipher_rsa.encrypt(SECRET_key)

    # Email encrypted with RSA Key
    bemail = bytes(email, 'utf-8')

    # Ether transfer from TalaoGen wallet
    hash = ether_transfer(address, mode.ether2transfer, mode)
    logging.info('ether transfer done')

    # Talao tokens transfer from TalaoGen wallet
    hash = token_transfer(address, mode.talao_to_transfer, mode)
    logging.info('token transfer done')

    # CreateVaultAccess call in the token to declare the identity within the Talao Token smart contract
    hash = createVaultAccess(address, private_key, mode)
    logging.info('create vault acces done')

    # Identity setup
    contract = mode.w3.eth.contract(mode.workspacefactory_contract,
                                    abi=constante.Workspace_Factory_ABI)
    nonce = mode.w3.eth.getTransactionCount(address)
    txn = contract.functions.createWorkspace(1001, 1, 1, RSA_public,
                                             AES_encrypted, SECRET_encrypted,
                                             bemail).buildTransaction({
                                                 'chainId':
                                                 mode.CHAIN_ID,
                                                 'gas':
                                                 7500000,
                                                 'gasPrice':
                                                 mode.w3.toWei(
                                                     mode.GASPRICE, 'gwei'),
                                                 'nonce':
                                                 nonce,
                                             })
    signed_txn = mode.w3.eth.account.signTransaction(txn, private_key)
    mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    transaction_hash = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction))
    if not mode.w3.eth.waitForTransactionReceipt(
            transaction_hash, timeout=2000, poll_latency=1)['status']:
        logging.error('transaction createWorkspace failed')
        return None, None, None
    logging.info('createWorkspace done')

    # workspace_contract address to be read in fondation smart contract
    workspace_contract = ownersToContracts(address, mode)
    logging.info('workspace_contract has been setup = %s', workspace_contract)

    # store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
    filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':' + workspace_contract[
        2:] + ".pem"
    try:
        file = open(filename, "wb")
        file.write(RSA_private)
        file.close()
        logging.info('RSA key stored on disk')
    except:
        logging.error('RSA key not stored on disk')

    # add username to register in local nameservice Database
    if firstname and lastname:
        filename = mode.db_path + 'person.json'
        personal = json.load(open(filename, 'r'))
        personal['lastname']['claim_value'] = lastname
        personal['firstname']['claim_value'] = firstname
        personal = json.dumps(personal, ensure_ascii=False)
    else:
        personal = ''
    if not ns.add_identity(username,
                           workspace_contract,
                           email,
                           mode,
                           phone=phone,
                           password=password,
                           did=did,
                           personal=personal):
        logging.error('add identity in nameservice.db failed')
        return None, None, None
    logging.info('add identity in nameservice.db done')

    # store Ethereum private key in keystore
    if not privatekey.add_private_key(private_key, mode):
        logging.error('add private key in keystore failed')
        return None, None, None
    else:
        logging.info('private key in keystore')

    # key 1 issued to Web Relay to act as agent.
    if not add_key(address, workspace_contract, address, workspace_contract,
                   private_key, mode.relay_address, 1, mode):
        logging.error('add key 1 to web Relay failed')
    else:
        logging.info('key 1 to web Relay has been added')

    # emails send to user and admin
    Talao_message.messageLog(lastname, firstname, username, email,
                             "createidentity.py", address, private_key,
                             workspace_contract, "", email, "", "", mode)
    # By default an email is sent to user
    Talao_message.messageUser(lastname, firstname, username, email, address,
                              private_key, workspace_contract, mode)

    logging.info('end of create identity')
    return address, private_key, workspace_contract
Ejemplo n.º 2
0
	def create(self, did, mode, email=None, password=False, phone=None, wallet=None, category=1001) :
		""" Main function to create a repository for a user
		category is 1001 for person and 2001 for company
		DID is used to generate an ethereum private key
		email is used to recover in case of did keys are lost
		Talao smart contract is deployed on talaonet
		"""
		# Setup with DID as password, deterministic way to generate an address
		if not did :
			logging.error('did malformed')
			return False
		if did.split(':')[1] not in ['web', 'tz', 'ethr', 'key'] :
			logging.error('did not supported')
			return False
		repository = Repository()
		if repository.load(mode, did) :
			logging.error('A repository already exists for this DID')
			return False
		self.did = did
		self.email = email if email else ""
		if category not in [1001, 2001] :
			logging.error('wrong category')
			return False
		self.category = category
		self.private_key = '0x' + PBKDF2(self.did.encode(), SALT, 32, count=1000000, hmac_hash_module=SHA512).hex()
		self.address = helpers.ethereum_pvk_to_address(self.private_key)
		self.public_key = helpers.ethereum_pvk_to_pub(self.private_key)
		self.jwk = helpers.ethereum_to_jwk(self.private_key, 'ethr')

		# create RSA key
		RSA_key = RSA.generate(2048)
		self.RSA_private = RSA_key.exportKey('PEM')
		self.RSA_public =  RSA_key.publickey().exportKey('PEM')
		logging.info('RSA key generated')

		# Setup an AES key named 'private' to encrypt private data and to be shared with partnership
		private = get_random_bytes(16)
		self.private = private.hex()

		# Setup an AES key named 'secret' to encrypt secret data FIXME
		secret = get_random_bytes(16)
		self.secret = secret.hex()

		# AES private encrypted with RSA key
		cipher_rsa = PKCS1_OAEP.new(RSA_key)
		private_encrypted = cipher_rsa.encrypt(private)

		# AES secret encrypted with RSA key
		cipher_rsa = PKCS1_OAEP.new(RSA_key)
		secret_encrypted = cipher_rsa.encrypt(secret)

		try :
			# Ether transfer from TalaoGen wallet
			ether_transfer(self.address, mode.ether2transfer,mode)
			logging.info('ether transfer done ')
			# Talao tokens transfer from TalaoGen wallet
			token_transfer(self.address, mode.talao_to_transfer, mode)
			logging.info('token transfer done')
			# CreateVaultAccess call in the token to declare the identity within the Talao Token smart contract
			createVaultAccess(self.address, self.private_key, mode)
			logging.info('vault access created')
		except :
			logging.error('init Talao protocol failed')
			return False

		# Identity setup
		contract = mode.w3.eth.contract(mode.workspacefactory_contract,abi=constante.Workspace_Factory_ABI)
		nonce = mode.w3.eth.getTransactionCount(self.address)
		bemail = bytes(self.email.lower() , 'utf-8')
		txn = contract.functions.createWorkspace(self.category,
												1,
												1,
												self.RSA_public,
												private_encrypted,
												secret_encrypted,
												bemail).buildTransaction({'chainId': mode.CHAIN_ID,
																			'gas': 7500000,
																			'gasPrice': mode.w3.toWei(mode.GASPRICE, 'gwei'),
																			'nonce': nonce})
		signed_txn = mode.w3.eth.account.signTransaction(txn, self.private_key)
		mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction)
		transaction_hash = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction))
		receipt = mode.w3.eth.waitForTransactionReceipt(transaction_hash, timeout=2000, poll_latency=1)
		if not receipt['status'] :
			logging.error('transaction to create repository failed')
			return False

		# workspace_contract address to be read in fondation smart contract
		self.workspace_contract = ownersToContracts(self.address, mode)
		logging.info('repository has been deployed')

		# store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
		filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':'  + self.workspace_contract[2:] + ".pem"
		try :
			file = open(filename,"wb")
			file.write( self.RSA_private)
			file.close()
			logging.info('RSA key stored on server')
		except :
			logging.error('RSA key not stored on server')
			return False

		# store Ethereum private key in keystore
		if not privatekey.add_private_key(self.private_key, mode) :
			logging.error('private key storage failed')
			return False
		else :
			logging.info('private key stored on server')

		# ERC725 key 1 issued to Web Relay as the Repository Manager
		if not add_key(self.address, self.workspace_contract, self.address, self.workspace_contract, self.private_key, mode.relay_address, 1, mode) :
			logging.error('ERC725 key 1 to repository manager failed')
			return False
		else :
			logging.error('ERC725 key 1 isued to repository manager')

		# rewrite email for recovery
		if Claim().add(self.address, self.workspace_contract, self.address, self.workspace_contract, self.private_key, 'email', self.email, 'public', mode)[0] :
			logging.info('email encryted updated')
		else :
			logging.warning('email encrypted not updated')

		logging.info('end of create repository')
		return True
Ejemplo n.º 3
0
def _create_user_step_1(wallet_address, email, mode, firstname, lastname, rsa,
                        private, secret, decentralized):
    """
	Setup an initial random Ethereum private key and derive address
	This address will be eventually the owner if the wallet is used as an Alias in the centralized mode
	"""
    account = mode.w3.eth.account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530' +
                                         email)
    address = account.address
    private_key = account.privateKey.hex()
    """
	if mode = decentralized , all keys come from wallet
	if mode = centralized , all keys are generated by server
	"""
    if decentralized:
        # clean RSA pem key received (str)
        RSA_public = rsa.encode('utf-8')
        RSA_public = RSA_public.replace(b'\r\n', b'\n')
        # get bytes from keys generated and encrypted client side. Keys have been passed (JS=>Python) un hex trsing
        AES_encrypted = bytes.fromhex(private[2:])
        SECRET_encrypted = bytes.fromhex(secret[2:])
    else:
        # create RSA key as derivative from Ethereum private key
        RSA_key, RSA_private, RSA_public = privatekey.create_rsa_key(
            private_key, mode)
        # Setup a key (symetric) named 'AES' to encrypt private data and to be shared with partnership
        AES_key = get_random_bytes(16)
        # Setup another key named 'SECRET' (symetric) to encrypt secret data
        SECRET_key = get_random_bytes(16)
        # AES key encrypted with RSA key
        cipher_rsa = PKCS1_OAEP.new(RSA_key)
        AES_encrypted = cipher_rsa.encrypt(AES_key)
        # SECRET encrypted with RSA key
        cipher_rsa = PKCS1_OAEP.new(RSA_key)
        SECRET_encrypted = cipher_rsa.encrypt(SECRET_key)

    # store Ethereum private key in keystore
    if not privatekey.add_private_key(private_key, mode):
        print('Error : add private key in keystore failed')
        return None, None, None
    else:
        print('Success : private key in keystore')

    # Email requested by solidity function. it will be encrypted later on
    #bemail = bytes(email.lower() , 'utf-8')
    bemail = bytes(" ".lower(), 'utf-8')

    # Ether transfer from TalaoGen wallet to address
    ether_transfer(address, mode.ether2transfer, mode)
    # Talao tokens transfer from TalaoGen wallet to address
    token_transfer(address, mode.talao_to_transfer, mode)
    # CreateVaultAccess call in the token to declare the identity within the Talao Token smart contract
    if not createVaultAccess(address, private_key, mode):
        print('Error : transaction createVaultAccess failed')
        return None, None, None

    # Deploy workspace contract on blockchain
    contract = mode.w3.eth.contract(mode.workspacefactory_contract,
                                    abi=constante.Workspace_Factory_ABI)
    nonce = mode.w3.eth.getTransactionCount(address)
    txn = contract.functions.createWorkspace(1001, 1, 1, RSA_public,
                                             AES_encrypted, SECRET_encrypted,
                                             bemail).buildTransaction({
                                                 'chainId':
                                                 mode.CHAIN_ID,
                                                 'gas':
                                                 7500000,
                                                 'gasPrice':
                                                 mode.w3.toWei(
                                                     mode.GASPRICE, 'gwei'),
                                                 'nonce':
                                                 nonce,
                                             })
    signed_txn = mode.w3.eth.account.signTransaction(txn, private_key)
    mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    transaction_hash = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction))
    receipt = mode.w3.eth.waitForTransactionReceipt(transaction_hash,
                                                    timeout=2000,
                                                    poll_latency=1)
    if not receipt['status']:
        print('Error : transaction createWorkspace failed')
        return None, None, None

    # workspace_contract address to be read in foundation smart contract
    workspace_contract = ownersToContracts(address, mode)
    print('Success : workspace_contract has been setup = ', workspace_contract)

    # if centralized, store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
    if not decentralized:
        filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':' + workspace_contract[
            2:] + ".pem"
        try:
            file = open(filename, "wb")
            file.write(RSA_private)
            file.close()
            print('Success : RSA key stored on disk')
        except:
            print('Error : RSA key not stored on disk')

    # add hexpublic key for wallet address
    ns.add_publickey(wallet_address, mode)

    # claims for firstname and lastname
    if firstname and lastname:
        if not update_self_claims(address, private_key, {
                'firstname': firstname,
                'lastname': lastname
        }, mode):
            print('Error : firstname and lastname not updated')
        print('Success : firstname and lastname updated')

    print("Success : create identity process step 1 is over")
    return address, private_key, workspace_contract
def create_company(email, username, did, mode, siren=None, name=None) :

	global relay_address

	# wallet init
	account = mode.w3.eth.account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
	address = account.address
	private_key = account.privateKey.hex()
	logging.info('adresse = %s', address)
	logging.info('Success : private key = %s', private_key)

	# calculate RSA key
	RSA_key, RSA_private, RSA_public = privatekey.create_rsa_key(private_key, mode)

	# création de la cle AES
	AES_key = get_random_bytes(16)
	# création de la cle SECRET
	SECRET_key = get_random_bytes(16)
	# encryption de la cle AES avec la cle RSA
	cipher_rsa = PKCS1_OAEP.new(RSA_key)
	AES_encrypted=cipher_rsa.encrypt(AES_key)
	# encryption de la cle SECRET avec la cle RSA
	cipher_rsa = PKCS1_OAEP.new(RSA_key)
	SECRET_encrypted=cipher_rsa.encrypt(SECRET_key)
	# Email to bytes
	bemail = bytes(email , 'utf-8')

	try :
		# Transaction pour le transfert des nethers depuis le portfeuille TalaoGen
		h1 = ether_transfer(address, mode.ether2transfer, mode)
		logging.info('ether transfer done')
		# Transaction pour le transfert des tokens Talao depuis le portfeuille TalaoGen
		h2 = token_transfer(address, mode.talao_to_transfer, mode)
		logging.info('token transfer done')
		# Transaction pour l'acces dans le token Talao par createVaultAccess
		h3 = createVaultAccess(address, private_key, mode)
		logging.info('create vault access done')
		# Transaction pour la creation du workspace :
		bemail = bytes(email , 'utf-8')
		h4 = createWorkspace(address, private_key, RSA_public, AES_encrypted, SECRET_encrypted, bemail, mode, user_type=2001)
		logging.info('create create workspace done')
	except :
		logging.error('transaction failed')
		return None, None, None
	if not (h1 and h2 and h3 and h4) :
		logging.error('transaction failed')
		return None, None, None

	# lecture de l'adresse du workspace contract dans la fondation
	workspace_contract = ownersToContracts(address, mode)
	logging.info( 'workspace contract = %s', workspace_contract)

	# store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum
	filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':'  + workspace_contract[2:] + ".pem"
	try :
		file = open(filename,"wb")
		file.write(RSA_private)
		file.close()
		logging.info('RSA key stored on disk')
	except :
		logging.error(' RSA key not stored on disk')

	# add private key in keystore
	if privatekey.add_private_key(private_key, mode) :
		logging.info('private key added in keystore ')
	else :
		logging.error('add private key failed')
		return None, None, None

	# update resolver and create local database for this company
	if not ns.add_identity(username, workspace_contract, email, mode, did=did) :
		logging.error('add identity in nameservice failed')
		return None, None, None

	# create database for manager within the company
	if not ns.init_host(username, mode) :
		logging.error('add company in nameservice failed')

	# For setup of new chain one need to first create workspaces for Relay and Talao
	if username != 'relay' and username != 'talao' :
		# management key (1) issued to Relay
		add_key(address, workspace_contract, address, workspace_contract, private_key, mode.relay_address, 1, mode)

	if username == 'relay' :
		# one stores relay address for Talao workspace setup
		relay_address = address
	if username == 'talao' :
		add_key(address, workspace_contract, address, workspace_contract, private_key, relay_address, 1, mode)

	# send messages
	Talao_message.messageLog("no lastname","no firstname", username, email, 'Company created by Talao', address, private_key, workspace_contract, "", email, "", "", mode)
	# one sends an email by default
	Talao_message.messageUser("no lastname", "no firstname", username, email, address, private_key, workspace_contract, mode)

	logging.info('end of of create company')
	return address, private_key, workspace_contract