Skip to content
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
46 changes: 46 additions & 0 deletions citrate_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ def _event_topic(signature: str) -> str:
return Web3.keccak(text=signature).hex().lower()


#: Shown when a plain value transfer (no calldata) names an address that holds code (other than a
#: member's smart wallet).
CONTRACT_RECIPIENT = (
"This address is a contract, so a plain transfer to it may never be credited to anyone. "
"Use the contract's own deposit function instead."
)


class CitrateClient:
"""
Main client for interacting with Citrate blockchain.
Expand Down Expand Up @@ -504,6 +512,40 @@ def _send_transaction(
encoded = data if isinstance(data, str) else json.dumps(data)
return self._sign_and_send(to_address, "0x" + encoded.encode().hex(), value, gas_limit)

def _check_plain_transfer_recipient(self, to_address: str) -> None:
"""Refuse a plain value transfer (no calldata) to an address that holds code.

Value for a contract goes through that contract's own function. The one exception is a
member's smart wallet: CitrateWalletFactory's ERC1967 proxy code whose implementation slot
holds the book's ``CitrateWallet`` (its ``receive()`` is empty, so the wallet is credited).
Data source: ``eth_getCode`` and ``eth_getStorageAt`` on ``rpc_url``; anything that cannot
be read is refused.
"""
from .identity.wallet import (
CITRATE_WALLET_PROXY_RUNTIME,
ERC1967_IMPLEMENTATION_SLOT,
)

try:
code = self._rpc_call("eth_getCode", [to_address, "latest"])
except Exception as e: # noqa: BLE001 - any failure fails closed
raise CitrateError(f"could not check the recipient: {e}") from e
if not isinstance(code, str) or not code.startswith("0x"):
raise CitrateError("could not check the recipient: eth_getCode returned no hex")
if code in ("0x", "0x0"):
return
if code.lower() != CITRATE_WALLET_PROXY_RUNTIME:
raise CitrateError(CONTRACT_RECIPIENT)
try:
slot = self._rpc_call("eth_getStorageAt", [to_address, ERC1967_IMPLEMENTATION_SLOT, "latest"])
except Exception as e: # noqa: BLE001 - any failure fails closed
raise CitrateError(f"could not check the recipient: {e}") from e
if not isinstance(slot, str) or not slot.startswith("0x") or len(slot) != 66:
raise CitrateError("could not check the recipient: eth_getStorageAt returned no word")
wallet_impl = str(_contract.aa_stack()["CitrateWallet"]).lower()
if slot.lower() != "0x" + "00" * 12 + wallet_impl[2:]:
raise CitrateError(CONTRACT_RECIPIENT)

def _sign_and_send(
self, to_address: str | None, data_hex: str, value: int, gas_limit: int
) -> str:
Expand All @@ -518,6 +560,10 @@ def _sign_and_send(
# r1006: refuse another network (same chain id, different genesis) before signing.
self.verify_network()

# A plain value transfer to a contract is refused before anything is signed.
if to_address is not None and data_hex in ("", "0x") and value > 0:
self._check_plain_transfer_recipient(to_address)

# Get account info
from_address = self.key_manager.get_address()
nonce = self.get_nonce(from_address)
Expand Down
9 changes: 9 additions & 0 deletions citrate_sdk/identity/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@
_TAIL = bytes.fromhex("cc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3")
_ZERO = "0x" + "00" * 20

#: The runtime code CitrateWalletFactory deploys for every wallet: Solady's ERC1967 proxy
#: (LibClone ``createDeterministicERC1967``), the tail of the init code hashed above. It reads its
#: implementation from the ERC1967 slot, so the code is the same for every wallet.
CITRATE_WALLET_PROXY_RUNTIME = "0x" + (_BODY[3:] + _TAIL).hex()
#: keccak256 of that runtime; Core's transfer guard pins the same value.
CITRATE_WALLET_PROXY_CODEHASH = "0x" + keccak(_BODY[3:] + _TAIL).hex()
#: ERC1967 implementation slot (``bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)``).
ERC1967_IMPLEMENTATION_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"


class WalletPredictionError(Exception):
pass
Expand Down
164 changes: 164 additions & 0 deletions tests/test_plain_transfer_recipient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
"""A plain value transfer (no calldata) to an address that holds code is refused before anything
is signed: the caller is pointed at the contract's own deposit function. The RPC answers here are
a scripted test fixture (patch.object on _rpc_call)."""
from unittest.mock import MagicMock, patch

import pytest
from eth_utils import keccak

from citrate_sdk._generated import contract as _contract
from citrate_sdk.client import CONTRACT_RECIPIENT, CitrateClient
from citrate_sdk.errors import CitrateError
from citrate_sdk.identity.wallet import (
CITRATE_WALLET_PROXY_CODEHASH,
CITRATE_WALLET_PROXY_RUNTIME,
ERC1967_IMPLEMENTATION_SLOT,
)

# The live 40204 book (citrate-chain contracts/addresses/40204.json, r1007): both are contracts.
WRAPPED_SALT = "0xaa918302b94a4b0e75e01e019cc6b819b4f7c906"
ENTRY_POINT = "0x97d5391a647429233e202f99231743c53a648f3c"
PLAIN = "0x1111111111111111111111111111111111111111"
# A CitrateWalletFactory smart wallet: Solady's ERC1967 proxy whose implementation slot holds the
# book's CitrateWallet (receive() is empty, so a plain transfer credits the wallet).
SMART_WALLET = "0x2222222222222222222222222222222222222222"
# The same proxy code pointing at some other implementation.
OTHER_PROXY = "0x3333333333333333333333333333333333333333"
OTHER_IMPL = "0x4444444444444444444444444444444444444444"


def _client():
c = CitrateClient(rpc_url="http://example", allow_insecure_http=True)
km = MagicMock()
km.get_address.return_value = "0x9858effd232b4033e47d90003d41ec34ecaeda94"
km.sign_transaction.return_value = "0xsigned"
c.key_manager = km
return c


def _slot(addr):
return "0x" + "00" * 12 + addr[2:].lower()


def _rpc(methods, code_fails=False, slot_fails=False):
def answer(method, params=None):
methods.append(method)
if method == "eth_getCode":
if code_fails:
raise CitrateError("unavailable")
if params[0].lower() in (SMART_WALLET, OTHER_PROXY):
return CITRATE_WALLET_PROXY_RUNTIME
return "0x6080604052" if params[0].lower() in (WRAPPED_SALT, ENTRY_POINT) else "0x"
if method == "eth_getStorageAt":
if slot_fails:
raise CitrateError("unavailable")
assert params[1] == ERC1967_IMPLEMENTATION_SLOT
impl = _contract.aa_stack()["CitrateWallet"] if params[0].lower() == SMART_WALLET else OTHER_IMPL
return _slot(impl)
if method == "eth_getTransactionCount":
return "0x0"
if method == "eth_sendRawTransaction":
return "0x" + "22" * 32
raise AssertionError(f"unexpected {method}")

return answer


@pytest.mark.parametrize("to", [WRAPPED_SALT, ENTRY_POINT])
def test_value_to_wrapped_salt_and_entry_point_is_refused(to):
c = _client()
methods: list[str] = []
with patch.object(c, "_rpc_call", side_effect=_rpc(methods)), patch.object(c, "verify_network"), patch.object(
c, "_eip155_chain_id", return_value=40204
):
with pytest.raises(CitrateError) as e:
c._sign_and_send(to, "0x", 10**18, 21_000)
assert str(e.value) == CONTRACT_RECIPIENT
assert CONTRACT_RECIPIENT == (
"This address is a contract, so a plain transfer to it may never be credited to anyone. "
"Use the contract's own deposit function instead."
)
assert "\u2014" not in CONTRACT_RECIPIENT
assert "eth_sendRawTransaction" not in methods
c.key_manager.sign_transaction.assert_not_called()


def test_value_to_a_plain_account_is_sent_as_before():
c = _client()
methods: list[str] = []
with patch.object(c, "_rpc_call", side_effect=_rpc(methods)), patch.object(c, "verify_network"), patch.object(
c, "_eip155_chain_id", return_value=40204
):
tx_hash = c._sign_and_send(PLAIN, "0x", 5, 21_000)
assert tx_hash.startswith("0x")
assert methods[0] == "eth_getCode" and methods[-1] == "eth_sendRawTransaction"


def test_a_call_with_calldata_is_not_checked():
c = _client()
methods: list[str] = []
with patch.object(c, "_rpc_call", side_effect=_rpc(methods)), patch.object(c, "verify_network"), patch.object(
c, "_eip155_chain_id", return_value=40204
):
c._sign_and_send(WRAPPED_SALT, "0xd0e30db0", 5, 60_000)
assert "eth_getCode" not in methods


def test_unreadable_recipient_code_is_refused():
c = _client()
methods: list[str] = []
with patch.object(c, "_rpc_call", side_effect=_rpc(methods, code_fails=True)), patch.object(
c, "verify_network"
), patch.object(c, "_eip155_chain_id", return_value=40204):
with pytest.raises(CitrateError) as e:
c._sign_and_send(PLAIN, "0x", 5, 21_000)
assert "could not check the recipient" in str(e.value)
c.key_manager.sign_transaction.assert_not_called()


# R5 B1 (2026-11-30): a member's smart wallet is a contract that accepts a plain transfer.


def _send(to, **kw):
c = _client()
methods: list[str] = []
with patch.object(c, "_rpc_call", side_effect=_rpc(methods, **kw)), patch.object(
c, "verify_network"
), patch.object(c, "_eip155_chain_id", return_value=40204):
try:
return c, methods, c._sign_and_send(to, "0x", 10**18, 21_000), None
except CitrateError as e:
return c, methods, None, e


def test_value_to_a_citrate_wallet_is_sent():
c, methods, tx_hash, err = _send(SMART_WALLET)
assert err is None and tx_hash is not None
assert methods[:2] == ["eth_getCode", "eth_getStorageAt"]
assert methods[-1] == "eth_sendRawTransaction"


def test_the_same_proxy_code_for_another_implementation_is_refused():
c, methods, _, err = _send(OTHER_PROXY)
assert err is not None and str(err) == CONTRACT_RECIPIENT
c.key_manager.sign_transaction.assert_not_called()


def test_an_unreadable_implementation_slot_is_refused():
c, methods, _, err = _send(SMART_WALLET, slot_fails=True)
assert err is not None and "could not check the recipient" in str(err)
c.key_manager.sign_transaction.assert_not_called()


def test_the_wallet_proxy_definition_is_the_factory_one():
# One definition for Core and the SDKs: Solady's ERC1967 proxy runtime (LibClone, the code
# CitrateWalletFactory deploys; the same bytes the wallet address prediction hashes) and its
# codehash, pinned here and in Core's transfer guard.
assert CITRATE_WALLET_PROXY_RUNTIME == (
"0x363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076"
"cc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3"
)
assert CITRATE_WALLET_PROXY_CODEHASH == "0x" + keccak(bytes.fromhex(CITRATE_WALLET_PROXY_RUNTIME[2:])).hex()
# Solady LibClone.ERC1967_CODE_HASH at citrate-chain's pinned lib/kernel/lib/solady.
assert CITRATE_WALLET_PROXY_CODEHASH == "0xaaa52c8cc8a0e3fd27ce756cc6b4e70c51423e9b597b11f32d3e49f8b1fc890d"
assert ERC1967_IMPLEMENTATION_SLOT == "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
Loading