Example #1
0
def test_submit_txn_when_both_ready(monkeypatch):
    user = OneUser.run(db_session,
                       account_amount=100_000_000_000,
                       account_currency=currency)
    amount = 10_000_000_000
    receiver = LocalAccount.generate()
    subaddress = identifier.gen_subaddress()
    txn = save_outbound_transaction(user.account_id, receiver.account_address,
                                    subaddress, amount, currency)
    cmd = _txn_payment_command(txn)
    receiver_cmd = dataclasses.replace(
        cmd, my_actor_address=cmd.payment.receiver.address)
    receiver_ready_cmd = receiver_cmd.new_command(
        recipient_signature=b"recipient_signature".hex(),
        status=offchain.Status.ready_for_settlement,
        kyc_data=_user_kyc_data(user.account_id),
    )

    with monkeypatch.context() as m:
        client = context.get().offchain_client
        m.setattr(
            client,
            "process_inbound_request",
            lambda _, c: client.create_inbound_payment_command(
                c.cid, c.payment),
        )
        code, resp = process_inbound_command(cmd.payment.receiver.address,
                                             receiver_ready_cmd)
        assert code == 200
        assert resp
    txn = get_transaction_by_reference_id(cmd.reference_id())
    assert txn
    assert txn.status == TransactionStatus.OFF_CHAIN_INBOUND

    cmd = _txn_payment_command(txn)
    assert cmd.is_inbound(), str(cmd)

    process_offchain_tasks()
    db_session.refresh(txn)
    assert txn.status == TransactionStatus.OFF_CHAIN_READY

    # sync command and submit
    with monkeypatch.context() as m:
        m.setattr(
            context.get().offchain_client,
            "send_command",
            lambda cmd, _: offchain.reply_request(cmd.cid),
        )
        m.setattr(
            context.get(),
            "p2p_by_travel_rule",
            jsonrpc_txn_sample,
        )
        process_offchain_tasks()

    db_session.refresh(txn)
    assert txn.status == TransactionStatus.COMPLETED
    assert txn.sequence == 5
    assert txn.blockchain_version == 3232
Example #2
0
def get_deposit_address(account_id: Optional[int] = None,
                        account_name: Optional[str] = None):
    account = get_account(account_id=account_id, account_name=account_name)
    subaddress = generate_new_subaddress(account.id)

    return identifier.encode_account(
        context.get().config.vasp_account_address(),
        subaddress,
        context.get().config.diem_address_hrp(),
    )
Example #3
0
def submit_onchain(transaction_id: int) -> None:
    transaction = get_transaction(transaction_id)
    if transaction.status == TransactionStatus.PENDING:
        try:
            diem_currency = DiemCurrency[transaction.currency]

            if transaction.type == TransactionType.EXTERNAL:
                jsonrpc_txn = context.get().p2p_by_general(
                    currency=diem_currency.value,
                    amount=transaction.amount,
                    receiver_vasp_address=transaction.destination_address,
                    receiver_sub_address=transaction.destination_subaddress,
                    sender_sub_address=transaction.source_subaddress,
                )

                update_transaction(
                    transaction_id=transaction_id,
                    status=TransactionStatus.COMPLETED,
                    sequence=jsonrpc_txn.transaction.sequence_number,
                    blockchain_tx_version=jsonrpc_txn.version,
                )
                add_transaction_log(
                    transaction_id,
                    "On Chain Transfer of General Txn Complete")
                log_execution("On chain transfer complete "
                              f"txid: {transaction_id} "
                              f"v: {jsonrpc_txn.version} ")

            if transaction.type == TransactionType.REFUND:
                original_txn_version = get_transaction(
                    transaction.original_txn_id).blockchain_version
                jsonrpc_txn = context.get().p2p_by_refund(
                    currency=diem_currency.value,
                    amount=transaction.amount,
                    receiver_vasp_address=transaction.destination_address,
                    original_txn_version=original_txn_version,
                )
                update_transaction(
                    transaction_id=transaction_id,
                    status=TransactionStatus.COMPLETED,
                    sequence=jsonrpc_txn.transaction.sequence_number,
                    blockchain_tx_version=jsonrpc_txn.version,
                )
                add_transaction_log(
                    transaction_id, "On Chain Transfer of Refund Txn Complete")
                log_execution("On chain transfer complete "
                              f"txid: {transaction_id} "
                              f"v: {jsonrpc_txn.version} ")

        except Exception:
            logger.exception(f"Error in _async_start_onchain_transfer")
            add_transaction_log(transaction_id, "On Chain Transfer Failed")
            log_execution("On Chain Transfer Failed")
            update_transaction(transaction_id=transaction_id,
                               status=TransactionStatus.CANCELED)
Example #4
0
    def get_transaction_response_object(
            cls, account_id: int, transaction: Transaction) -> Dict[str, str]:
        direction = get_transaction_direction(account_id=account_id,
                                              transaction=transaction)

        blockchain_tx = None

        if transaction.type == TransactionType.EXTERNAL:
            blockchain_tx = {
                "amount": transaction.amount,
                "source": transaction.source_address,
                "destination": transaction.destination_address,
                "expirationTime": "",
                "sequenceNumber": transaction.sequence,
                "status": transaction.status,
                "version": transaction.blockchain_version,
            }

        return {
            "id": transaction.id,
            "amount": transaction.amount,
            "currency": transaction.currency,
            "direction": direction.value.lower(),
            "status": transaction.status,
            "timestamp": transaction.created_timestamp.isoformat(),
            "source": {
                "vasp_name":
                transaction.source_address,
                "user_id":
                transaction.source_subaddress,
                "full_addr":
                identifier.encode_account(
                    transaction.source_address,
                    transaction.source_subaddress,
                    context.get().config.diem_address_hrp(),
                ),
            },
            "destination": {
                "vasp_name":
                transaction.destination_address,
                "user_id":
                transaction.destination_subaddress,
                "full_addr":
                identifier.encode_account(
                    transaction.destination_address,
                    transaction.destination_subaddress,
                    context.get().config.diem_address_hrp(),
                ),
            },
            "is_internal": transaction.type == TransactionType.INTERNAL,
            "blockchain_tx": blockchain_tx,
        }
Example #5
0
def show_context(request, path):
	document_root = contrib.get_document_root(path)
	fullpath = contrib.get_full_path(document_root, path)
	log.debug('show context of %s (%s %s)' % (fullpath, document_root, path))

	result = ""

	sections = config.sections(context.get(fullpath).inifile)
	for section_name in sections:
		ctx = context.get(fullpath, section=section_name)
		context_ini = context.render_ini(path, ctx, request.get_host(), section_name)
		result += context_ini

	return HttpResponse(result)
Example #6
0
def test_process_inbound_command(monkeypatch):
    hrp = context.get().config.diem_address_hrp()
    user = OneUser.run(db_session,
                       account_amount=100_000_000_000,
                       account_currency=currency)
    amount = 10_000_000_000
    sender = LocalAccount.generate()
    sender_subaddress = identifier.gen_subaddress()
    receiver_subaddress = generate_new_subaddress(user.account_id)
    cmd = offchain.PaymentCommand.init(
        identifier.encode_account(sender.account_address, sender_subaddress,
                                  hrp),
        _user_kyc_data(user.account_id),
        identifier.encode_account(context.get().config.vasp_address,
                                  receiver_subaddress, hrp),
        amount,
        currency.value,
    )

    with monkeypatch.context() as m:
        client = context.get().offchain_client
        m.setattr(
            client,
            "process_inbound_request",
            lambda _, cmd: client.create_inbound_payment_command(
                cmd.cid, cmd.payment),
        )
        code, resp = process_inbound_command(cmd.payment.sender.address, cmd)
        assert code == 200
        assert resp

    txn = get_transaction_by_reference_id(cmd.reference_id())
    assert txn
    assert txn.status == TransactionStatus.OFF_CHAIN_INBOUND

    cmd = _txn_payment_command(txn)
    assert cmd.is_inbound(), str(cmd)

    with monkeypatch.context() as m:
        m.setattr(
            context.get().offchain_client,
            "send_command",
            lambda cmd, _: offchain.reply_request(cmd.cid),
        )
        process_offchain_tasks()

        db_session.refresh(txn)
        assert txn.status == TransactionStatus.OFF_CHAIN_OUTBOUND
Example #7
0
def runTest(request, fullpath):
	path = contrib.normpath(request.REQUEST["path"])
	context_name = request.REQUEST.get("context", None)
	ctx = context.get(fullpath, section=context_name)

	log.info('run test %s with context %s' % (path, context_name))
	server = request.get_host()
	contextjs = context.render(path, ctx, server)
	log.debug('contextJS: '+ contextjs)

	clean_path = contrib.get_relative_clean_path(path)
	target = contrib.get_runner_url(ctx, server)
	log.info('target of test %s is %s' % (clean_path, target))

	tools.savetest(request.REQUEST.get('content', None), fullpath)
	test_content = request.REQUEST.get("content", open(fullpath, 'r').read())

	#if contrib.target_is_remote( target, server):
	#	log.debug('TARGET: %s, %s' % ( target, server ))
	#	url = "http://%s/%s" % (target, settings.UPLOAD_TESTS_CMD)
	#	saveRemoteContext(os.path.dirname(clean_path), contextjs, url, ctx)
	#	distributor.saveTestSatelliteScripts(url, path, ctx)
	#	distributor.sendContentToRemote(clean_path, test_content, url, ctx)
	#	url = "http://%s/%s?path=/%s" % (target, settings.EXEC_TESTS_CMD, clean_path)
	#else:
	#	saveLocalContext(fullpath, contextjs)
	#	url = "http://%s/%s?path=/%s" % (target, settings.EXEC_TESTS_CMD, clean_path)
	saveLocalContext(fullpath, contextjs)
	if coffee(path):
		path = coffeescript.compile(test_content, path, fullpath)
	url = "http://%s/%s?server=%s&path=/%s" % (target, settings.EXEC_TESTS_CMD, server, path)
	log.info("redirect to run test %s" % url)
	return HttpResponseRedirect(url)
Example #8
0
def runSuite(request, fullpath):
	path = contrib.normpath(request.REQUEST["path"])
	context_name = request.REQUEST["context"]
	ctx = context.get(fullpath, section=context_name)

	log.info('run suite %s with context %s' % (path, context_name))
	server = request.get_host();
	compileSuiteCoffee(path, fullpath)
	contextjs = context.render(path, ctx, server)

	clean_path = contrib.get_relative_clean_path(path)
	target = contrib.get_runner_url(ctx, server)
	log.info('target of suite %s is %s' % (clean_path, target))

	#if contrib.target_is_remote( target, server):
	#	url = "http://%s/%s" % (target, settings.UPLOAD_TESTS_CMD)
	#	saveRemoteContext(clean_path, contextjs, url, ctx)
	#	distributor.saveSuiteAllTests(url, path, ctx)
	#	distributor.saveTestSatelliteScripts(url, path, ctx)
	#	url = "http://%s/%s?suite=/%s" % ( target, settings.EXEC_TESTS_CMD, clean_path )
	#else:
	#	saveLocalContext(fullpath, contextjs)
	#	url = "http://%s/%s?suite=/%s" % ( target, settings.EXEC_TESTS_CMD, clean_path )

	saveLocalContext(fullpath, contextjs)
	url = "http://%s/%s?server=%s&path=/%s" % ( target, settings.EXEC_TESTS_CMD, server, path )
	log.info("redirect to run suite %s" % url)
	return HttpResponseRedirect( url )
Example #9
0
def save_outbound_transaction(
    sender_id: int,
    destination_address: str,
    destination_subaddress: str,
    amount: int,
    currency: DiemCurrency,
) -> Transaction:
    sender_onchain_address = context.get().config.vasp_address
    sender_subaddress = account.generate_new_subaddress(account_id=sender_id)
    return commit_transaction(
        _new_payment_command_transaction(
            offchain.PaymentCommand.init(
                identifier.encode_account(
                    sender_onchain_address, sender_subaddress, _hrp()
                ),
                _user_kyc_data(sender_id),
                identifier.encode_account(
                    destination_address, destination_subaddress, _hrp()
                ),
                amount,
                currency.value,
            ),
            TransactionStatus.OFF_CHAIN_OUTBOUND,
        )
    )
Example #10
0
        def post(self):
            try:
                tx_params = request.json

                user = self.user
                account_id = user.account_id

                currency = DiemCurrency[tx_params["currency"]]
                amount = int(tx_params["amount"])
                recv_address: str = tx_params["receiver_address"]
                dest_address, dest_subaddress = identifier.decode_account(
                    recv_address,
                    context.get().config.diem_address_hrp())

                tx = transaction_service.send_transaction(
                    sender_id=account_id,
                    amount=amount,
                    currency=currency,
                    destination_address=utils.account_address_bytes(
                        dest_address).hex(),
                    destination_subaddress=dest_subaddress.hex()
                    if dest_subaddress else None,
                )
                transaction = AccountRoutes.get_transaction_response_object(
                    user.account_id, tx)
                return transaction, HTTPStatus.OK
            except transaction_service.RiskCheckError as risk_check_failed_error:
                return self.respond_with_error(HTTPStatus.FAILED_DEPENDENCY,
                                               str(risk_check_failed_error))
            except transaction_service.SelfAsDestinationError as send_to_self_error:
                return self.respond_with_error(HTTPStatus.FORBIDDEN,
                                               str(send_to_self_error))
Example #11
0
def send_fake_tx(amount=100, send_to_self=False) -> Tuple[int, Transaction]:
    user = OneUser.run(db_session,
                       account_amount=100_000_000_000,
                       account_currency=DiemCurrency.XUS)
    account_id = user.account_id
    amount = amount
    payment_type = types.TransactionType.EXTERNAL
    currency = diem_utils.types.currencies.DiemCurrency.XUS
    destination_address = "receiver_address"
    destination_subaddress = "receiver_subaddress"

    if send_to_self:
        destination_address = account_address_hex(
            context.get().config.vasp_address)
        destination_subaddress = generate_new_subaddress(account_id)

    send_tx = send_transaction(
        sender_id=account_id,
        amount=amount,
        currency=currency,
        payment_type=payment_type,
        destination_address=destination_address,
        destination_subaddress=destination_subaddress,
    )

    return account_id, get_transaction(send_tx.id) if send_tx else None
Example #12
0
def submit_onchain(transaction_id: int) -> None:
    transaction = get_transaction(transaction_id)
    if transaction.status == TransactionStatus.PENDING:
        try:
            diem_currency = DiemCurrency[transaction.currency]

            jsonrpc_txn = context.get().p2p_by_general(
                currency=diem_currency.value,
                amount=transaction.amount,
                receiver_vasp_address=transaction.destination_address,
                receiver_sub_address=transaction.destination_subaddress,
                sender_sub_address=transaction.source_subaddress,
            )

            update_transaction(
                transaction_id=transaction_id,
                status=TransactionStatus.COMPLETED,
                sequence=jsonrpc_txn.transaction.sequence_number,
                blockchain_tx_version=jsonrpc_txn.version,
            )
            add_transaction_log(transaction_id, "On Chain Transfer Complete")
            log_execution("On Chain Transfer Complete")
        except Exception:
            logger.exception(f"Error in _async_start_onchain_transfer")
            add_transaction_log(transaction_id, "On Chain Transfer Failed")
            log_execution("On Chain Transfer Failed")
            update_transaction(transaction_id=transaction_id,
                               status=TransactionStatus.CANCELED)
Example #13
0
def enumerate_suites(request):
	"""
	Return a list of suite names.
	Arguments:
		ctx	(optional)	- filter suites containing supplied ctx name
		json 	(optional)	- return result in JSON format
	"""
	ctx_name = request.REQUEST.get('context', None)
	as_json = request.REQUEST.get('json', False)
	target = request.REQUEST.get('target', False)

	suites = []
	root = contrib.get_document_root(target)
	contextini = settings.TEST_CONTEXT_FILE_NAME

	for dirpath, dirnames, filenames in os.walk(root, followlinks=True):
		if not ( contextini in filenames ):
			continue
		if ctx_name:
			contextfile = os.path.join(dirpath, contextini)
			ctx = context.get(contextfile)
			ctx_sections = ctx.sections()
			if not ctx_name in ctx_sections:
				continue

			suites += [ dirpath.replace(root, '').replace('\\','/').lstrip('/') ]

	if as_json:
		return HttpResponse(json.dumps(suites))
	return HttpResponse(str(suites).replace('[','').replace(']','').rstrip(',').replace('\'',''))
Example #14
0
def get_dir_index(document_root, path, fullpath):
	files = []
	dirs = []

	def get_descriptor(title):
		fullpath = os.path.join(path, title)
		return { 'title': title, 'type': tools.get_type(contrib.get_full_path(document_root, fullpath)) }

	if not document_root:
		pagetype = 'front-page'
		for key in contrib.get_virtual_paths():
			dir_descriptor = get_descriptor(key)
			dirs.append(dir_descriptor)
	else:
		pagetype = tools.get_type(fullpath)
		for f in sorted(os.listdir(fullpath)):
			if not f.startswith('.'):
				if os.path.isfile(os.path.join(fullpath, f)):
					files.append(get_descriptor(f))
				else:
					f += '/'
					dirs.append(get_descriptor(f))

	try:
		if tools.get_type(fullpath) == 'virtual':
			contexts = context.global_settings(fullpath).sections()
		else:
			contexts = context.get(fullpath).sections()
		log.debug(contexts)
	except Exception, e:
		log.error(e)
		contexts = []
Example #15
0
def main():
    import json
    import context

    ctx = context.get()
    t = list(totals(ctx))
    t.sort(key=lambda c: c["receipts"], reverse=True)
    print(json.dumps(t, indent=4))
Example #16
0
def external_transaction(
    sender_id: int,
    receiver_address: str,
    receiver_subaddress: str,
    amount: int,
    currency: DiemCurrency,
    payment_type: TransactionType,
    original_txn_id: int,
) -> Transaction:
    logger.info(
        f"external_transaction {sender_id} to receiver {receiver_address}, "
        f"receiver subaddress {receiver_subaddress}, amount {amount}")
    if not validate_balance(sender_id, amount, currency):
        raise BalanceError(
            f"Balance {account_service.get_account_balance_by_id(account_id=sender_id).total[currency]} "
            f"is less than amount needed {amount}")

    sender_onchain_address = context.get().config.vasp_address

    sender_subaddress = None
    if (payment_type == TransactionType.EXTERNAL
            or payment_type == TransactionType.REFUND):
        sender_subaddress = account_service.generate_new_subaddress(
            account_id=sender_id)

    transaction = add_transaction(
        amount=amount,
        currency=currency,
        payment_type=payment_type,
        status=TransactionStatus.PENDING,
        source_id=sender_id,
        source_address=sender_onchain_address,
        source_subaddress=sender_subaddress,
        destination_id=None,
        destination_address=receiver_address,
        destination_subaddress=receiver_subaddress,
        original_txn_id=original_txn_id,
    )

    if services.run_bg_tasks():
        from ..background_tasks.background import async_external_transaction

        async_external_transaction.send(transaction.id)
    else:
        submit_onchain(transaction_id=transaction.id)

    return transaction
Example #17
0
def runSuite(request, fullpath):
	path = contrib.normpath(request.REQUEST["path"])
	context_name = request.REQUEST["context"]
	ctx = context.get(fullpath, section=context_name)

	log.info('run suite %s with context %s' % (path, context_name))
	server = request.get_host();
	compileSuiteCoffee(path, fullpath)
	contextjs = context.render(path, ctx, server, context_name)

	clean_path = contrib.get_relative_clean_path(path)
	target = contrib.get_runner_url(ctx, server)
	log.info('target of suite %s is %s' % (clean_path, target))

	saveLocalContext(fullpath, contextjs)
	url = "http://%s/%s?server=%s&path=/%s" % ( target, settings.EXEC_TESTS_CMD, server, path )
	log.info("redirect to run suite %s" % url)
	return HttpResponseRedirect( url )
Example #18
0
 def submit_txn(txn, cmd, _) -> Transaction:
     if cmd.is_sender():
         logger.info(
             f"Submitting transaction ID:{txn.id} {txn.amount} {txn.currency}"
         )
         _offchain_client().send_command(cmd, _compliance_private_key().sign)
         rpc_txn = context.get().p2p_by_travel_rule(
             cmd.receiver_account_address(_hrp()),
             cmd.payment.action.currency,
             cmd.payment.action.amount,
             cmd.travel_rule_metadata(_hrp()),
             bytes.fromhex(cmd.payment.recipient_signature),
         )
         txn.sequence = rpc_txn.transaction.sequence_number
         txn.blockchain_version = rpc_txn.version
         txn.status = TransactionStatus.COMPLETED
         logger.info(
             f"Submitted transaction ID:{txn.id} V:{txn.blockchain_version} {txn.amount} {txn.currency}"
         )
Example #19
0
def body(parsed: Parsed, body_line: Line) -> Parsed:
    '''put body in context wrt head => parse

    create a "context" from the head and the body (given the parser that parsed the head). put the body into that context with formatting and parse it.
    '''
    head_parser = parsed.parser
    definition = config.parsers[head_parser]
    body_parser = definition['body']
    parse = parsers[body_parser]

    #HACK force body comment to be parsed (not joined with head)
    if re.search(config.parsers['comment']['regex'], body_line):
        return parsers['comment'](body_line)

    head_line = parsed.head
    holes = context.get(head_parser, head_line, body_line)
    line = holes % escape(body_line)
    line = Line(line, lineno=body_line.lineno, file=body_line.file)

    return parse(line)
Example #20
0
def settle_offchain(transaction_id: int) -> None:
    transaction = get_transaction(transaction_id)
    logger.info(f"settle_offchain: {transaction_id}, "
                f"{transaction.status}, "
                f"{transaction.type}")
    if (transaction.status == TransactionStatus.READY_FOR_ON_CHAIN
            and transaction.type == TransactionType.OFFCHAIN):
        try:
            diem_currency = DiemCurrency[transaction.currency]
            logger.info(
                f"==============starting submit_onchain {diem_currency}, {transaction.amount}, "
                f"{transaction.destination_address}, {transaction.destination_subaddress}, "
                f"{transaction.source_subaddress}")
            reference_id = get_reference_id_from_transaction_id(transaction_id)
            jsonrpc_txn = context.get().p2p_by_travel_rule(
                currency=diem_currency.value,
                amount=transaction.amount,
                receiver_vasp_address=transaction.destination_address,
                off_chain_reference_id=reference_id,
                metadata_signature=bytes.fromhex(
                    get_metadata_signature_from_reference_id(reference_id)),
            )

            update_transaction(
                transaction_id=transaction_id,
                status=TransactionStatus.COMPLETED,
                sequence=jsonrpc_txn.transaction.sequence_number,
                blockchain_tx_version=jsonrpc_txn.version,
            )

            add_transaction_log(transaction_id, "On Chain Transfer Complete")
            log_execution("On Chain Transfer Complete")
        except Exception as e:
            logger.exception(f"Error in settle_offchain: {e}")
            add_transaction_log(transaction_id, "Off Chain Settlement Failed")
            log_execution("Off Chain Settlement Failed")
            update_transaction(transaction_id=transaction_id,
                               status=TransactionStatus.CANCELED)
Example #21
0
def internal_transaction(
    sender_id: int,
    receiver_id: int,
    amount: int,
    currency: DiemCurrency,
    payment_type: TransactionType,
) -> Transaction:
    """Transfer transaction between accounts in the LRW internal ledger."""

    log_execution("Enter internal_transaction")

    if not validate_balance(sender_id, amount, currency):
        raise BalanceError(
            f"Balance {account_service.get_account_balance_by_id(account_id=sender_id).total[currency]} "
            f"is less than amount needed {amount}")

    sender_subaddress = account_service.generate_new_subaddress(sender_id)
    receiver_subaddress = account_service.generate_new_subaddress(receiver_id)
    internal_vasp_address = context.get().config.vasp_address

    transaction = add_transaction(
        amount=amount,
        currency=currency,
        payment_type=payment_type,
        status=TransactionStatus.COMPLETED,
        source_id=sender_id,
        source_address=internal_vasp_address,
        source_subaddress=sender_subaddress,
        destination_id=receiver_id,
        destination_address=internal_vasp_address,
        destination_subaddress=receiver_subaddress,
    )

    log_execution(
        f"Transfer from {sender_id} to {receiver_id} started with transaction id {transaction.id}"
    )
    add_transaction_log(transaction.id, "Transfer completed")
    return transaction
Example #22
0
def runTest(request, fullpath):
	path = contrib.normpath(request.REQUEST["path"])
	context_name = request.REQUEST.get("context", None)
	ctx = context.get(fullpath, section=context_name)

	log.info('run test %s with context %s' % (path, context_name))
	server = request.get_host()
	contextjs = context.render(path, ctx, server, context_name)
	log.debug('contextJS: '+ contextjs)

	clean_path = contrib.get_relative_clean_path(path)
	target = contrib.get_runner_url(ctx, server)
	log.info('target of test %s is %s' % (clean_path, target))

	tools.savetest(request.REQUEST.get('content', None), fullpath)
	test_content = request.REQUEST.get("content", open(fullpath, 'r').read())
	
	saveLocalContext(fullpath, contextjs)
	if coffee(path):
		path = coffeescript.compile2js(test_content, path, fullpath)
	url = "http://%s/%s?server=%s&path=/%s" % (target, settings.EXEC_TESTS_CMD, server, path)
	log.info("redirect to run test %s" % url)
	return HttpResponseRedirect(url)
Example #23
0
def _cover_buy(order: Order, quote: QuoteData) -> bool:
    deposit_address = get_inventory_deposit_address()
    trade_id = LpClient().trade_and_execute(
        quote_id=quote.quote_id,
        direction=Direction[order.direction],
        diem_deposit_address=deposit_address,
    )
    trade_info = _wait_for_trade(order=order, trade_id=trade_id)

    if not trade_info:
        update_order(
            order_id=OrderId(UUID(order.id)),
            cover_status=CoverStatus.FailedCoverLPTradeError,
        )
        return False

    update_order(
        order_id=OrderId(UUID(order.id)),
        cover_status=CoverStatus.PendingCoverValidation,
    )

    vasp_address, internal_subaddress = decode_account(
        deposit_address, context.get().config.diem_address_hrp()
    )
    if not _validate_blockchain_transaction(
        blockchain_version=trade_info.tx_version,
        vasp_address=utils.account_address_hex(vasp_address),
        internal_subaddress=internal_subaddress.hex(),
        amount=round(trade_info.amount),
    ):
        update_order(
            order_id=OrderId(UUID(order.id)),
            cover_status=CoverStatus.FailedCoverTransactionError,
        )
        return False

    return True
Example #24
0
def test_save_outbound_transaction(monkeypatch):
    user = OneUser.run(db_session,
                       account_amount=100_000_000_000,
                       account_currency=currency)
    amount = 10_000_000_000
    receiver = LocalAccount.generate()
    subaddress = identifier.gen_subaddress()
    txn = save_outbound_transaction(user.account_id, receiver.account_address,
                                    subaddress, amount, currency)

    assert txn.id in get_account_transaction_ids(user.account_id)
    assert txn.reference_id is not None
    assert txn.command_json is not None

    with monkeypatch.context() as m:
        m.setattr(
            context.get().offchain_client,
            "send_command",
            lambda cmd, _: offchain.reply_request(cmd.cid),
        )
        process_offchain_tasks()

        db_session.refresh(txn)
        assert txn.status == TransactionStatus.OFF_CHAIN_WAIT
def test_get_set():
    ctx = context.from_env()
    context.set(ctx)
    assert context.get() == ctx
Example #26
0
def is_own_address(sender_id, receiver_vasp, receiver_subaddress) -> bool:
    return (receiver_vasp == context.get().config.vasp_address
            and get_account_id_from_subaddr(receiver_subaddress) == sender_id)
Example #27
0
def is_in_wallet(receiver_subaddress, receiver_vasp) -> bool:
    return (get_account_id_from_subaddr(receiver_subaddress) is not None
            and receiver_vasp == context.get().config.vasp_address)
Example #28
0
def _hrp() -> str:
    return context.get().config.diem_address_hrp()
Example #29
0
def _compliance_private_key() -> Ed25519PrivateKey:
    return context.get().config.compliance_private_key()
Example #30
0
def _account_address_and_subaddress(
        account_id: str) -> Tuple[str, Optional[str]]:
    account_address, sub = identifier.decode_account(
        account_id,
        context.get().config.diem_address_hrp())
    return (account_address.to_hex(), sub.hex() if sub else None)
Example #31
0
 def execute(self, context=None):
     '''
     Lookup of symbol values will start in the closest scope layer and proceed outward
     from there. Throws an exception if the symbol is not found in this context.
     '''
     return context.get(self.symbol).execute(context)
Example #32
0
def get_new_offchain_reference_id(sender_address_hex: str) -> str:
    address = LibraAddress.from_hex(context.get().config.diem_address_hrp(),
                                    sender_address_hex, None)
    id = uuid.uuid1().hex
    return f"{address.as_str()}_{id}"
Example #33
0
    print("2. Determine Best Options")
    print("3. Quit")
    print("")

    text = input("Please Enter Something : ")

    int_value = int(text)

    print("You entered " + str(int_value))

    if int_value == 1:
        print("")
        print("")
        lst = []
        cnt = int(0)
        for x in context.get():
            if not isinstance(x, ibodypart.IBodyPart):
                raise Exception('Bad interface')
            lst.append(x)
            print(str(cnt) + ' -- ' + x.name())
            cnt = cnt + 1
        print("")
        text = input("Enter Which One : ")
        sel = int(text)
        lst[sel].setDate(datetime.date.today())
        print("Date Set")

    if int_value == 2:
        print("")
        print("")
        for x in context.get():
Example #34
0
def _init_offchain():
    vasp = offchain_service.make_vasp(context.get())
    offchain_service.launch(vasp)
    offchain_client.set(vasp)
Example #35
0
def get_file_content_to_edit(path, fullpath, stubbed):
	try:
		contexts = context.get( fullpath ).sections()
	except Exception, e:
		log.exception(e)
		contexts = []
Example #36
0
def external_offchain_transaction(
    sender_id: int,
    receiver_address: str,
    receiver_subaddress: str,
    amount: int,
    currency: DiemCurrency,
    payment_type: TransactionType,
    original_payment_reference_id: Optional[str] = None,
    description: Optional[str] = None,
) -> Transaction:

    sender_onchain_address = context.get().config.vasp_address
    logger.info(
        f"=================Start external_offchain_transaction "
        f"{sender_onchain_address}, {sender_id}, {receiver_address}, {receiver_subaddress}, "
        f"{amount}, {currency}, {payment_type}")
    if not validate_balance(sender_id, amount, currency):
        raise BalanceError(
            f"Balance {account_service.get_account_balance_by_id(account_id=sender_id).total[currency]} "
            f"is less than amount needed {amount}")

    sender_subaddress = account_service.generate_new_subaddress(
        account_id=sender_id)
    logger.info(f"======sender_subaddress: {sender_subaddress}")
    ref_id = get_new_offchain_reference_id(sender_onchain_address)
    transaction = add_transaction(
        amount=amount,
        currency=currency,
        payment_type=payment_type,
        status=TransactionStatus.PENDING,
        source_id=sender_id,
        source_address=sender_onchain_address,
        source_subaddress=sender_subaddress,
        destination_id=None,
        destination_address=receiver_address,
        destination_subaddress=receiver_subaddress,
        reference_id=ref_id,
    )

    # off-chain logic
    sender_address = LibraAddress.from_bytes(
        context.get().config.diem_address_hrp(),
        bytes.fromhex(sender_onchain_address),
        bytes.fromhex(sender_subaddress),
    )
    logger.info(
        f"sender address: {sender_onchain_address}, {sender_address.as_str()}, {sender_address.get_onchain().as_str()}"
    )
    receiver_address = LibraAddress.from_bytes(
        context.get().config.diem_address_hrp(),
        bytes.fromhex(receiver_address),
        bytes.fromhex(receiver_subaddress),
    )
    logger.info(
        f"receiver address: {receiver_address.as_str()}, {receiver_address.get_onchain().as_str()}",
    )
    sender = PaymentActor(
        sender_address.as_str(),
        StatusObject(Status.needs_kyc_data),
        [],
    )
    receiver = PaymentActor(receiver_address.as_str(),
                            StatusObject(Status.none), [])
    action = PaymentAction(amount, currency, "charge", int(time()))
    reference_id = get_reference_id_from_transaction_id(transaction.id)
    payment = PaymentObject(
        sender=sender,
        receiver=receiver,
        reference_id=reference_id,
        original_payment_reference_id=original_payment_reference_id,
        description=description,
        action=action,
    )
    cmd = PaymentCommand(payment)

    if not get_transaction_status(transaction.id) == TransactionStatus.PENDING:
        logger.info(
            "In external_offchain_transaction, payment status is not PENDING, abort"
        )
        return

    update_transaction(transaction.id, TransactionStatus.OFF_CHAIN_STARTED)
    logger.info(
        "In external_offchain_transaction: Updated status to OFF_CHAIN_STARTED"
    )

    result = (offchain_client.get().new_command(receiver_address.get_onchain(),
                                                cmd).result(timeout=300))
    logger.info(f"Offchain Result: {result}")

    return transaction
Example #37
0
def _offchain_client() -> offchain.Client:
    return context.get().offchain_client
Example #38
0
def getRegistry(r):
    if r is None:
        return context.get(AdapterRegistry, theAdapterRegistry)
    else:
        return r