def post(account: str, request: Request, **kwargs): if kwargs: return render_error_response( _("POST requests should not specify subresources in the URI")) elif not registered_sep31_receiver_integration.valid_sending_anchor( account): return render_error_response("invalid sending account", status_code=403) try: params = validate_post_request(request) except ValueError as e: return render_error_response(str(e)) # validate fields separately since error responses need different format missing_fields = validate_post_fields(params.get("fields"), params.get("asset"), params.get("lang")) if missing_fields: return Response( { "error": "transaction_info_needed", "fields": missing_fields }, status=400, ) transaction_id = create_transaction_id() # create memo transaction_id_hex = transaction_id.hex padded_hex_memo = "0" * (64 - len(transaction_id_hex)) + transaction_id_hex transaction_memo = memo_hex_to_base64(padded_hex_memo) # create transaction object without saving to the DB transaction = Transaction( id=transaction_id, protocol=Transaction.PROTOCOL.sep31, kind=Transaction.KIND.send, status=Transaction.STATUS.pending_sender, stellar_account=account, asset=params["asset"], amount_in=params["amount"], memo=transaction_memo, memo_type=Transaction.MEMO_TYPES.hash, receiving_anchor_account=params["asset"].distribution_account, ) error_data = registered_sep31_receiver_integration.process_post_request( params, transaction) try: response_data = process_post_response(error_data, transaction) except ValueError as e: logger.error(str(e)) return render_error_response(_("unable to process the request"), status_code=500) else: transaction.save() return Response(response_data, status=400 if "error" in response_data else 200)
def test_memo_str_hash_memo(): raw_bytes = token_bytes(32) memo_str = utils.memo_hex_to_base64(raw_bytes.hex()) assert utils.memo_str(HashMemo(raw_bytes)) == ( memo_str, Transaction.MEMO_TYPES.hash, )
def withdraw( account: str, client_domain: Optional[str], request: Request, ) -> Response: args = parse_request_args(request) if "error" in args: return args["error"] args["account"] = account transaction_id = create_transaction_id() transaction_id_hex = transaction_id.hex padded_hex_memo = "0" * (64 - len(transaction_id_hex)) + transaction_id_hex transaction_memo = memo_hex_to_base64(padded_hex_memo) transaction = Transaction( id=transaction_id, stellar_account=account, asset=args["asset"], kind=Transaction.KIND.withdrawal, status=Transaction.STATUS.pending_user_transfer_start, receiving_anchor_account=args["asset"].distribution_account, memo=transaction_memo, memo_type=Transaction.MEMO_TYPES.hash, protocol=Transaction.PROTOCOL.sep6, more_info_url=request.build_absolute_uri( f"{SEP6_MORE_INFO_PATH}?id={transaction_id}"), on_change_callback=args["on_change_callback"], client_domain=client_domain, ) # All request arguments are validated in parse_request_args() # except 'type', 'dest', and 'dest_extra'. Since Polaris doesn't know # which argument was invalid, the anchor is responsible for raising # an exception with a translated message. try: integration_response = rwi.process_sep6_request(args, transaction) except ValueError as e: return render_error_response(str(e)) try: response, status_code = validate_response(args, integration_response, transaction) except ValueError as e: logger.error(str(e)) return render_error_response(_("unable to process the request"), status_code=500) if status_code == 200: response["memo"] = transaction.memo response["memo_type"] = transaction.memo_type logger.info(f"Created withdraw transaction {transaction.id}") transaction.save() elif Transaction.objects.filter(id=transaction.id).exists(): logger.error( "Do not save transaction objects for invalid SEP-6 requests") return render_error_response(_("unable to process the request"), status_code=500) return Response(response, status=status_code)
def post_interactive_withdraw(request: Request) -> Response: """ POST /transactions/withdraw/webapp This endpoint processes form submissions during the withdraw interactive flow. The following steps are taken during this process: 1. URL arguments are parsed and validated. 2. form_for_transaction() is called to retrieve the form used to submit this request. This function is implemented by the anchor. 3. The form is used to validate the data submitted, and if the form is a TransactionForm, the fee for the transaction is calculated. 4. after_form_validation() is called to allow the anchor to process the data submitted. This function should change the application state such that the next call to form_for_transaction() returns the next form in the flow. 5. form_for_transaction() is called again to retrieve the next form to be served to the user. If a form is returned, the function redirects to GET /transaction/withdraw/webapp. Otherwise, The user's session is invalidated, the transaction status is updated, and the function redirects to GET /more_info. """ args_or_error = interactive_args_validation(request) if "error" in args_or_error: return args_or_error["error"] transaction = args_or_error["transaction"] asset = args_or_error["asset"] callback = args_or_error["callback"] amount = args_or_error["amount"] form = rwi.form_for_transaction(transaction, post_data=request.data) if not form: logger.error("Initial form_for_transaction() call returned None " f"for {transaction.id}") if transaction.status != transaction.STATUS.incomplete: return render_error_response( _("The anchor did not provide content, is the interactive flow already complete?" ), status_code=422, content_type="text/html", ) return render_error_response( _("The anchor did not provide content, unable to serve page."), status_code=500, content_type="text/html", ) if not form.is_bound: # The anchor must initialize the form with request.data logger.error( "form returned was not initialized with POST data, returning 500") return render_error_response( _("Unable to validate form submission."), status_code=500, content_type="text/html", ) elif form.is_valid(): if issubclass(form.__class__, TransactionForm): transaction.amount_in = form.cleaned_data["amount"] transaction.save() rwi.after_form_validation(form, transaction) next_form = rwi.form_for_transaction(transaction) if next_form or rwi.content_for_template( Template.WITHDRAW, form=next_form, transaction=transaction): args = {"transaction_id": transaction.id, "asset_code": asset.code} if amount: args["amount"] = amount if callback: args["callback"] = callback url = reverse("get_interactive_withdraw") return redirect(f"{url}?{urlencode(args)}") else: # Last form has been submitted logger.info( f"Finished data collection and processing for transaction {transaction.id}" ) invalidate_session(request) # Add memo now that interactive flow is complete # # We use the transaction ID as a memo on the Stellar transaction for the # payment in the withdrawal. This lets us identify that as uniquely # corresponding to this `Transaction` in the database. But a UUID4 is a 32 # character hex string, while the Stellar HashMemo requires a 64 character # hex-encoded (32 byte) string. So, we zero-pad the ID to create an # appropriately sized string for the `HashMemo`. transaction_id_hex = transaction.id.hex padded_hex_memo = "0" * ( 64 - len(transaction_id_hex)) + transaction_id_hex transaction.memo = memo_hex_to_base64(padded_hex_memo) # Update status # This signals to the wallet that the transaction can be submitted transaction.status = Transaction.STATUS.pending_user_transfer_start transaction.save() url = reverse("more_info") args = urlencode({"id": transaction.id, "callback": callback}) return redirect(f"{url}?{args}") else: content = (rwi.content_for_template( Template.WITHDRAW, form=form, transaction=transaction) or {}) if registered_scripts_func is not scripts: logger.warning( "DEPRECATED: the `scripts` Polaris integration function will be " "removed in Polaris 2.0 in favor of allowing the anchor to override " "and extend Polaris' Django templates. See the Template Extensions " "documentation for more information.") template_scripts = registered_scripts_func({"form": form, **content}) url_args = {"transaction_id": transaction.id, "asset_code": asset.code} if callback: url_args["callback"] = callback if amount: url_args["amount"] = amount toml_data = registered_toml_func() post_url = f"{reverse('post_interactive_withdraw')}?{urlencode(url_args)}" get_url = f"{reverse('get_interactive_withdraw')}?{urlencode(url_args)}" content.update( form=form, post_url=post_url, get_url=get_url, scripts=template_scripts, operation=settings.OPERATION_WITHDRAWAL, asset=asset, use_fee_endpoint=registered_fee_func != calculate_fee, org_logo_url=toml_data.get("DOCUMENTATION", {}).get("ORG_LOGO"), ) return Response(content, template_name="polaris/withdraw.html", status=422)