Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SealedTx feature #695

Merged
merged 1 commit into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@
share,
token_holders,
)
from app.routers.misc import bc_explorer, e2e_messaging, freeze_log, settlement_agent
from app.routers.misc import (
bc_explorer,
e2e_messaging,
freeze_log,
sealed_tx,
settlement_agent,
)
from app.utils.docs_utils import custom_openapi
from config import (
BC_EXPLORER_ENABLED,
Expand All @@ -70,6 +76,10 @@
"name": "[misc] messaging",
"description": "Messaging functions with external systems",
},
{
"name": "[misc] sealed_tx",
"description": "Sealed transaction",
},
]

if DVP_AGENT_FEATURE_ENABLED:
Expand Down Expand Up @@ -136,6 +146,7 @@ async def root():
app.include_router(share.router)
app.include_router(token_holders.router)
app.include_router(settlement_issuer.router)
app.include_router(sealed_tx.router)

if DVP_AGENT_FEATURE_ENABLED:
app.include_router(settlement_agent.router)
Expand Down
1 change: 1 addition & 0 deletions app/model/schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
ScheduledEventIdResponse,
ScheduledEventResponse,
)
from .sealed_tx import SealedTxRegisterPersonalInfoRequest
from .settlement import (
AbortDVPDeliveryRequest,
CancelDVPDeliveryRequest,
Expand Down
42 changes: 42 additions & 0 deletions app/model/schema/sealed_tx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
Copyright BOOSTRY Co., Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache-2.0
"""

from pydantic import BaseModel

from app.model import EthereumAddress
from app.model.schema.personal_info import PersonalInfoInput


############################
# REQUEST
############################
class SealedTxPersonalInfoInput(PersonalInfoInput):
"""Personal Information Input schema for sealed tx"""

key_manager: str


############################
# REQUEST
############################
class SealedTxRegisterPersonalInfoRequest(BaseModel):
"""Schema for personal information registration using sealed tx(REQUEST)"""

link_address: EthereumAddress
personal_information: SealedTxPersonalInfoInput
82 changes: 82 additions & 0 deletions app/routers/misc/sealed_tx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
Copyright BOOSTRY Co., Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache-2.0
"""

import json

from fastapi import APIRouter
from starlette.requests import Request

from app.database import DBAsyncSession
from app.model.db import (
IDXPersonalInfo,
IDXPersonalInfoHistory,
PersonalInfoDataSource,
PersonalInfoEventType,
)
from app.model.schema import SealedTxRegisterPersonalInfoRequest
from app.utils.docs_utils import get_routers_responses
from app.utils.sealedtx_utils import (
RawRequestBody,
SealedTxSignatureHeader,
VerifySealedTxSignature,
)

router = APIRouter(prefix="/sealed_tx", tags=["[misc] sealed_tx"])


# POST: /personal_info/register
@router.post(
"/personal_info/register",
operation_id="SealedTxRegisterPersonalInfo",
response_model=None,
responses=get_routers_responses(400),
)
async def sealed_tx_register_personal_info(
db: DBAsyncSession,
raw_request_body: RawRequestBody,
request: Request,
sealed_tx_sig: SealedTxSignatureHeader,
register_data: SealedTxRegisterPersonalInfoRequest,
):
# Verify sealed tx signature
account_address = VerifySealedTxSignature(
req=request, body=json.loads(raw_request_body.decode()), signature=sealed_tx_sig
)

# Insert offchain personal information
# NOTE: Overwrite if a record for the same account already exists.
personal_info = register_data.personal_information.model_dump()
_off_personal_info = IDXPersonalInfo()
_off_personal_info.issuer_address = register_data.link_address
_off_personal_info.account_address = account_address
_off_personal_info.personal_info = personal_info
_off_personal_info.data_source = PersonalInfoDataSource.OFF_CHAIN
await db.merge(_off_personal_info)

# Insert personal information history
_personal_info_history = IDXPersonalInfoHistory()
_personal_info_history.issuer_address = register_data.link_address
_personal_info_history.account_address = account_address
_personal_info_history.event_type = PersonalInfoEventType.REGISTER
_personal_info_history.personal_info = personal_info
db.add(_personal_info_history)

await db.commit()

return
94 changes: 94 additions & 0 deletions app/utils/sealedtx_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""
Copyright BOOSTRY Co., Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache-2.0
"""

import json
from typing import Annotated

from eth_account.messages import encode_defunct
from fastapi import Depends, Header, Request
from web3.auto import w3

from app import log
from app.exceptions import InvalidParameterError

LOG = log.get_logger()


async def get_body(req: Request):
return await req.body()


RawRequestBody = Annotated[bytes, Depends(get_body)]

SealedTxSignatureHeader = Annotated[str, Header(alias="X-SealedTx-Signature")]


def VerifySealedTxSignature(req: Request, body: dict | None, signature: str):
"""
Verify X-SealedTx-Signature
- https://github.com/BoostryJP/ibet-Prime/issues/689
"""

if signature == "":
raise InvalidParameterError("Signature is empty")
LOG.debug("X-SealedTx-Signature: " + signature)

# Calculating the hash value of the request body
if body:
request_body = json.dumps(body, separators=(",", ":"))
else:
request_body = json.dumps({})
LOG.debug("request_body: " + request_body)
request_body_hash = w3.keccak(text=request_body).hex()

# Normalize the query parameters
kvs = []
for k, v in sorted(req.query_params.items()):
if type(v) == int:
v = str(v)
kvs.append(k + "=" + v)

if len(kvs) == 0:
query_params = ""
else:
query_params = "?" + "&".join(kvs)

# Generate a CanonicalRequest
canonical_request = (
req.method
+ "\n"
+ req.url.path
+ "\n"
+ query_params
+ "\n"
+ request_body_hash
)
LOG.debug("Canonical Request: " + canonical_request)

# Verify the signature
try:
recovered_address = w3.eth.account.recover_message(
encode_defunct(text=canonical_request),
signature=signature,
)
LOG.debug("Recovered EOA: " + recovered_address)
except Exception:
raise InvalidParameterError("failed to recover hash")

return recovered_address
Loading
Loading