diff --git a/bridge-sdk/pyproject.toml b/bridge-sdk/pyproject.toml index f16bd112..ea031be6 100644 --- a/bridge-sdk/pyproject.toml +++ b/bridge-sdk/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "aleo-bridge-sdk" -version = "0.8.0" +version = "0.9.0" description = "Bridge Aleo, Ethereum, BSC, Arc, Base, Arbitrum and Solana assets with Hyperlane, Verulink, Circle xReserve and CCTP" readme = "README.md" requires-python = ">=3.10" diff --git a/bridge-sdk/python/aleo_bridge/__init__.py b/bridge-sdk/python/aleo_bridge/__init__.py index 42119445..2a29a117 100644 --- a/bridge-sdk/python/aleo_bridge/__init__.py +++ b/bridge-sdk/python/aleo_bridge/__init__.py @@ -8,7 +8,7 @@ from pathlib import Path -__version__ = "0.8.0" +__version__ = "0.9.0" _ALEO_SDK_MINIMUM = "0.7.0" diff --git a/bridge-sdk/tests/test_client_lifecycle.py b/bridge-sdk/tests/test_client_lifecycle.py index ade27af2..02f1e8e5 100644 --- a/bridge-sdk/tests/test_client_lifecycle.py +++ b/bridge-sdk/tests/test_client_lifecycle.py @@ -205,7 +205,7 @@ def test_public_exports_pin_pre_existing_set_and_add_lifecycle_names(): assert hasattr(aleo_bridge, name), name assert set(PRE_EXISTING_EXPORTS) <= set(aleo_bridge.__all__) assert set(NEW_EXPORTS) <= set(aleo_bridge.__all__) - assert aleo_bridge.__version__ == "0.8.0" + assert aleo_bridge.__version__ == "0.9.0" assert aleo_bridge.lifecycle is lifecycle assert aleo_bridge.prepare is lifecycle.prepare assert aleo_bridge.bridge_tools is agent.bridge_tools diff --git a/bridge-sdk/tests/test_package.py b/bridge-sdk/tests/test_package.py index 32a65527..5d0b6fa8 100644 --- a/bridge-sdk/tests/test_package.py +++ b/bridge-sdk/tests/test_package.py @@ -13,7 +13,7 @@ def test_version_is_pinned_in_lockstep(): pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) - assert pyproject["project"]["version"] == "0.8.0" == aleo_bridge.__version__ + assert pyproject["project"]["version"] == "0.9.0" == aleo_bridge.__version__ assert pyproject["project"]["name"] == "aleo-bridge-sdk" deps = pyproject["project"]["dependencies"] for base in ("aleo-sdk", "pynacl", "web3", "eth-account", "solders", "solana", "privy-client", "dynamic-wallet-sdk"): @@ -105,7 +105,7 @@ def test_import_without_optional_extras(monkeypatch): monkeypatch.delitem(sys.modules, name) # reverted at teardown — a fresh reimport below must not # leak new module/class objects into tests that run after this one pkg = importlib.import_module("aleo_bridge") - assert pkg.__version__ == "0.8.0" + assert pkg.__version__ == "0.9.0" assert issubclass(pkg.RouteNotFoundError, pkg.BridgeError) diff --git a/sdk-abi/Cargo.lock b/sdk-abi/Cargo.lock index cc2cf527..112ff1e8 100644 --- a/sdk-abi/Cargo.lock +++ b/sdk-abi/Cargo.lock @@ -19,7 +19,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aleo-abi" -version = "0.8.0" +version = "0.9.0" dependencies = [ "anyhow", "leo-abi", diff --git a/sdk-abi/Cargo.toml b/sdk-abi/Cargo.toml index 7bd35f7f..15dd9eef 100644 --- a/sdk-abi/Cargo.toml +++ b/sdk-abi/Cargo.toml @@ -5,7 +5,7 @@ [package] name = "aleo-abi" -version = "0.8.0" +version = "0.9.0" edition = "2024" license = "GPL-3.0-or-later" description = "Python bindings for ABI generation from Aleo bytecode (via Leo's leo-abi crate)" diff --git a/sdk-abi/pyproject.toml b/sdk-abi/pyproject.toml index b64c6045..e243904d 100644 --- a/sdk-abi/pyproject.toml +++ b/sdk-abi/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "aleo-contract-abi-generator" -version = "0.8.0" +version = "0.9.0" description = "Python bindings for ABI generation from Aleo bytecode" readme = "README.md" license = {text = "GPL-3.0-or-later"} diff --git a/sdk/Cargo.lock b/sdk/Cargo.lock index 28ea9d1d..96fdf937 100644 --- a/sdk/Cargo.lock +++ b/sdk/Cargo.lock @@ -37,7 +37,7 @@ dependencies = [ [[package]] name = "aleo" -version = "0.8.0" +version = "0.9.0" dependencies = [ "anyhow", "hex", diff --git a/sdk/Cargo.toml b/sdk/Cargo.toml index f8a34c65..d712c502 100644 --- a/sdk/Cargo.toml +++ b/sdk/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "aleo" authors = ["Konstantin Pandl", "Mike Turner", "Roman Proskuryakov"] -version = "0.8.0" +version = "0.9.0" description = "A Python sdk for zero-knowledge cryptography based on Aleo" edition = "2021" license = "GPL-3.0-or-later" diff --git a/sdk/docs/source/conf.py b/sdk/docs/source/conf.py index 04468ca7..98f26ae7 100644 --- a/sdk/docs/source/conf.py +++ b/sdk/docs/source/conf.py @@ -11,7 +11,7 @@ copyright = '2019-2026, Provable Inc.' author = 'kpp' -version = '0.8.0' +version = '0.9.0' # -- General configuration diff --git a/sdk/pyproject.toml b/sdk/pyproject.toml index 33c1f338..53006484 100644 --- a/sdk/pyproject.toml +++ b/sdk/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "aleo-sdk" description = "Python SDK for building zero-knowledge apps and DeFi on the Aleo network" -version = "0.8.0" +version = "0.9.0" readme = "Readme.md" license = {file = "LICENSE.md"} authors = [ diff --git a/shield-swap-sdk/AGENTS.md b/shield-swap-sdk/AGENTS.md index 3d43c60e..a645f264 100644 --- a/shield-swap-sdk/AGENTS.md +++ b/shield-swap-sdk/AGENTS.md @@ -8,12 +8,13 @@ Typed Python client for the shield_swap AMM on Aleo MCP alternative: `python -m aleo_shield_swap.mcp` exposes the same lifecycle as tools. -## Tier 1 — the lifecycle (six lines end to end) +## Tier 1 — start and resume a trading session ```python -from aleo_shield_swap import ShieldSwap +from aleo_shield_swap import Profile, ShieldSwap -dex = ShieldSwap.from_profile() # key material auto-managed on disk +Profile.load_or_create(storage="encrypted") # Protect a new key; existing storage stays unchanged. +dex = ShieldSwap.from_profile() # Resume with the same account and journal. dex.onboard() # first run registers; no-op afterwards pools = dex.api.get_pools() report = dex.swap_many(pool_key=pools[0].key, token_in_id=pools[0].token0, @@ -23,23 +24,54 @@ dex.collect_all() # any session, any time ### `from_profile(home: 'Any' = None, *, network: 'Optional[str]' = None, endpoint: 'Optional[str]' = None) -> "'ShieldSwap'"` -The client for the local participant profile (created on first use). +Continue trading with the same account, credentials, and swap journal. -Wires endpoint, network, signer, and (when present) delegated-proving -credentials from ``$SHIELD_SWAP_HOME``/``~/.shield-swap``. Run -``onboard()`` next on a fresh profile. +Use the same *home* on each run to retain pending swaps and saved API +credentials. On first use, the client uses an existing Aleo account +or creates one. To keep an existing address and its funds, import +that account before starting; see :meth:`Profile.load_or_create`. -*network* and *endpoint* apply only when the profile is being created — -an existing one keeps what it was created with, because its derived pool -keys and blinded identities are network-scoped and would not transfer. -Give each network its own home directory. +For a new account, use macOS Keychain or password encryption to +protect the private key. Set this up before building the client:: + + from aleo_shield_swap import Profile, ShieldSwap + + Profile.load_or_create(storage="encrypted") + dex = ShieldSwap.from_profile() + +This prompts for a password if none is supplied by the environment +or Keychain. It does not change an account's existing storage. +Without this setup, a generated key is saved as plaintext: anyone +who can read the account file can spend its funds. Use +``storage="keychain"`` on macOS to keep the key outside the file. + +An encrypted account needs its password each time the client starts. +For unattended runs, set ``ALEO_ACCOUNT_PASSWORD`` or save the password +in the macOS Keychain. A key supplied through ``ALEO_PRIVATE_KEY`` or +``ALEO_PRIVATE_KEY_FILE`` must also be supplied each run; it is never +saved by the profile. + +The client attempts to register with the hosted record scanner, +sharing the account's view key so the scanner can read its records. +For a custom record provider, construct ``ShieldSwap(aleo)`` instead. +Call ``onboard()`` to register a new account with Shield Swap before +trading. Client construction does not submit a trade. Args: - home: Profile directory; defaults to ``$SHIELD_SWAP_HOME`` or - ``~/.shield-swap``. - network: ``"mainnet"`` or ``"testnet"`` for a NEW profile; defaults - to testnet. - endpoint: Node API origin for a NEW profile. + home: Directory holding the profile and its saved work. Defaults to + ``SHIELD_SWAP_HOME``, then ``~/.shield-swap``. Use a separate + directory for each network. + network: ``"mainnet"`` or ``"testnet"``; defaults to testnet for a + new profile. An existing profile keeps its recorded network. + endpoint: API service root for a new profile; defaults to + ``https://edge.provable.com/api``. Ignored for an existing profile. + +Raises: + aleo.keystore.KeystoreError: The account cannot be opened. Check + ``code``: ``PASSWORD_REQUIRED`` means a password must be supplied; + ``ACCOUNT_NOT_FOUND`` means an existing profile's key is missing; + ``ADDRESS_MISMATCH`` means the selected key belongs to another + address. Restore the intended key before trying again. ### `onboard(self, referral_code: 'Optional[str]' = None) -> 'OnboardReport'` @@ -99,13 +131,19 @@ reports. Requires ``from_profile()``. ### Before doing anything: two questions -1. **Existing account?** When `status()` shows a brand-new, unregistered - profile, ask whether the user already has a shield-swap account before - creating anything — their funds and access live on the old key. - **NEVER ask the user to paste a private key into the conversation.** - They supply it out-of-band: `export SHIELD_SWAP_PRIVATE_KEY=...` (or - `SHIELD_SWAP_PRIVATE_KEY_FILE=path`) in their own shell before the - profile is first created. +1. **Existing account?** Ask before creating a profile: an existing + account's funds stay with its original key. Have the user import that key + in their own terminal with + `python -m aleo.keystore import --storage encrypted`, or use + `--storage keychain` on macOS. These protect the saved key; plaintext + storage leaves it readable to anyone with access to the account file. + After import, `Profile.load_or_create(create=False)` requires that account + rather than generating another key if setup is missing. + **Never ask for a private key in the conversation.** Do not run + `python -m aleo.keystore export` or read account files to inspect an + address; use `python -m aleo.keystore show` instead. An account supplied + through `ALEO_PRIVATE_KEY` or `ALEO_PRIVATE_KEY_FILE` must be supplied + each run; the profile does not save that key. 2. **Referral code — optional.** Access is granted by authentication alone; `onboard()` needs nothing from the user. Mention that a referral code from a friend can be passed (`onboard(referral_code=)`) @@ -184,7 +222,7 @@ where the signing keys live: | Building | Stack | Keys live | | --- | --- | --- | -| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A local private key (`ShieldSwap.from_profile()` manages it); delegated proving through the Provable prover — fees covered by default. | +| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A saved Aleo account. Import an existing key to retain its funds, or create an account with Keychain or encrypted storage before calling `ShieldSwap.from_profile()`. Delegated proving uses the Provable prover; fees are covered by default. | | Agent integration | `aleo_shield_swap.agent` (Claude-shape tool schemas + `dispatch_tool`) or `python -m aleo_shield_swap.mcp` (MCP server), over the same client | Same as the underlying client; the tools bind to it. | | Browser dApp (wallet-signed) | The TypeScript stack: `@provablehq/shield-swap-sdk` + Veil react hooks — not this package | The user's wallet signs and proves. | diff --git a/shield-swap-sdk/README.md b/shield-swap-sdk/README.md index 57ab64f7..ccfcd807 100644 --- a/shield-swap-sdk/README.md +++ b/shield-swap-sdk/README.md @@ -43,7 +43,7 @@ pip install -e "shield-swap-sdk[async]" # + AsyncShieldSwap (httpx) pip install -e "shield-swap-sdk[mcp]" # + the MCP server ``` -Requires `aleo-sdk>=0.8.0` (this repo's SDK; imports as `aleo`) and Python 3.10+. +Requires `aleo-sdk>=0.9.0` (this repo's SDK; imports as `aleo`) and Python 3.10+. ## First swap example @@ -72,6 +72,124 @@ Claude Code users get it via the `shield-swap` skill (packaged under `aleo_shield_swap/skills/`, copy into `.claude/skills/`); any MCP client can run the same lifecycle through `python -m aleo_shield_swap.mcp`. +## Keep using the same account + +A profile keeps an account's address, API credentials, and swap journal +together so a script can resume trading or collect unfinished swaps after a +restart. Use the same profile directory on each run: `~/.shield-swap` by +default, or a directory selected with `SHIELD_SWAP_HOME` or the `home` argument. + +Profile directories that use one account on one network share its swap +counters through `~/.aleo/shield-swap/counters//
.jsonl`, so +their swaps never reuse a blinded identity. Each directory keeps its own +journal: collect a swap from the profile that made it. + +### Use an existing account + +Import the account to keep its address and funds. Run this in a terminal; +the command asks for the private key without displaying it: + +```sh +python -m aleo.keystore import --name trading --storage encrypted +``` + +Then create a profile for that account. `create=False` requires an existing +key, so a missing account produces an error instead of a new address. + +```python +from aleo_shield_swap import Profile, ShieldSwap + +profile = Profile.load_or_create(account="trading", create=False) +dex = ShieldSwap.from_profile(profile.home) +``` + +On later runs, `ShieldSwap.from_profile()` reuses the saved account, credentials, +and journal. An encrypted account needs its password when the client starts. + +### Protect a new account's key + +Use macOS Keychain or encrypted storage for saved keys. The default is +plaintext, so choose storage before generating an account: + +```python +from aleo_shield_swap import Profile, ShieldSwap + +Profile.load_or_create(storage="encrypted") +dex = ShieldSwap.from_profile() +``` + +The first call asks for an encryption password if none was supplied. On macOS, +use `storage="keychain"` to keep the private key outside the account file. +The choices differ in what access to that file reveals: + +| Storage | Where the key is kept | What unlocks it | +| --- | --- | --- | +| `"keychain"` (macOS) | In macOS Keychain; the account file contains a reference to it. | Access to the Keychain entry. Copying the account file does not copy the key. | +| `"encrypted"` | Encrypted inside the account file. | The account password. A copy or backup remains encrypted. | +| `"plaintext"` (default) | Readable inside the account file. | Nothing beyond access to the file. Owner-only permissions do not encrypt the key or protect a copied file. | + +Anyone who obtains the private key can spend the account's funds. The address +remains readable in the account file in every mode. + +`storage` only applies when generating a key. To protect an account that +already exists, change its storage without changing its address or funds: + +```sh +python -m aleo.keystore protect --name trading --storage encrypted +``` + +To create a separate account, choose both an unused `account` name and a +separate profile directory. A second directory alone reuses the same account. +Clear any private-key variables first, since those take precedence over the +named account. + +### Run without a password prompt + +For `ShieldSwap.from_profile()` and MCP, set `ALEO_ACCOUNT_PASSWORD` or save +the encryption password in macOS Keychain. When creating an encrypted account, +`save_password=True` saves the password there so later runs can unlock it +without a prompt. The password is still needed; Keychain supplies it. + +Code that uses `Profile` directly can also pass `password` to +`Profile.load_or_create`. That password is kept only by the returned object; +it is not passed on to a later `ShieldSwap.from_profile()` call. Without a +password source, unlocking asks at a hidden terminal prompt, which unattended +scripts and MCP servers cannot answer. + +A key supplied through `ALEO_PRIVATE_KEY` or `ALEO_PRIVATE_KEY_FILE` is used +before a saved key and is never copied to disk. Supply it on every run, or +import it once to save it. `SHIELD_SWAP_PRIVATE_KEY` and +`SHIELD_SWAP_PRIVATE_KEY_FILE` are also accepted. Any supplied key must match +the profile's address and the selected account file, if one exists. + +Account files default to `~/.aleo/accounts/.json`. The name comes from +`account`, then `ALEO_ACCOUNT`, then the profile's saved name, then `default`. +Use `accounts_dir` or `ALEO_ACCOUNTS_DIR` for another directory. The profile +does not save that location, so supply it on each run; clients opened with +`ShieldSwap.from_profile()` need `ALEO_ACCOUNTS_DIR` for a custom location. + +Opening an existing `Profile` does not require its key. Reading +`profile.private_key` unlocks it and checks the address. Failures raise +`aleo.keystore.KeystoreError`; check `error.code` for a missing account +(`ACCOUNT_NOT_FOUND`), a needed password (`PASSWORD_REQUIRED`), or a key for +another address (`ADDRESS_MISMATCH`). See +[`aleo.keystore`](../sdk/Readme.md#store-an-account--aleokeystore) for the full +account API. + +### Move a key out of an older profile + +Older profiles with a private key in `profile.json` still work. Using that key +logs a migration command once per profile file per process. To encrypt the key +and remove the plaintext copy from the profile, run: + +```sh +python -m aleo.keystore migrate --from ~/.shield-swap/profile.json --storage encrypted --remove-legacy-key +``` + +Without `--remove-legacy-key`, migration leaves the plaintext key in +`profile.json`. Existing backups also retain their copies. Earlier SDK releases +cannot read a profile after its key has been removed. + ## How calls work Every read returns a value immediately. Every write returns a prepared diff --git a/shield-swap-sdk/codegen/gen_context.py b/shield-swap-sdk/codegen/gen_context.py index 9c684b1b..8d045ca9 100644 --- a/shield-swap-sdk/codegen/gen_context.py +++ b/shield-swap-sdk/codegen/gen_context.py @@ -43,9 +43,10 @@ QUICKSTART = """\ ```python -from aleo_shield_swap import ShieldSwap +from aleo_shield_swap import Profile, ShieldSwap -dex = ShieldSwap.from_profile() # key material auto-managed on disk +Profile.load_or_create(storage="encrypted") # Protect a new key; existing storage stays unchanged. +dex = ShieldSwap.from_profile() # Resume with the same account and journal. dex.onboard() # first run registers; no-op afterwards pools = dex.api.get_pools() report = dex.swap_many(pool_key=pools[0].key, token_in_id=pools[0].token0, @@ -58,13 +59,19 @@ ### Before doing anything: two questions -1. **Existing account?** When `status()` shows a brand-new, unregistered - profile, ask whether the user already has a shield-swap account before - creating anything — their funds and access live on the old key. - **NEVER ask the user to paste a private key into the conversation.** - They supply it out-of-band: `export SHIELD_SWAP_PRIVATE_KEY=...` (or - `SHIELD_SWAP_PRIVATE_KEY_FILE=path`) in their own shell before the - profile is first created. +1. **Existing account?** Ask before creating a profile: an existing + account's funds stay with its original key. Have the user import that key + in their own terminal with + `python -m aleo.keystore import --storage encrypted`, or use + `--storage keychain` on macOS. These protect the saved key; plaintext + storage leaves it readable to anyone with access to the account file. + After import, `Profile.load_or_create(create=False)` requires that account + rather than generating another key if setup is missing. + **Never ask for a private key in the conversation.** Do not run + `python -m aleo.keystore export` or read account files to inspect an + address; use `python -m aleo.keystore show` instead. An account supplied + through `ALEO_PRIVATE_KEY` or `ALEO_PRIVATE_KEY_FILE` must be supplied + each run; the profile does not save that key. 2. **Referral code — optional.** Access is granted by authentication alone; `onboard()` needs nothing from the user. Mention that a referral code from a friend can be passed (`onboard(referral_code=)`) @@ -143,7 +150,7 @@ | Building | Stack | Keys live | | --- | --- | --- | -| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A local private key (`ShieldSwap.from_profile()` manages it); delegated proving through the Provable prover — fees covered by default. | +| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A saved Aleo account. Import an existing key to retain its funds, or create an account with Keychain or encrypted storage before calling `ShieldSwap.from_profile()`. Delegated proving uses the Provable prover; fees are covered by default. | | Agent integration | `aleo_shield_swap.agent` (Claude-shape tool schemas + `dispatch_tool`) or `python -m aleo_shield_swap.mcp` (MCP server), over the same client | Same as the underlying client; the tools bind to it. | | Browser dApp (wallet-signed) | The TypeScript stack: `@provablehq/shield-swap-sdk` + Veil react hooks — not this package | The user's wallet signs and proves. | @@ -206,7 +213,7 @@ def render() -> str: "MCP alternative: `python -m aleo_shield_swap.mcp` exposes the same", "lifecycle as tools.", "", - "## Tier 1 — the lifecycle (six lines end to end)", + "## Tier 1 — start and resume a trading session", "", QUICKSTART, "", diff --git a/shield-swap-sdk/examples/first-swap/README.md b/shield-swap-sdk/examples/first-swap/README.md index b7db6eed..9d5cace5 100644 --- a/shield-swap-sdk/examples/first-swap/README.md +++ b/shield-swap-sdk/examples/first-swap/README.md @@ -19,10 +19,26 @@ An installed release that contains the example also supports: python -m aleo_shield_swap.examples.first_swap.swap ``` -## 1. Create an account +## 1. Choose the account to trade with -Start with an existing testnet private key or let the SDK create and retain one -in `~/.shield-swap/profile.json`. +Use an existing testnet account to keep its address and funds. Before running +the example, import its key from a terminal: + +```sh +python -m aleo.keystore import --storage encrypted +``` + +For a new account, run `python -m aleo.keystore create --storage encrypted` +instead. Both commands ask for a password without displaying it. On macOS, +`--storage keychain` keeps the key in Keychain instead of encrypting it in a +file. These are the recommended choices: the default, plaintext, leaves the +private key readable to anyone with access to the account file. + +The example reuses this account on later runs. With no account set up, it +creates one using plaintext storage in `~/.aleo/accounts/default.json` and +records its address in `~/.shield-swap/profile.json`. An encrypted account +needs its password at startup; unattended runs need `ALEO_ACCOUNT_PASSWORD` +or a password saved in macOS Keychain. ```python import os diff --git a/shield-swap-sdk/examples/first-swap/swap.py b/shield-swap-sdk/examples/first-swap/swap.py index 5f871308..23e693a6 100644 --- a/shield-swap-sdk/examples/first-swap/swap.py +++ b/shield-swap-sdk/examples/first-swap/swap.py @@ -17,7 +17,8 @@ # Use a configured private key or create a new key. key = os.environ.get("SHIELD_SWAP_PRIVATE_KEY") if not key: - # Load a saved private key from an existing Profile or create a new one. + # Reuse the account on later runs so its funds remain available. + # With no saved account, this creates one using plaintext storage. profile = Profile.load_or_create(network="testnet") if profile.network != "testnet": raise RuntimeError("This example requires a testnet profile") diff --git a/shield-swap-sdk/pyproject.toml b/shield-swap-sdk/pyproject.toml index fa435f3e..7a7235a9 100644 --- a/shield-swap-sdk/pyproject.toml +++ b/shield-swap-sdk/pyproject.toml @@ -1,10 +1,10 @@ [project] name = "shield-swap-sdk" -version = "0.8.0" +version = "0.9.0" description = "Python SDK for the shield swap AMM Dex on Aleo" readme = "README.md" requires-python = ">=3.10" -dependencies = ["aleo-sdk>=0.8.0", "requests>=2"] # 0.8.0: aleo.inventory (record management) +dependencies = ["aleo-sdk>=0.9.0", "requests>=2"] # Profiles require aleo.keystore. [project.optional-dependencies] async = ["httpx>=0.27"] diff --git a/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md b/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md index 3d43c60e..a645f264 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md +++ b/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md @@ -8,12 +8,13 @@ Typed Python client for the shield_swap AMM on Aleo MCP alternative: `python -m aleo_shield_swap.mcp` exposes the same lifecycle as tools. -## Tier 1 — the lifecycle (six lines end to end) +## Tier 1 — start and resume a trading session ```python -from aleo_shield_swap import ShieldSwap +from aleo_shield_swap import Profile, ShieldSwap -dex = ShieldSwap.from_profile() # key material auto-managed on disk +Profile.load_or_create(storage="encrypted") # Protect a new key; existing storage stays unchanged. +dex = ShieldSwap.from_profile() # Resume with the same account and journal. dex.onboard() # first run registers; no-op afterwards pools = dex.api.get_pools() report = dex.swap_many(pool_key=pools[0].key, token_in_id=pools[0].token0, @@ -23,23 +24,54 @@ dex.collect_all() # any session, any time ### `from_profile(home: 'Any' = None, *, network: 'Optional[str]' = None, endpoint: 'Optional[str]' = None) -> "'ShieldSwap'"` -The client for the local participant profile (created on first use). +Continue trading with the same account, credentials, and swap journal. -Wires endpoint, network, signer, and (when present) delegated-proving -credentials from ``$SHIELD_SWAP_HOME``/``~/.shield-swap``. Run -``onboard()`` next on a fresh profile. +Use the same *home* on each run to retain pending swaps and saved API +credentials. On first use, the client uses an existing Aleo account +or creates one. To keep an existing address and its funds, import +that account before starting; see :meth:`Profile.load_or_create`. -*network* and *endpoint* apply only when the profile is being created — -an existing one keeps what it was created with, because its derived pool -keys and blinded identities are network-scoped and would not transfer. -Give each network its own home directory. +For a new account, use macOS Keychain or password encryption to +protect the private key. Set this up before building the client:: + + from aleo_shield_swap import Profile, ShieldSwap + + Profile.load_or_create(storage="encrypted") + dex = ShieldSwap.from_profile() + +This prompts for a password if none is supplied by the environment +or Keychain. It does not change an account's existing storage. +Without this setup, a generated key is saved as plaintext: anyone +who can read the account file can spend its funds. Use +``storage="keychain"`` on macOS to keep the key outside the file. + +An encrypted account needs its password each time the client starts. +For unattended runs, set ``ALEO_ACCOUNT_PASSWORD`` or save the password +in the macOS Keychain. A key supplied through ``ALEO_PRIVATE_KEY`` or +``ALEO_PRIVATE_KEY_FILE`` must also be supplied each run; it is never +saved by the profile. + +The client attempts to register with the hosted record scanner, +sharing the account's view key so the scanner can read its records. +For a custom record provider, construct ``ShieldSwap(aleo)`` instead. +Call ``onboard()`` to register a new account with Shield Swap before +trading. Client construction does not submit a trade. Args: - home: Profile directory; defaults to ``$SHIELD_SWAP_HOME`` or - ``~/.shield-swap``. - network: ``"mainnet"`` or ``"testnet"`` for a NEW profile; defaults - to testnet. - endpoint: Node API origin for a NEW profile. + home: Directory holding the profile and its saved work. Defaults to + ``SHIELD_SWAP_HOME``, then ``~/.shield-swap``. Use a separate + directory for each network. + network: ``"mainnet"`` or ``"testnet"``; defaults to testnet for a + new profile. An existing profile keeps its recorded network. + endpoint: API service root for a new profile; defaults to + ``https://edge.provable.com/api``. Ignored for an existing profile. + +Raises: + aleo.keystore.KeystoreError: The account cannot be opened. Check + ``code``: ``PASSWORD_REQUIRED`` means a password must be supplied; + ``ACCOUNT_NOT_FOUND`` means an existing profile's key is missing; + ``ADDRESS_MISMATCH`` means the selected key belongs to another + address. Restore the intended key before trying again. ### `onboard(self, referral_code: 'Optional[str]' = None) -> 'OnboardReport'` @@ -99,13 +131,19 @@ reports. Requires ``from_profile()``. ### Before doing anything: two questions -1. **Existing account?** When `status()` shows a brand-new, unregistered - profile, ask whether the user already has a shield-swap account before - creating anything — their funds and access live on the old key. - **NEVER ask the user to paste a private key into the conversation.** - They supply it out-of-band: `export SHIELD_SWAP_PRIVATE_KEY=...` (or - `SHIELD_SWAP_PRIVATE_KEY_FILE=path`) in their own shell before the - profile is first created. +1. **Existing account?** Ask before creating a profile: an existing + account's funds stay with its original key. Have the user import that key + in their own terminal with + `python -m aleo.keystore import --storage encrypted`, or use + `--storage keychain` on macOS. These protect the saved key; plaintext + storage leaves it readable to anyone with access to the account file. + After import, `Profile.load_or_create(create=False)` requires that account + rather than generating another key if setup is missing. + **Never ask for a private key in the conversation.** Do not run + `python -m aleo.keystore export` or read account files to inspect an + address; use `python -m aleo.keystore show` instead. An account supplied + through `ALEO_PRIVATE_KEY` or `ALEO_PRIVATE_KEY_FILE` must be supplied + each run; the profile does not save that key. 2. **Referral code — optional.** Access is granted by authentication alone; `onboard()` needs nothing from the user. Mention that a referral code from a friend can be passed (`onboard(referral_code=)`) @@ -184,7 +222,7 @@ where the signing keys live: | Building | Stack | Keys live | | --- | --- | --- | -| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A local private key (`ShieldSwap.from_profile()` manages it); delegated proving through the Provable prover — fees covered by default. | +| Bot / server / CLI / notebook | `aleo-sdk` facade + `shield-swap-sdk` (this package) | A saved Aleo account. Import an existing key to retain its funds, or create an account with Keychain or encrypted storage before calling `ShieldSwap.from_profile()`. Delegated proving uses the Provable prover; fees are covered by default. | | Agent integration | `aleo_shield_swap.agent` (Claude-shape tool schemas + `dispatch_tool`) or `python -m aleo_shield_swap.mcp` (MCP server), over the same client | Same as the underlying client; the tools bind to it. | | Browser dApp (wallet-signed) | The TypeScript stack: `@provablehq/shield-swap-sdk` + Veil react hooks — not this package | The user's wallet signs and proves. | diff --git a/shield-swap-sdk/python/aleo_shield_swap/__init__.py b/shield-swap-sdk/python/aleo_shield_swap/__init__.py index 66d8871a..9996cada 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/__init__.py +++ b/shield-swap-sdk/python/aleo_shield_swap/__init__.py @@ -14,18 +14,16 @@ amount_in=10**9).delegate() out = dex.claim_swap_output(handle).delegate() """ -_ALEO_SDK_MINIMUM = "0.8.0" +_ALEO_SDK_MINIMUM = "0.9.0" def _require_aleo_sdk() -> None: - """Fail at import, naming the fix, when the installed aleo-sdk predates ``aleo.inventory``. + """Report the required SDK upgrade before a caller tries to load an account. - Record management comes from ``aleo.inventory``, which first shipped in aleo-sdk 0.8.0 - (freeze-list proofs, from ``aleo.compliance``, arrived in 0.7.0). An older install would - otherwise fail on the first import of the client with a bare ``ModuleNotFoundError``. + Profiles need ``aleo.keystore``, available in aleo-sdk 0.9.0 and later. """ try: - import aleo.inventory # noqa: F401 + import aleo.keystore # noqa: F401 except ImportError as exc: from importlib.metadata import PackageNotFoundError, version try: @@ -118,7 +116,7 @@ def agent_guide() -> str: return files(__name__).joinpath("AGENTS.md").read_text() -__version__ = "0.8.0" +__version__ = "0.9.0" __all__ = [ "ShieldSwap", "AsyncShieldSwap", "ApiClient", "AsyncApiClient", diff --git a/shield-swap-sdk/python/aleo_shield_swap/client.py b/shield-swap-sdk/python/aleo_shield_swap/client.py index 09acbd15..bc10db04 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/client.py +++ b/shield-swap-sdk/python/aleo_shield_swap/client.py @@ -164,23 +164,54 @@ def __repr__(self) -> str: def from_profile(cls, home: Any = None, *, network: Optional[str] = None, endpoint: Optional[str] = None) -> "ShieldSwap": - """The client for the local participant profile (created on first use). + """Continue trading with the same account, credentials, and swap journal. - Wires endpoint, network, signer, and (when present) delegated-proving - credentials from ``$SHIELD_SWAP_HOME``/``~/.shield-swap``. Run - ``onboard()`` next on a fresh profile. + Use the same *home* on each run to retain pending swaps and saved API + credentials. On first use, the client uses an existing Aleo account + or creates one. To keep an existing address and its funds, import + that account before starting; see :meth:`Profile.load_or_create`. - *network* and *endpoint* apply only when the profile is being created — - an existing one keeps what it was created with, because its derived pool - keys and blinded identities are network-scoped and would not transfer. - Give each network its own home directory. + For a new account, use macOS Keychain or password encryption to + protect the private key. Set this up before building the client:: + + from aleo_shield_swap import Profile, ShieldSwap + + Profile.load_or_create(storage="encrypted") + dex = ShieldSwap.from_profile() + + This prompts for a password if none is supplied by the environment + or Keychain. It does not change an account's existing storage. + Without this setup, a generated key is saved as plaintext: anyone + who can read the account file can spend its funds. Use + ``storage="keychain"`` on macOS to keep the key outside the file. + + An encrypted account needs its password each time the client starts. + For unattended runs, set ``ALEO_ACCOUNT_PASSWORD`` or save the password + in the macOS Keychain. A key supplied through ``ALEO_PRIVATE_KEY`` or + ``ALEO_PRIVATE_KEY_FILE`` must also be supplied each run; it is never + saved by the profile. + + The client attempts to register with the hosted record scanner, + sharing the account's view key so the scanner can read its records. + For a custom record provider, construct ``ShieldSwap(aleo)`` instead. + Call ``onboard()`` to register a new account with Shield Swap before + trading. Client construction does not submit a trade. Args: - home: Profile directory; defaults to ``$SHIELD_SWAP_HOME`` or - ``~/.shield-swap``. - network: ``"mainnet"`` or ``"testnet"`` for a NEW profile; defaults - to testnet. - endpoint: Node API origin for a NEW profile. + home: Directory holding the profile and its saved work. Defaults to + ``SHIELD_SWAP_HOME``, then ``~/.shield-swap``. Use a separate + directory for each network. + network: ``"mainnet"`` or ``"testnet"``; defaults to testnet for a + new profile. An existing profile keeps its recorded network. + endpoint: API service root for a new profile; defaults to + ``https://edge.provable.com/api``. Ignored for an existing profile. + + Raises: + aleo.keystore.KeystoreError: The account cannot be opened. Check + ``code``: ``PASSWORD_REQUIRED`` means a password must be supplied; + ``ACCOUNT_NOT_FOUND`` means an existing profile's key is missing; + ``ADDRESS_MISMATCH`` means the selected key belongs to another + address. Restore the intended key before trying again. """ from aleo import Aleo, HTTPProvider @@ -204,7 +235,8 @@ def from_profile(cls, home: Any = None, *, pass # offline or scanner down — record methods will surface it dex = cls(aleo) dex.profile = profile - dex.journal = Journal(profile.journal_path) + # The ledger keeps homes that share this account off each other's counters. + dex.journal = Journal(profile.journal_path, counters=profile.counters_path) # Durable ss_ token first — session JWTs are short-lived and stale # ones would shadow a perfectly good API token. if creds.get("dex_api_token"): diff --git a/shield-swap-sdk/python/aleo_shield_swap/journal.py b/shield-swap-sdk/python/aleo_shield_swap/journal.py index 1ed8592f..57cfa374 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/journal.py +++ b/shield-swap-sdk/python/aleo_shield_swap/journal.py @@ -9,11 +9,16 @@ Counter reservation is the concurrency-critical piece: blinded identities must never collide, so counters are issued once, under an advisory file lock, and burned (never reused) when their swap fails. + +Profiles that trade from one account on one network share a counter ledger, +a second JSONL file outside every profile home. A journal opened with that +ledger issues counters through it, so two homes never issue the same one. """ from __future__ import annotations import fcntl import json +import os import time from contextlib import contextmanager from pathlib import Path @@ -55,11 +60,23 @@ class Journal: path: Where the log lives, usually ``Profile.journal_path``. Its parent is created on first append, alongside a ``.lock`` sibling used to serialize writers. + counters: Ledger of the counters issued for this journal's account, + usually ``Profile.counters_path``. Every journal opened with the + same ledger issues counters through it, so profile homes that + share an account never issue the same counter. The ledger holds + counter numbers and timestamps only; swaps and blinding factors + stay in *path*. Opening the journal reads both files and, when + *path* records counters the ledger lacks, retires them in the + ledger. Defaults to None: counters are then coordinated only + among users of *path*. """ - def __init__(self, path: "Path | str") -> None: + def __init__(self, path: "Path | str", *, counters: "Path | str | None" = None) -> None: self.path = Path(path) self._lock_path = self.path.with_suffix(".lock") + self._ledger = Journal(counters) if counters is not None else None + # Counters issued before this journal used the ledger may still be pending. + self._publish_counters() def __repr__(self) -> str: return f"Journal({str(self.path)!r})" @@ -113,17 +130,85 @@ def events(self) -> list[dict[str, Any]]: # ── Counters ───────────────────────────────────────────────────────────── + @contextmanager + def _counters_locked(self) -> Iterator[None]: + """Hold every lock a counter change needs. + + Takes the ledger's lock before this journal's, in that order on every + path, so journals sharing a ledger cannot deadlock. Takes one lock + when both are the same file. Creates the + ledger's directory for its owner only: the file names in it are the + addresses this user trades from. + """ + if self._ledger is None: + with self._locked(): + yield + return + self._ledger.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + self.path.parent.mkdir(parents=True, exist_ok=True) + with self._ledger._lock_path.open("a") as outer, self._lock_path.open("a") as inner: + # Two file names can derive one lock file, such as journal.jsonl and + # journal.counters. A second lock on it would wait on the first forever. + shared = os.path.sameopenfile(outer.fileno(), inner.fileno()) + fcntl.flock(outer, fcntl.LOCK_EX) + try: + if not shared: + fcntl.flock(inner, fcntl.LOCK_EX) + try: + yield + finally: + if not shared: + fcntl.flock(inner, fcntl.LOCK_UN) + finally: + fcntl.flock(outer, fcntl.LOCK_UN) + + def _write_counter_event(self, event: dict[str, Any]) -> None: + """Append a counter event to the ledger, then to this journal. + + The caller holds :meth:`_counters_locked`. The ledger is written + first: a crash between the two writes leaves a counter that no + journal uses, never one that two journals use. + """ + line = json.dumps(event) + "\n" + for journal in (self._ledger, self): + if journal is not None: + with journal.path.open("a") as f: + f.write(line) + + def _publish_counters(self) -> None: + """Retire this journal's counters in the ledger when the ledger is behind. + + A journal holds counters the ledger did not issue when it reserved + them before it was opened with a ledger, or recorded a swap on an + identity the caller chose. Their swaps may not have finalized, so + the chain cannot report them to the other journals; this does. + + Reads both files. Takes the locks and appends one + ``counters_skipped`` event to the ledger only when the ledger is + behind; otherwise writes nothing. + """ + if self._ledger is None or self._own_cursor() <= self._ledger.counter_cursor(): + return + with self._counters_locked(): + through = self._own_cursor() - 1 + if through >= self._ledger.counter_cursor(): + event = {"type": "counters_skipped", "ts": time.time(), "through": through} + with self._ledger.path.open("a") as f: + f.write(json.dumps(event) + "\n") + def reserve_counters(self, n: int) -> list[int]: - """Issue the next *n* counters, exactly once, under a file lock.""" + """Issue the next *n* counters, exactly once, under a file lock. + + With a counter ledger, the counters are also unique among every + journal that shares the ledger. + """ if n <= 0: return [] - with self._locked(): + with self._counters_locked(): start = self.counter_cursor() counters = list(range(start, start + n)) - event = {"type": "counters_reserved", "ts": time.time(), - "counters": counters} - with self.path.open("a") as f: # already under the lock - f.write(json.dumps(event) + "\n") + self._write_counter_event({"type": "counters_reserved", "ts": time.time(), + "counters": counters}) return counters def skip_counters_through(self, counter: int) -> None: @@ -132,17 +217,26 @@ def skip_counters_through(self, counter: int) -> None: A fresh journal for an account that already swapped starts at 0, but those counters are consumed on chain — a swap built on one is rejected at finalize. The client seeds the cursor past the used run with this; - it never moves the cursor backwards. + it never moves the cursor backwards. With a counter ledger, the run + is retired for every journal that shares the ledger. """ - with self._locked(): + with self._counters_locked(): if counter < self.counter_cursor(): return - event = {"type": "counters_skipped", "ts": time.time(), "through": counter} - with self.path.open("a") as f: # already under the lock - f.write(json.dumps(event) + "\n") + self._write_counter_event({"type": "counters_skipped", "ts": time.time(), + "through": counter}) def counter_cursor(self) -> int: - """Next unissued counter (max seen in any event + 1).""" + """Next unissued counter (max seen in any event + 1). + + With a counter ledger, counts the counters issued to every journal + that shares it as well as this journal's own. + """ + cursor = self._own_cursor() + return cursor if self._ledger is None else max(cursor, self._ledger.counter_cursor()) + + def _own_cursor(self) -> int: + """Next counter past every one this journal's own file records.""" top = -1 for e in self.events(): if e["type"] == "counters_reserved": @@ -169,6 +263,7 @@ def record_swap(self, handle: SwapHandle, counter: int) -> None: """ self.append("swap", counter=counter, pool_keys=list(handle.pool_keys), **{k: getattr(handle, k) for k in _HANDLE_FIELDS}) + self._publish_counters() # the caller may have chosen the identity def record_swap_failed(self, counter: int, error: str) -> None: """Burn a counter whose swap never landed. @@ -182,6 +277,7 @@ def record_swap_failed(self, counter: int, error: str) -> None: error: Why the swap failed, kept for diagnosis. """ self.append("swap_failed", counter=counter, error=error) + self._publish_counters() def record_claim(self, swap_id: str, transaction_id: str, amount_out: int) -> None: diff --git a/shield-swap-sdk/python/aleo_shield_swap/mcp.py b/shield-swap-sdk/python/aleo_shield_swap/mcp.py index 6d395060..91bc492f 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/mcp.py +++ b/shield-swap-sdk/python/aleo_shield_swap/mcp.py @@ -1,24 +1,34 @@ -"""MCP server exposing shield_swap as tools (the ``[mcp]`` extra). +"""Use Shield Swap from an MCP client. -Run: ``python -m aleo_shield_swap.mcp`` +Install ``shield-swap-sdk[mcp]`` and run +``python -m aleo_shield_swap.mcp``. By default, the server uses the local +profile to retain the account, API credentials, and unfinished swaps +between sessions. -Uses the low-level ``mcp.server.Server`` (not FastMCP) so each tool -advertises the exact JSON schema from :func:`~aleo_shield_swap.agent -.shield_swap_tools` — FastMCP infers schemas from handler signatures, which -would collapse every tool to one opaque ``args`` object. Tools run against -the synchronous :class:`~aleo_shield_swap.client.ShieldSwap` (its full method -surface) in a worker thread, keeping the event loop free. +Set up the account before starting the server. Import an existing account +to keep its address and funds, or create one for a separate address. +Use macOS Keychain or encrypted storage to protect the private key; see +:meth:`~aleo_shield_swap.profile.Profile.load_or_create`. Without setup, +the first run can create an account with its key stored as plaintext. + +An encrypted account needs ``ALEO_ACCOUNT_PASSWORD`` or a password saved +in the macOS Keychain: a server connected over stdio cannot answer a +password prompt. Environment: - ALEO_ENDPOINT API service root (default ``https://edge.provable.com/api``, no credentials — - the provider derives ``/v2`` reads, ``/prove``, and - ``/scanner`` from it) - ALEO_PRIVATE_KEY Explicit signer (overrides the profile); without it - the server binds ShieldSwap.from_profile() — - ~/.shield-swap key material, journal, credentials - ALEO_NETWORK ``testnet`` (default) or ``mainnet`` + SHIELD_SWAP_HOME Profile directory; defaults to ``~/.shield-swap``. + ALEO_ACCOUNT Account name; defaults to the profile's saved name, + then ``default``. + ALEO_ACCOUNTS_DIR Account directory; defaults to ``~/.aleo/accounts``. + ALEO_PRIVATE_KEY Use this key directly, without the profile's journal + or credentials. Supply it again on each server start. + ALEO_ENDPOINT API service root for a direct-key client; defaults to + ``https://edge.provable.com/api``. + ALEO_NETWORK ``testnet`` (default) or ``mainnet`` for a direct-key + client. A profile keeps its recorded network. ALEO_E2E_API_KEY / ALEO_E2E_CONSUMER_ID - Delegated-proving + hosted-scanner credentials + Optional service credentials for a direct-key client. + A profile uses its saved credentials instead. """ from __future__ import annotations @@ -84,17 +94,17 @@ def _build_dex() -> Any: if pk: aleo.default_account = aleo.account.from_private_key(pk) return ShieldSwap(aleo) - # No explicit key: bind the local participant profile (created on first - # use), so MCP agents get persistence — journal, counters, credentials. + # Keep pending swaps and credentials available when the MCP client restarts. return ShieldSwap.from_profile() def main() -> None: - """Serve the shield_swap MCP tools over stdio until the client disconnects. + """Serve Shield Swap tools until the MCP client disconnects. - Builds a DEX client first, which binds a key from ``ALEO_PRIVATE_KEY`` or - else creates/loads the local participant profile on disk. Blocks for the - lifetime of the server; requires the ``[mcp]`` extra. + Requires ``shield-swap-sdk[mcp]``. Prepare the account and any password + before starting; see the module's setup instructions. Without + ``ALEO_PRIVATE_KEY``, the server uses the saved profile and journal. + Setting that variable starts a client without profile persistence. """ import anyio from mcp.server.stdio import stdio_server diff --git a/shield-swap-sdk/python/aleo_shield_swap/profile.py b/shield-swap-sdk/python/aleo_shield_swap/profile.py index 94bd27b9..d4deecf7 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/profile.py +++ b/shield-swap-sdk/python/aleo_shield_swap/profile.py @@ -1,21 +1,33 @@ -"""On-disk participant profile — key material, credentials, journal location. +"""Keep a trading account and its saved work available between runs. -One profile per home directory (``$SHIELD_SWAP_HOME`` or ``~/.shield-swap``). -``Profile.load_or_create()`` generates key material on first use and reuses -it forever after; credentials (JWT, delegated-proving keys) are stored -separately so they can be refreshed without touching the key. +A profile ties one Aleo address to a directory containing API credentials +and a swap journal. Reuse that directory to continue trading and collect +pending swaps. The default is ``SHIELD_SWAP_HOME``, then ``~/.shield-swap``. + +New profiles store the address and account name in ``profile.json``. The +private key is loaded through ``aleo.keystore`` or supplied through the +environment. Use macOS Keychain or encrypted account storage to protect a +saved key; see :meth:`Profile.load_or_create`. """ from __future__ import annotations import json +import logging import os +import threading from pathlib import Path -from typing import Any, Optional +from typing import Any, Optional, cast DEFAULT_ENDPOINT = "https://edge.provable.com/api" _PROFILE = "profile.json" _CREDENTIALS = "credentials.json" +_log = logging.getLogger(__name__) + +# Avoid repeating the migration warning when several objects load one profile. +_legacy_notices: set[str] = set() +_legacy_notices_lock = threading.Lock() + def _write_private(path: Path, payload: dict[str, Any]) -> None: """Owner-only file, written atomically (no umask window, no torn reads).""" @@ -26,58 +38,115 @@ def _write_private(path: Path, payload: dict[str, Any]) -> None: os.replace(tmp, path) -def _initial_key(network: str) -> tuple[str, str]: - """(private_key, address) for a new profile. +def _selected_account_name(account: Optional[str]) -> str: + """Choose a name to record when no account file supplies one. - Imports ``SHIELD_SWAP_PRIVATE_KEY`` (or a path in - ``SHIELD_SWAP_PRIVATE_KEY_FILE``) when set — users with an existing - account supply their key out-of-band, never pasted into a conversation - — and generates a fresh random account otherwise. + Use the same defaults as the keystore: ``account``, then a nonempty + ``ALEO_ACCOUNT``, then ``default``. """ - import aleo - net = getattr(aleo, network) - key = (os.environ.get("SHIELD_SWAP_PRIVATE_KEY") or "").strip() - key_file = os.environ.get("SHIELD_SWAP_PRIVATE_KEY_FILE") - if not key and key_file: - key = Path(key_file).read_text().strip() - pk = net.PrivateKey.from_string(key) if key else net.PrivateKey.random() - return str(pk), str(pk.address) + return account if account is not None else (os.environ.get("ALEO_ACCOUNT") or "default") -class Profile: - """A participant's persistent identity and credentials. +def _counters_root() -> Path: + """Return the directory of the counter ledgers shared by this user's profile homes.""" + return Path.home() / ".aleo" / "shield-swap" / "counters" - Holds exactly one Aleo address, generated on first use and reused every - session after. For several addresses, create a profile per address — each - needs its own home directory (``SHIELD_SWAP_HOME``, or *home* on - :meth:`load_or_create`), since the journal and credentials are per-profile - too. - Load with :meth:`load_or_create`; the profile is created (with fresh key - material) when the home directory has none yet. The same call does both, - so callers never branch on whether one exists:: +def _same_directory(first: Path, second: Path) -> bool: + """Report whether two paths name one directory, following symbolic links.""" + try: + return os.path.samefile(first, second) + except OSError: + # A directory that does not exist yet is compared by its resolved path. + return os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)) - from pathlib import Path - from aleo_shield_swap import Profile - # First run: generates a key and writes it owner-only. - profile = Profile.load_or_create() - print(profile.address) # aleo1… +def _reject_account_in_profile_files(home: Path, name: str, + accounts_dir: "Path | str | None") -> None: + """Refuse an account file that is also one of the profile's own files. + + The keystore stores an account as ``.json``. When the accounts + directory is the profile home, the names ``profile`` and ``credentials`` + select ``profile.json`` and ``credentials.json``, and writing either + file would replace the stored key. Reads the environment and resolves + paths; writes nothing. + + Raises: + ValueError: The selected account file is ``profile.json`` or + ``credentials.json`` in ``home``. + """ + if f"{name}.json" not in (_PROFILE, _CREDENTIALS): + return + # Resolve the directory as the keystore does: argument, variable, then default. + directory = Path(accounts_dir or os.environ.get("ALEO_ACCOUNTS_DIR") + or Path.home() / ".aleo" / "accounts").expanduser() + if _same_directory(directory, home): + raise ValueError( + f'The account "{name}" in {directory} would be stored as {home / (name + ".json")}, ' + "a file this profile writes its own data to. Choose another account name, or an " + "accounts directory other than the profile home.") + + +def _report_legacy_key(path: Path, address: str) -> None: + """Point callers to the migration command for a key still in profile.json. + + Report each file once per process without including the key. + """ + with _legacy_notices_lock: + if str(path) in _legacy_notices: + return + _legacy_notices.add(str(path)) + _log.warning( + "The private key of %s is still stored in %s; `python -m aleo.keystore migrate --from %s` " + "copies it into an account file shared by the Aleo tools (add --remove-legacy-key to take " + "it out of profile.json).", + address, path, path) + - # Every run after: the same call returns that key, unchanged. - assert Profile.load_or_create().address == profile.address +class Profile: + """Reuse an account and its trading history across sessions. + + Load the same profile on each run to keep its address, API credentials, + and swap journal together. A profile belongs to one address and one + network; give a separate account or network its own home directory. - # A second address needs its own home; "~/..." is expanded. - other = Profile.load_or_create("~/.shield-swap-alt") + Use :meth:`load_or_create` to open the profile. If an account already + exists, the profile uses it. Otherwise it generates a key. For a new + key, choose password encryption or macOS Keychain storage:: - That last call generates a fresh key only when no key is being imported; - with ``SHIELD_SWAP_PRIVATE_KEY`` set, every new home adopts that one key - instead, so all of them share an address. + from aleo_shield_swap import Profile + + profile = Profile.load_or_create(storage="encrypted") + address = profile.address + + The first run asks for an encryption password unless one was supplied. + Later runs need that password to unlock the key. On macOS, + ``storage="keychain"`` keeps the key in Keychain instead of the account + file. The default, ``"plaintext"``, leaves the key readable to anyone + with access to the file. Passing ``storage`` does not convert an + existing account; use ``python -m aleo.keystore protect`` for that. + + A second home directory alone does not create a separate account: + profiles selecting the same account name share its key. To trade from + another address, use a separate home and ``account`` name, and clear + any key variables that still select the first account. + + Homes that share an account on one network issue swap counters through + one file, :attr:`counters_path`, so their swaps never reuse a blinded + identity. Each home keeps its own journal: collect a swap from the home + that made it. """ def __init__(self, home: Path, data: dict[str, Any]) -> None: self.home = home self._data = data + # Retain these options so inspecting a profile does not require unlocking it. + self._account: Optional[str] = None + self._accounts_dir: "Path | str | None" = None + self._password: Optional[str] = None + # Reuse the unlocked key for this object instead of prompting on every read. + self._private_key: Optional[str] = None + self._key_lock = threading.Lock() def __repr__(self) -> str: return f"Profile({self.address!r}, home={str(self.home)!r})" @@ -99,39 +168,151 @@ def default_home() -> Path: @classmethod def load_or_create(cls, home: "Path | str | None" = None, *, network: str = "testnet", - endpoint: str = DEFAULT_ENDPOINT) -> "Profile": - """Load the profile at *home*, creating one with fresh keys if absent. - - Creating a profile writes a private key to disk at mode 600; an existing - profile file has its mode tightened to 600 on load, healing a loose one. - The key comes from ``SHIELD_SWAP_PRIVATE_KEY`` (or the file named by - ``SHIELD_SWAP_PRIVATE_KEY_FILE``) when set, so a user with an existing - account supplies it out-of-band rather than pasting it into a chat. - - *network* and *endpoint* apply only when creating — they are ignored for an - existing profile, which keeps the values it was created with. + endpoint: str = DEFAULT_ENDPOINT, + create: bool = True, + storage: str = "plaintext", + account: Optional[str] = None, + accounts_dir: "Path | str | None" = None, + password: Optional[str] = None, + save_password: bool = False) -> "Profile": + """Open a trading profile, creating one if this is its first run. + + To keep an existing address and its funds, import its key with + ``python -m aleo.keystore import --storage encrypted`` first, then + load the profile with ``create=False``. On macOS, ``--storage keychain`` + keeps the key in Keychain. Import keys in a terminal, never in a chat. + ``create=False`` permits a new profile but requires an existing key. + + To start with a separate address, choose an unused account name and + profile home. Use ``storage="keychain"`` on macOS or + ``storage="encrypted"`` to protect a newly generated key. The default + is plaintext, which leaves the private key readable in the account + file. ``storage`` applies only when generating a key; it does not + change an existing account. ``python -m aleo.keystore protect`` can + change storage while keeping the address and funds. + + The profile records its address, account name, network, and endpoint + in ``profile.json``. Creating it does not contact the network or move + funds. When several processes create the same missing account at + once, one key is saved and every profile uses it. An existing profile keeps its recorded settings and can be + opened without a password; its key is unlocked on the first read of + :attr:`private_key`. + + Keys supplied through ``ALEO_PRIVATE_KEY`` or ``ALEO_PRIVATE_KEY_FILE`` + take precedence over saved keys and are never copied to disk. Supply + the key again on each run, or import it once to save it. + ``SHIELD_SWAP_PRIVATE_KEY`` and ``SHIELD_SWAP_PRIVATE_KEY_FILE`` are + also accepted. Any supplied key must match the profile's address + and, if present, the selected account file. Args: - home: Profile directory; defaults to :meth:`default_home`. - network: Network to bind a NEW profile to. - endpoint: API endpoint to record on a NEW profile. + home: Directory for the profile, credentials, and swap journal. + Defaults to ``SHIELD_SWAP_HOME``, then ``~/.shield-swap``. + network: ``"testnet"`` (default) or ``"mainnet"`` for a new profile. + An existing profile keeps its network; use another home to + trade on a different network. + endpoint: API service root for a new profile. Defaults to + ``https://edge.provable.com/api``; ignored for an existing profile. + create: Generate and save a key if none is found for a new profile. + Defaults to True. Use False to require an existing account. + storage: Protection for a generated key. ``"encrypted"`` encrypts + the key in the account file and requires a password to unlock + it. ``"keychain"`` stores the key in macOS Keychain, outside + the file. ``"plaintext"`` (default) restricts file permissions + but does not encrypt the key or protect a copied file. The + address remains readable in every mode. ``"none"`` is rejected + because the generated key would be lost when the process exits. + account: Name of the saved account. Defaults to ``ALEO_ACCOUNT``, + then the profile's saved name, then ``default``. Use a distinct + name as well as a distinct home for each separate account. + accounts_dir: Directory containing account files. Defaults to + ``ALEO_ACCOUNTS_DIR``, then ``~/.aleo/accounts``. This location + is not saved in the profile; supply it on each run. + password: Password to unlock an encrypted account or protect a new + key. If omitted, uses ``ALEO_ACCOUNT_PASSWORD``, then a password + saved in macOS Keychain, then a hidden terminal prompt. + save_password: Save a new encrypted account's password in macOS + Keychain so later runs can unlock it without a prompt. + Defaults to False; applies only when generating a key. Returns: - The loaded or newly created profile. + The profile for the recorded address. For an existing profile, + opening it does not check whether its key is available; read + :attr:`private_key` when it is needed for signing. + + Raises: + aleo.keystore.KeystoreError: A new profile cannot open or save its + account. Check ``code``: ``ACCOUNT_NOT_FOUND`` with + ``create=False`` means the account must be imported or supplied; + ``PASSWORD_REQUIRED`` or ``WRONG_PASSWORD`` requires a valid + password; ``ADDRESS_MISMATCH`` means the supplied key belongs + to another account. Other codes identify invalid key sources, + names, or unavailable storage. An existing profile reports key + errors when :attr:`private_key` is read. + ValueError: The account file would be ``profile.json`` or + ``credentials.json`` in ``home``: the account is named + ``profile`` or ``credentials`` and the accounts directory is + the profile home. The name is the one that selects the + account, including the name saved in an existing profile. + Nothing is written. Choose another name or another accounts + directory. """ - # expanduser: a "~/..." string is otherwise taken literally, creating a - # directory named ~ in the cwd and writing the private key there. + # Treat ~ as the user's home, including paths passed directly from Python. home = Path(home).expanduser() if home is not None else cls.default_home() + _reject_account_in_profile_files(home, _selected_account_name(account), accounts_dir) path = home / _PROFILE if path.exists(): path.chmod(0o600) # heal a pre-existing loose mode - return cls(home, json.loads(path.read_text())) - home.mkdir(parents=True, exist_ok=True) - private_key, address = _initial_key(network) - data = {"address": address, "private_key": private_key, - "network": network, "endpoint": endpoint} - _write_private(path, data) - return cls(home, data) + profile = cls(home, json.loads(path.read_text())) + # Allow address and credential reads before the account is unlocked. + profile._account = account + profile._accounts_dir = accounts_dir + profile._password = password + # The name saved in the profile selects the account when nothing else does. + saved = profile._data.get("account") + if account is None and not os.environ.get("ALEO_ACCOUNT") and isinstance(saved, str): + _reject_account_in_profile_files(home, saved, accounts_dir) + else: + import aleo + from aleo import keystore + net = getattr(aleo, network) + + def existing() -> "tuple[str, str, str]": + loaded = keystore.load(name=account, dir=accounts_dir, password=password) + # Remember the account name even when the key is supplied per run. + name = loaded.stored.name if loaded.stored is not None else _selected_account_name(account) + return loaded.private_key, loaded.address, name + + try: + private_key, address, name = existing() + except keystore.KeystoreError as error: + if error.code != "ACCOUNT_NOT_FOUND" or not create: + raise + if storage == "none": + raise keystore.KeystoreError( + "UNSUPPORTED_STORAGE", + 'A new account cannot be created with storage "none": nothing would hold its key ' + 'after this process exits. Choose "plaintext", "keychain" or "encrypted".', + ) from None + private_key = str(net.PrivateKey.random()) + try: + stored = keystore.save(private_key, name=account, dir=accounts_dir, + storage=cast(Any, storage), # save() validates storage. + password=password, save_password=save_password) + address, name = stored.address, stored.name + except keystore.KeystoreError as lost: + if lost.code != "ACCOUNT_EXISTS": + raise + # Another process stored this account after the lookup found + # none. Use its key; the key generated here was never saved. + private_key, address, name = existing() + home.mkdir(parents=True, exist_ok=True) + data = {"address": address, "account": name, + "network": network, "endpoint": endpoint} + _write_private(path, data) + profile = cls(home, data) + profile._private_key = private_key + return profile # ── Identity ───────────────────────────────────────────────────────────── @@ -142,12 +323,61 @@ def address(self) -> str: @property def private_key(self) -> str: - """The profile's private key, read from disk. - - Whoever holds this controls the account and can decrypt its records — do - not log it, echo it into a conversation, or send it to a service. + """Unlock the account's private key for signing. + + The key gives control of the account's funds and can decrypt its + records. Keep it out of logs, conversations, and service requests. + + For an existing profile, the first read loads the key and checks + that it belongs to :attr:`address`. An encrypted account may ask + for its password. Later reads reuse the unlocked key for this + object's lifetime, so changes to key variables or files take effect + only after loading another profile object. + + A key in ``ALEO_PRIVATE_KEY`` or ``ALEO_PRIVATE_KEY_FILE`` is used + before the saved account. Account selection follows the ``account`` + argument, ``ALEO_ACCOUNT``, the profile's saved name, then ``default``. + An older profile containing a private key still works when no other + key source or account file exists. Using that key logs a migration + command once per profile file per process; it does not move or delete + the key. + + Raises: + aleo.keystore.KeystoreError: Check ``code`` to decide what to supply. + ``ACCOUNT_NOT_FOUND`` means the key is missing; + ``KEY_NOT_STORED`` means the account file contains only an + address. Import or supply the original key in either case. + ``PASSWORD_REQUIRED`` or ``WRONG_PASSWORD`` means an encrypted + account needs its password. ``ADDRESS_MISMATCH`` means the key + belongs to another address; the message names both addresses. + ``EMPTY_KEY_SOURCE`` or ``KEY_CONFLICT`` identifies empty or + conflicting key variables. """ - return self._data["private_key"] + if self._private_key is None: + with self._key_lock: + if self._private_key is None: + self._private_key = self._resolve_private_key() + return self._private_key + + def _resolve_private_key(self) -> str: + """Load a key that matches the saved address before allowing it to sign.""" + from aleo import keystore + + # Passing the saved name would override ALEO_ACCOUNT in keystore.load(). + # Use it only when neither the caller nor the environment selects a name. + name = self._account + if name is None and not os.environ.get("ALEO_ACCOUNT"): + name = self._data.get("account") + loaded = keystore.load( + name=name, dir=self._accounts_dir, + # Keep older profiles usable until their keys are migrated. + legacy_key=self._data.get("private_key") or None, + expected_address=self.address, + password=self._password) + if loaded.source == "legacy": + _report_legacy_key(self.home / _PROFILE, self.address) + self._password = None # Release the password reference after unlocking. + return loaded.private_key @property def network(self) -> str: @@ -196,3 +426,20 @@ def journal_path(self) -> Path: on first append. """ return self.home / "journal.jsonl" + + @property + def counters_path(self) -> Path: + """Where the swap counters issued for this account are recorded. + + The file is ``~/.aleo/shield-swap/counters//
.jsonl``, + outside the profile home. Every profile on this machine that trades + from the same address on the same network shares it, so their swaps + never use the same counter. It holds counter numbers and timestamps; + swaps and their claim secrets stay in :attr:`journal_path`. Its + directory is created for the owner only, because the file names in + it are addresses. + + Returns the path whether or not the file exists — the journal creates + it when it first issues a counter. + """ + return _counters_root() / self.network / f"{self.address}.jsonl" diff --git a/shield-swap-sdk/tests/conftest.py b/shield-swap-sdk/tests/conftest.py index 909a8b83..ea5f3f19 100644 --- a/shield-swap-sdk/tests/conftest.py +++ b/shield-swap-sdk/tests/conftest.py @@ -8,9 +8,106 @@ """ from __future__ import annotations +import re +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Tuple + import pytest -SLOT_TEXT = ("{ tick: 4055i32, tick_spacing: 60u32, " +# Clear these variables so tests cannot select a real account or profile. +ACCOUNT_VARIABLES = ( + "ALEO_PRIVATE_KEY", + "ALEO_PRIVATE_KEY_FILE", + "ALEO_ACCOUNT", + "ALEO_ACCOUNTS_DIR", + "ALEO_ACCOUNT_PASSWORD", + "SHIELD_SWAP_PRIVATE_KEY", + "SHIELD_SWAP_PRIVATE_KEY_FILE", + "SHIELD_SWAP_HOME", +) + + +class FakeKeychain: + """Test Keychain storage without reading or changing macOS Keychain. + + Keep entries in memory and accept the add, find, and delete commands + used by the keystore. + """ + + def __init__(self) -> None: + self.entries: Dict[str, str] = {} + + def run(self, args: Sequence[str], stdin: Optional[str] = None) -> Tuple[Optional[int], str]: + args = list(args) + if args == ["-i"]: + match = re.fullmatch(r"add-generic-password -U -s (\S+) -a (\S+) -l (\S+) -w (\S+)\n", stdin or "") + if match is None: + return 1, "" + self.entries[f"{match.group(1)} {match.group(2)}"] = match.group(4) + return 0, "" + if len(args) == 6 and args[0] == "find-generic-password" and args[1] == "-s" and args[3] == "-a" and args[5] == "-w": + value = self.entries.get(f"{args[2]} {args[4]}") + return (44, "") if value is None else (0, f"{value}\n") + if len(args) == 5 and args[0] == "delete-generic-password" and args[1] == "-s" and args[3] == "-a": + return (44, "") if self.entries.pop(f"{args[2]} {args[4]}", None) is None else (0, "") + return 1, "" + + +class AccountSandbox: + """Keep a test's account files, Keychain entries, and notices together. + + Attributes: + home: Temporary home used to resolve default account and profile paths. + accounts: Account files created by the test, under ``/.aleo/accounts``. + keychain: In-memory entries available for assertions. + notes: Captured terminal notices, in the order they were written. + """ + + def __init__(self, home: Path) -> None: + self.home = home + self.accounts = home / ".aleo" / "accounts" + self.keychain = FakeKeychain() + self.notes: List[str] = [] + + +def _no_prompt(message: str) -> str: + raise AssertionError("unexpected prompt") + + +@pytest.fixture(autouse=True) +def account_sandbox(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory, + monkeypatch: pytest.MonkeyPatch) -> AccountSandbox: + """Isolate account tests from real keys and passwords. + + Clear account variables, redirect keystore files to a temporary home, + and replace Keychain access with an in-memory fake. Reject prompts so + a missing test password fails instead of waiting for input. Offline + tests also use the temporary home for profile files. + """ + from aleo.keystore._runtime import runtime + + for name in ACCOUNT_VARIABLES: + monkeypatch.delenv(name, raising=False) + box = AccountSandbox(tmp_path_factory.mktemp("account-home")) + monkeypatch.setattr(runtime, "home", lambda: str(box.home)) + monkeypatch.setattr(runtime, "security", box.keychain.run) + monkeypatch.setattr(runtime, "terminal_attached", lambda: False) + monkeypatch.setattr(runtime, "prompt_hidden", _no_prompt) + monkeypatch.setattr(runtime, "prompt_visible", _no_prompt) + monkeypatch.setattr(runtime, "notify", box.notes.append) + # Live and devnode tests need the existing proving-parameter cache. + # Keep their HOME while redirecting all keystore access above. + if request.node.get_closest_marker("live") is None and request.node.get_closest_marker("devnode") is None: + monkeypatch.setenv("HOME", str(box.home)) + monkeypatch.setenv("USERPROFILE", str(box.home)) + else: + # Keep counter ledgers out of the real home, which these tests retain. + from aleo_shield_swap import profile + monkeypatch.setattr(profile, "_counters_root", lambda: box.home / ".aleo" / "shield-swap" / "counters") + return box + + +SLOT_TEXT =("{ tick: 4055i32, tick_spacing: 60u32, " "sqrt_price: { hi: 1u128, lo: 0u128 }, " "fee_protocol: 0u8, liquidity: 1000u128, " "fee_growth_global0_x_128: { hi: 0u128, lo: 0u128 }, " diff --git a/shield-swap-sdk/tests/integration/test_agent_lifecycle_live.py b/shield-swap-sdk/tests/integration/test_agent_lifecycle_live.py index ab715d49..238e4893 100644 --- a/shield-swap-sdk/tests/integration/test_agent_lifecycle_live.py +++ b/shield-swap-sdk/tests/integration/test_agent_lifecycle_live.py @@ -23,10 +23,8 @@ def test_full_lifecycle_from_fresh_profile(tmp_path, monkeypatch): - # Prove the participant path: credentials must SELF-provision and the - # profile key must be genuinely fresh (a developer shell may carry - # SHIELD_SWAP_PRIVATE_KEY, which would import a funded, already-redeemed - # account and void every "fresh account" assertion below). + # Require onboarding to obtain credentials for a new account. Credentials + # or keys inherited from the shell could skip the stages tested below. monkeypatch.delenv("ALEO_E2E_API_KEY", raising=False) monkeypatch.delenv("ALEO_E2E_CONSUMER_ID", raising=False) monkeypatch.delenv("SHIELD_SWAP_PRIVATE_KEY", raising=False) diff --git a/shield-swap-sdk/tests/integration/test_swap_lifecycle.py b/shield-swap-sdk/tests/integration/test_swap_lifecycle.py index 50889f23..f1337dc5 100644 --- a/shield-swap-sdk/tests/integration/test_swap_lifecycle.py +++ b/shield-swap-sdk/tests/integration/test_swap_lifecycle.py @@ -222,7 +222,7 @@ def test_concurrent_swaps_reserve_distinct_identities(tmp_path, monkeypatch): monkeypatch.setenv("ALEO_E2E_CONSUMER_ID", cid) monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY", os.environ["ALEO_E2E_PRIVATE_KEY"]) dex = ShieldSwap.from_profile(tmp_path / "home") - report = dex.onboard() # imports the funded account; no-op stages skip + report = dex.onboard() # Reuse completed onboarding stages for the funded account. assert report.funded held = {tid: v for tid, v in dex.status().balances.items() if v.get("private", 0) > 0} diff --git a/shield-swap-sdk/tests/test_first_swap_account.py b/shield-swap-sdk/tests/test_first_swap_account.py index e1d1cc6a..9d19425d 100644 --- a/shield-swap-sdk/tests/test_first_swap_account.py +++ b/shield-swap-sdk/tests/test_first_swap_account.py @@ -1,4 +1,4 @@ -"""The runnable example saves generated keys before scanner or faucet I/O.""" +"""Check that the example reuses its account before contacting a service.""" import json import runpy from pathlib import Path @@ -11,21 +11,25 @@ EXAMPLE = Path(__file__).parents[1] / "examples/first-swap/swap.py" -def test_example_reuses_persisted_key_before_network(tmp_path, monkeypatch): - monkeypatch.delenv("SHIELD_SWAP_PRIVATE_KEY", raising=False) - monkeypatch.delenv("SHIELD_SWAP_PRIVATE_KEY_FILE", raising=False) +def test_example_reuses_stored_account_before_network(tmp_path, monkeypatch, account_sandbox): monkeypatch.setattr(Profile, "default_home", staticmethod(lambda: tmp_path)) # Stop at client construction, before registration/authentication/funding. monkeypatch.setattr("aleo.Aleo", Mock(side_effect=RuntimeError("stop before I/O"))) - for _ in range(2): + account_file = account_sandbox.accounts / "default.json" + for run in range(2): with pytest.raises(RuntimeError, match="stop before I/O"): runpy.run_path(str(EXAMPLE), run_name="__main__") saved = json.loads((tmp_path / "profile.json").read_text()) - if _ == 0: - first_key = saved["private_key"] - assert saved["private_key"] == first_key - assert saved["network"] == "testnet" + stored = json.loads(account_file.read_text()) + if run == 0: + first_address, first_account = saved["address"], account_file.read_bytes() + # A restart must keep both the saved address and its original key. + assert saved == {"address": first_address, "account": "default", "network": "testnet", + "endpoint": "https://edge.provable.com/api"} + assert stored["address"] == first_address and stored["key"]["type"] == "plaintext" + assert account_file.read_bytes() == first_account assert (tmp_path / "profile.json").stat().st_mode & 0o777 == 0o600 + assert account_file.stat().st_mode & 0o777 == 0o600 def test_example_uses_explicit_key_without_loading_profile(monkeypatch): diff --git a/shield-swap-sdk/tests/test_gen_context.py b/shield-swap-sdk/tests/test_gen_context.py index 16caf56e..581856ae 100644 --- a/shield-swap-sdk/tests/test_gen_context.py +++ b/shield-swap-sdk/tests/test_gen_context.py @@ -52,18 +52,5 @@ def test_committed_page_is_current(): def test_page_stays_compact(): - # ~6.5k tokens — cheap context, enforced. Raised 20k → 22k with the - # router-dispatch surface (wrapper_proofs / withdrawal params); 22k → 24k - # when get_pools/get_tokens/derive_pool_key/derive_tick_key picked up full - # docstrings (they rendered blank before); 24k → 26k for the swap/swap_many - # footgun warnings (build-time counter reservation, refusing an unusable - # quote). 24k had been squeezed to 134 chars of headroom, which any further - # edit broke — this is deliberate room, not another squeeze. 26k → 32k - # (2026-09) for the upstream sync: rebalancing (plan + execute, with the - # price-fragility warning agents must relay), fill receipts, the routing - # graph, and the indexer's unclaimed/protocol-state views. 32k → 34k - # (2026-10) for compliance proofs: six write methods gained a - # ``compliance_proofs`` parameter and a one-line note on what it takes. - # 34k → 36k (2026-10-23) for record inventory: ``plan_inventory`` and - # ``rebalance_inventory`` plus the reservation note on ``swap``. - assert len(_render()) < 36_000 + # Keep the full guide small enough to include in an agent's working context. + assert len(_render()) < 38_000 diff --git a/shield-swap-sdk/tests/test_journal.py b/shield-swap-sdk/tests/test_journal.py index 8f48985d..9f9a367a 100644 --- a/shield-swap-sdk/tests/test_journal.py +++ b/shield-swap-sdk/tests/test_journal.py @@ -1,4 +1,5 @@ import json +import stat import threading from aleo_shield_swap.journal import Journal @@ -84,3 +85,121 @@ def test_skip_counters_through_advances_the_cursor(tmp_path): assert Journal(tmp_path / "journal.jsonl").counter_cursor() == 12 j.skip_counters_through(5) # never moves backwards assert j.counter_cursor() == 12 + + +# Journals of one account sharing a counter ledger + +def _on_ledger(tmp_path, home): + """Open the journal of one profile home on the ledger every home shares.""" + return Journal(tmp_path / home / "journal.jsonl", counters=tmp_path / "counters" / "account.jsonl") + + +def test_journals_on_one_ledger_never_issue_the_same_counter(tmp_path): + one, two = _on_ledger(tmp_path, "one"), _on_ledger(tmp_path, "two") + assert one.reserve_counters(2) == [0, 1] + assert two.reserve_counters(2) == [2, 3] + assert one.reserve_counters(1) == [4] + assert one.counter_cursor() == two.counter_cursor() == 5 + assert _on_ledger(tmp_path, "three").reserve_counters(1) == [5] # a home opened later + + +def test_ledger_directory_is_readable_by_its_owner_only(tmp_path): + _on_ledger(tmp_path, "one").reserve_counters(1) + assert stat.S_IMODE((tmp_path / "counters").stat().st_mode) == 0o700 + + +def test_journals_on_one_ledger_are_safe_across_threads(tmp_path): + got: list[int] = [] + lock = threading.Lock() + + def grab(home): + counters = _on_ledger(tmp_path, home).reserve_counters(5) + with lock: + got.extend(counters) + + ts = [threading.Thread(target=grab, args=(f"home-{n}",)) for n in range(4)] + [t.start() for t in ts] + [t.join() for t in ts] + assert sorted(got) == list(range(20)) # no counter issued twice + + +def test_skipped_counters_reach_every_journal_on_the_ledger(tmp_path): + one, two = _on_ledger(tmp_path, "one"), _on_ledger(tmp_path, "two") + one.skip_counters_through(9) + assert two.counter_cursor() == 10 + assert two.reserve_counters(1) == [10] + two.skip_counters_through(5) # never moves backwards + assert one.counter_cursor() == 11 + + +def test_journal_ahead_of_the_ledger_starts_past_its_own_history(tmp_path): + # A journal that issued counters before it joined a ledger keeps them spent. + Journal(tmp_path / "one" / "journal.jsonl").reserve_counters(8) + one, two = _on_ledger(tmp_path, "one"), _on_ledger(tmp_path, "two") + assert one.reserve_counters(1) == [8] + assert two.reserve_counters(1) == [9] + + +def test_opening_a_journal_on_a_ledger_publishes_the_counters_it_already_issued(tmp_path): + # Counters reserved before the ledger existed may belong to swaps that have not finalized. + assert Journal(tmp_path / "one" / "journal.jsonl").reserve_counters(2) == [0, 1] + _on_ledger(tmp_path, "one") # opened, never asked for a counter + assert _on_ledger(tmp_path, "two").reserve_counters(1) == [2] + + +def test_opening_a_new_journal_on_a_ledger_writes_nothing(tmp_path): + _on_ledger(tmp_path, "one") + assert list(tmp_path.iterdir()) == [] + + +def test_reopening_a_journal_on_a_ledger_publishes_its_counters_once(tmp_path): + Journal(tmp_path / "one" / "journal.jsonl").reserve_counters(2) + for _ in range(3): + _on_ledger(tmp_path, "one") + assert len((tmp_path / "counters" / "account.jsonl").read_text().splitlines()) == 1 + + +def test_swap_recorded_on_a_caller_chosen_counter_reaches_the_ledger(tmp_path): + one, two = _on_ledger(tmp_path, "one"), _on_ledger(tmp_path, "two") + one.record_swap(_handle("s1"), counter=7) # an identity the ledger did not issue + assert two.reserve_counters(1) == [8] + two.record_swap_failed(11, "boom") + assert one.reserve_counters(1) == [12] + + +def test_journal_and_ledger_that_derive_one_lock_file_do_not_deadlock(tmp_path): + # Both names lose their suffix to ".lock", so the two locks are one file. + got: list[int] = [] + + def reserve(): + for home in ("one", "one"): + journal = Journal(tmp_path / home / "journal.jsonl", counters=tmp_path / home / "journal.counters") + got.extend(journal.reserve_counters(2)) + journal.skip_counters_through(got[-1] + 1) + + worker = threading.Thread(target=reserve, daemon=True) + worker.start() + worker.join(timeout=10) + assert not worker.is_alive() # a second lock on the same file would wait forever + assert got == [0, 1, 3, 4] + + +def test_each_journal_records_the_counters_it_was_issued(tmp_path): + # Without the ledger file, a journal still never reissues its own counters. + one, two = _on_ledger(tmp_path, "one"), _on_ledger(tmp_path, "two") + one.reserve_counters(2) + two.reserve_counters(2) + assert Journal(tmp_path / "two" / "journal.jsonl").counter_cursor() == 4 + assert Journal(tmp_path / "one" / "journal.jsonl").counter_cursor() == 2 + + +def test_ledger_holds_counters_and_nothing_about_the_swaps(tmp_path): + one = _on_ledger(tmp_path, "one") + (counter,) = one.reserve_counters(1) + one.record_swap(_handle("s1"), counter=counter) + one.record_swap_failed(one.reserve_counters(1)[0], "boom") + one.skip_counters_through(6) + events = [json.loads(line) for line in (tmp_path / "counters" / "account.jsonl").read_text().splitlines()] + assert [sorted(event) for event in events] == [ + ["counters", "ts", "type"], ["counters", "ts", "type"], ["through", "ts", "type"]] + assert [h.swap_id for h in one.pending_claims()] == ["s1"] diff --git a/shield-swap-sdk/tests/test_package.py b/shield-swap-sdk/tests/test_package.py index 5344b05f..2803e3e3 100644 --- a/shield-swap-sdk/tests/test_package.py +++ b/shield-swap-sdk/tests/test_package.py @@ -2,7 +2,7 @@ def test_version(): - assert aleo_shield_swap.__version__ == "0.8.0" + assert aleo_shield_swap.__version__ == "0.9.0" def test_lifecycle_exports(): @@ -32,7 +32,7 @@ def test_import_guard_names_the_aleo_sdk_upgrade(monkeypatch): import pytest import aleo_shield_swap - aleo_shield_swap._require_aleo_sdk() # the installed sdk has aleo.inventory - monkeypatch.setitem(sys.modules, "aleo.inventory", None) # simulate an aleo-sdk without it - with pytest.raises(ImportError, match=r'needs aleo-sdk>=0\.8\.0 \(found .*\); run: pip install -U "aleo-sdk>=0\.8\.0"'): + aleo_shield_swap._require_aleo_sdk() # Confirm the installed SDK supports account storage. + monkeypatch.setitem(sys.modules, "aleo.keystore", None) # Exercise the upgrade message for an older SDK. + with pytest.raises(ImportError, match=r'needs aleo-sdk>=0\.9\.0 \(found .*\); run: pip install -U "aleo-sdk>=0\.9\.0"'): aleo_shield_swap._require_aleo_sdk() diff --git a/shield-swap-sdk/tests/test_profile.py b/shield-swap-sdk/tests/test_profile.py index 68d93cab..2bf0b596 100644 --- a/shield-swap-sdk/tests/test_profile.py +++ b/shield-swap-sdk/tests/test_profile.py @@ -1,7 +1,122 @@ +"""Check that profiles retain the intended account without exposing its key. + +The account_sandbox fixture supplies temporary files and a fake Keychain. +Accounts are generated for tests and never funded. Use same_secret for key +comparisons so pytest does not include private keys in failure output. +""" +from __future__ import annotations + +import json +import logging import stat +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Callable +from unittest.mock import Mock + +import pytest +from aleo import keystore, testnet +from aleo.keystore import KeystoreError + +from aleo_shield_swap import ShieldSwap +from aleo_shield_swap import profile as profile_module +from aleo_shield_swap.journal import Journal +from aleo_shield_swap.profile import DEFAULT_ENDPOINT, Profile + +# Fixed passwords for unfunded test accounts. +PASSWORD = "correct horse battery staple" +OTHER_PASSWORD = "another test password" + + +def new_account() -> SimpleNamespace: + """Generate an unfunded account for a test.""" + key = testnet.PrivateKey.random() + return SimpleNamespace(address=str(key.address), private_key=str(key)) + + +def same_secret(actual: object, expected: object) -> None: + """Fail on unequal secrets without printing either value.""" + if not isinstance(actual, str) or actual != expected: + raise AssertionError("the secret values differ") + + +def failure(call: Callable[[], Any]) -> KeystoreError: + """Capture a failed call so the test can inspect its error code.""" + try: + call() + except KeystoreError as error: + return error + raise AssertionError("expected the call to fail") + + +def mode(path: Path) -> int: + return stat.S_IMODE(path.stat().st_mode) + + +def files_under(*roots: Path) -> list[Path]: + return [path for root in roots if root.exists() for path in root.rglob("*") if path.is_file()] + + +def assert_key_on_no_disk(private_key: str, *roots: Path) -> None: + """Check for leaked private keys in files below the supplied directories.""" + for path in files_under(*roots): + if private_key.encode() in path.read_bytes(): + raise AssertionError(f"{path} contains a private key") + + +def saved_profile(home: Path) -> dict[str, Any]: + return json.loads((home / "profile.json").read_text()) + + +def write_legacy_profile(home: Path, account: SimpleNamespace, **extra: Any) -> Path: + """Create a profile in the older format for compatibility and migration tests.""" + home.mkdir(parents=True, exist_ok=True) + path = home / "profile.json" + data = {"address": account.address, "private_key": account.private_key, + "network": "testnet", "endpoint": DEFAULT_ENDPOINT, **extra} + path.write_text(json.dumps(data, indent=1)) + path.chmod(0o600) + return path + + +@pytest.fixture(autouse=True) +def fresh_legacy_notices(monkeypatch): + """Let each test observe its own migration warnings.""" + monkeypatch.setattr(profile_module, "_legacy_notices", set()) + + +@pytest.fixture +def lookups(monkeypatch): + """Record lookup arguments to check account selection and key caching.""" + calls: list[dict[str, Any]] = [] + real = keystore.load + + def counted(**kwargs: Any): + calls.append(kwargs) + return real(**kwargs) + + monkeypatch.setattr(keystore, "load", counted) + return calls -from aleo_shield_swap.profile import Profile +# Test isolation + +def test_tests_run_against_a_stand_in_home(account_sandbox, tmp_path): + """Verify that the fixture redirects default paths and clears account variables.""" + import os + + assert Path.home() == account_sandbox.home + assert Profile.default_home() == account_sandbox.home / ".shield-swap" + for name in ("ALEO_PRIVATE_KEY", "ALEO_PRIVATE_KEY_FILE", "ALEO_ACCOUNT", "ALEO_ACCOUNTS_DIR", + "ALEO_ACCOUNT_PASSWORD", "SHIELD_SWAP_PRIVATE_KEY", "SHIELD_SWAP_PRIVATE_KEY_FILE", + "SHIELD_SWAP_HOME"): + assert name not in os.environ + assert keystore.info() is None + stored = keystore.save(new_account().private_key) + assert stored.path == account_sandbox.accounts / "default.json" + + +# Creating a profile def test_create_then_reload_is_stable(tmp_path): p1 = Profile.load_or_create(tmp_path / "home") @@ -9,14 +124,743 @@ def test_create_then_reload_is_stable(tmp_path): assert p1.private_key.startswith("APrivateKey1") assert p1.network == "testnet" p2 = Profile.load_or_create(tmp_path / "home") # reload, no regen - assert (p2.address, p2.private_key) == (p1.address, p1.private_key) + assert p2.address == p1.address + same_secret(p2.private_key, p1.private_key) + + +def test_new_profile_stores_the_key_in_the_account_file_not_the_profile(tmp_path, account_sandbox): + profile = Profile.load_or_create(tmp_path / "home", network="mainnet", endpoint="https://node.example") + saved = saved_profile(profile.home) + assert saved == {"address": profile.address, "account": "default", + "network": "mainnet", "endpoint": "https://node.example"} + assert_key_on_no_disk(profile.private_key, tmp_path) + + account_file = account_sandbox.accounts / "default.json" + stored = json.loads(account_file.read_text()) + assert stored["address"] == profile.address + assert stored["key"]["type"] == "plaintext" + same_secret(stored["key"]["privateKey"], profile.private_key) + assert mode(account_file) == 0o600 + assert keystore.info() == keystore.StoredAccount( + name="default", path=account_file, address=profile.address, storage="plaintext") -def test_key_file_is_owner_only(tmp_path): +def test_profile_file_is_owner_only(tmp_path): p = Profile.load_or_create(tmp_path / "home") - mode = stat.S_IMODE((p.home / "profile.json").stat().st_mode) - assert mode == 0o600 + assert mode(p.home / "profile.json") == 0o600 + + +def test_loose_profile_mode_is_tightened_on_load(tmp_path): + p = Profile.load_or_create(tmp_path / "home") + (p.home / "profile.json").chmod(0o644) + Profile.load_or_create(tmp_path / "home") + assert mode(p.home / "profile.json") == 0o600 + + +def test_new_profile_adopts_the_stored_account(tmp_path, account_sandbox): + account = new_account() + keystore.save(account.private_key) + before = (account_sandbox.accounts / "default.json").read_bytes() + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == account.address + same_secret(profile.private_key, account.private_key) + assert (account_sandbox.accounts / "default.json").read_bytes() == before + assert saved_profile(profile.home)["account"] == "default" + + +def test_account_stored_by_a_concurrent_startup_is_adopted(tmp_path, monkeypatch, account_sandbox): + winner = new_account() + real = keystore.load + + def racing(**kwargs: Any): + try: + return real(**kwargs) + except KeystoreError: + # Another process stores the account after this lookup found none. + if not (account_sandbox.accounts / "default.json").exists(): + keystore.save(winner.private_key) + raise + + monkeypatch.setattr(keystore, "load", racing) + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == winner.address + same_secret(profile.private_key, winner.private_key) + assert saved_profile(profile.home)["address"] == winner.address + assert [path.name for path in account_sandbox.accounts.iterdir() if path.suffix == ".json"] == ["default.json"] + + +def test_locked_account_stored_by_a_concurrent_startup_is_reported(tmp_path, monkeypatch, account_sandbox): + real = keystore.load + + def racing(**kwargs: Any): + try: + return real(**kwargs) + except KeystoreError: + if not (account_sandbox.accounts / "default.json").exists(): + keystore.save(new_account().private_key, storage="encrypted", password=PASSWORD) + raise + + monkeypatch.setattr(keystore, "load", racing) + assert failure(lambda: Profile.load_or_create(tmp_path / "home")).code == "PASSWORD_REQUIRED" + assert not (tmp_path / "home").exists() + + +def test_two_homes_share_the_stored_account(tmp_path): + first = Profile.load_or_create(tmp_path / "one") + second = Profile.load_or_create(tmp_path / "two") + assert second.address == first.address + + +@pytest.mark.parametrize("variable", ["ALEO_PRIVATE_KEY", "SHIELD_SWAP_PRIVATE_KEY"]) +def test_key_from_the_environment_is_used_and_never_written(tmp_path, monkeypatch, account_sandbox, variable): + account = new_account() + monkeypatch.setenv(variable, account.private_key) + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == account.address + same_secret(profile.private_key, account.private_key) + assert saved_profile(profile.home) == {"address": account.address, "account": "default", + "network": "testnet", "endpoint": DEFAULT_ENDPOINT} + assert not account_sandbox.accounts.exists() + assert_key_on_no_disk(account.private_key, tmp_path, account_sandbox.home) + + +@pytest.mark.parametrize("variable", ["ALEO_PRIVATE_KEY_FILE", "SHIELD_SWAP_PRIVATE_KEY_FILE"]) +def test_key_file_from_the_environment_is_used_and_never_copied(tmp_path, monkeypatch, account_sandbox, variable): + account = new_account() + key_file = tmp_path / "key.txt" + key_file.write_text(account.private_key + "\n") + monkeypatch.setenv(variable, str(key_file)) + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == account.address + same_secret(profile.private_key, account.private_key) + assert not account_sandbox.accounts.exists() + assert_key_on_no_disk(account.private_key, tmp_path / "home", account_sandbox.home) + + +def test_profile_made_from_an_environment_key_needs_it_again(tmp_path, monkeypatch): + account = new_account() + monkeypatch.setenv("ALEO_PRIVATE_KEY", account.private_key) + Profile.load_or_create(tmp_path / "home") + monkeypatch.delenv("ALEO_PRIVATE_KEY") + + later = Profile.load_or_create(tmp_path / "home") # The saved address is still available without the key. + assert later.address == account.address + assert failure(lambda: later.private_key).code == "ACCOUNT_NOT_FOUND" + + monkeypatch.setenv("ALEO_PRIVATE_KEY", account.private_key) + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + + +def test_environment_key_must_match_the_selected_account_file(tmp_path, monkeypatch): + stored, supplied = new_account(), new_account() + keystore.save(stored.private_key) + monkeypatch.setenv("ALEO_PRIVATE_KEY", supplied.private_key) + error = failure(lambda: Profile.load_or_create(tmp_path / "home")) + assert error.code == "ADDRESS_MISMATCH" + assert stored.address in str(error) and supplied.address in str(error) + assert not (tmp_path / "home").exists() + + +@pytest.mark.parametrize("variable", ["ALEO_PRIVATE_KEY", "SHIELD_SWAP_PRIVATE_KEY"]) +def test_empty_key_variable_is_an_error_not_a_new_account(tmp_path, monkeypatch, account_sandbox, variable): + monkeypatch.setenv(variable, "") + assert failure(lambda: Profile.load_or_create(tmp_path / "home")).code == "EMPTY_KEY_SOURCE" + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_empty_key_file_is_an_error_not_a_new_account(tmp_path, monkeypatch, account_sandbox): + key_file = tmp_path / "key.txt" + key_file.write_text("\n") + monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY_FILE", str(key_file)) + assert failure(lambda: Profile.load_or_create(tmp_path / "home")).code == "EMPTY_KEY_SOURCE" + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_variables_holding_different_keys_are_an_error(tmp_path, monkeypatch): + monkeypatch.setenv("ALEO_PRIVATE_KEY", new_account().private_key) + monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY", new_account().private_key) + assert failure(lambda: Profile.load_or_create(tmp_path / "home")).code == "KEY_CONFLICT" + assert not (tmp_path / "home").exists() + + +def test_create_false_raises_when_no_account_resolves(tmp_path, account_sandbox): + error = failure(lambda: Profile.load_or_create(tmp_path / "home", create=False)) + assert error.code == "ACCOUNT_NOT_FOUND" + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_create_false_uses_an_account_that_resolves(tmp_path, monkeypatch): + stored = new_account() + keystore.save(stored.private_key) + assert Profile.load_or_create(tmp_path / "stored", create=False).address == stored.address + + supplied = new_account() + monkeypatch.setenv("ALEO_ACCOUNT", "per-run") + monkeypatch.setenv("ALEO_PRIVATE_KEY", supplied.private_key) + assert Profile.load_or_create(tmp_path / "supplied", create=False).address == supplied.address + + +def test_creating_without_a_stored_key_is_rejected(tmp_path, account_sandbox): + error = failure(lambda: Profile.load_or_create(tmp_path / "home", storage="none")) + assert error.code == "UNSUPPORTED_STORAGE" + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_storage_none_is_only_rejected_when_an_account_would_be_created(tmp_path, monkeypatch): + account = new_account() + monkeypatch.setenv("ALEO_PRIVATE_KEY", account.private_key) + assert Profile.load_or_create(tmp_path / "home", storage="none").address == account.address + + +def test_unknown_storage_is_rejected_before_anything_is_written(tmp_path, account_sandbox): + error = failure(lambda: Profile.load_or_create(tmp_path / "home", storage="vault")) + assert error.code == "UNSUPPORTED_STORAGE" + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_unknown_network_is_rejected_before_anything_is_written(tmp_path, account_sandbox): + with pytest.raises(AttributeError): + Profile.load_or_create(tmp_path / "home", network="nonet") + assert not (tmp_path / "home").exists() + assert not account_sandbox.accounts.exists() + + +def test_account_argument_names_the_account_file(tmp_path, account_sandbox): + profile = Profile.load_or_create(tmp_path / "home", account="trading") + assert saved_profile(profile.home)["account"] == "trading" + assert (account_sandbox.accounts / "trading.json").exists() + assert not (account_sandbox.accounts / "default.json").exists() + + +def test_account_variable_names_the_account_file(tmp_path, monkeypatch, account_sandbox): + monkeypatch.setenv("ALEO_ACCOUNT", "from-env") + profile = Profile.load_or_create(tmp_path / "home") + assert saved_profile(profile.home)["account"] == "from-env" + assert (account_sandbox.accounts / "from-env.json").exists() + + +@pytest.mark.parametrize("argument, variable, recorded", [ + (None, None, "default"), (None, "from-env", "from-env"), ("from-argument", "from-env", "from-argument"), +]) +def test_selected_name_is_recorded_when_the_key_comes_from_the_environment( + tmp_path, monkeypatch, account_sandbox, argument, variable, recorded): + """Keep the selected name so the same key can later be imported under it.""" + monkeypatch.setenv("ALEO_PRIVATE_KEY", new_account().private_key) + if variable is not None: + monkeypatch.setenv("ALEO_ACCOUNT", variable) + profile = Profile.load_or_create(tmp_path / "home", account=argument) + assert saved_profile(profile.home)["account"] == recorded + assert not account_sandbox.accounts.exists() + + +def test_account_argument_beats_the_variable_when_creating(tmp_path, monkeypatch, account_sandbox): + monkeypatch.setenv("ALEO_ACCOUNT", "from-env") + profile = Profile.load_or_create(tmp_path / "home", account="from-argument") + assert saved_profile(profile.home)["account"] == "from-argument" + assert [path.name for path in account_sandbox.accounts.iterdir()] == ["from-argument.json"] + + +def test_invalid_account_name_is_rejected(tmp_path, account_sandbox): + assert failure(lambda: Profile.load_or_create(tmp_path / "home", account="Not Valid")).code == "INVALID_NAME" + assert not (tmp_path / "home").exists() + + +def test_accounts_dir_is_used_and_not_recorded(tmp_path, account_sandbox): + accounts = tmp_path / "accounts" + profile = Profile.load_or_create(tmp_path / "home", accounts_dir=accounts) + assert (accounts / "default.json").exists() + assert not account_sandbox.accounts.exists() + assert set(saved_profile(profile.home)) == {"address", "account", "network", "endpoint"} + + # Reopening from a custom location requires the same directory. + same_secret(Profile.load_or_create(tmp_path / "home", accounts_dir=accounts).private_key, profile.private_key) + without = Profile.load_or_create(tmp_path / "home") + assert failure(lambda: without.private_key).code == "ACCOUNT_NOT_FOUND" + + +def test_accounts_dir_variable_is_honoured(tmp_path, monkeypatch, account_sandbox): + monkeypatch.setenv("ALEO_ACCOUNTS_DIR", str(tmp_path / "from-env")) + profile = Profile.load_or_create(tmp_path / "home") + assert (tmp_path / "from-env" / "default.json").exists() + assert not account_sandbox.accounts.exists() + same_secret(Profile.load_or_create(tmp_path / "home").private_key, profile.private_key) + + +@pytest.mark.parametrize("name", ["profile", "credentials"]) +def test_account_file_that_is_a_profile_file_is_rejected_before_anything_is_written(tmp_path, name): + home = tmp_path / "home" + with pytest.raises(ValueError, match=f"{name}.json"): + Profile.load_or_create(home, accounts_dir=home, account=name) + assert not home.exists() + + +def test_account_file_that_is_a_profile_file_is_rejected_when_the_variables_select_it(tmp_path, monkeypatch): + home = tmp_path / "home" + monkeypatch.setenv("ALEO_ACCOUNTS_DIR", str(home)) + monkeypatch.setenv("ALEO_ACCOUNT", "profile") + with pytest.raises(ValueError, match="profile.json"): + Profile.load_or_create(home) + assert not home.exists() + + +def test_account_file_that_is_a_profile_file_is_rejected_through_another_spelling_of_the_home(tmp_path): + home = tmp_path / "home" + home.mkdir() + (tmp_path / "link").symlink_to(home, target_is_directory=True) + with pytest.raises(ValueError, match="profile.json"): + Profile.load_or_create(home, accounts_dir=tmp_path / "link", account="profile") + assert files_under(home) == [] + + +def test_stored_account_named_like_the_credentials_file_is_left_untouched(tmp_path): + # Saving credentials would replace this account file, so the profile refuses it. + home = tmp_path / "home" + account = new_account() + stored = keystore.save(account.private_key, name="credentials", dir=home) + before = Path(stored.path).read_bytes() + with pytest.raises(ValueError, match="credentials.json"): + Profile.load_or_create(home, accounts_dir=home, account="credentials") + assert files_under(home) == [Path(stored.path)] + assert Path(stored.path).read_bytes() == before + + +def test_saved_account_name_that_selects_a_profile_file_is_rejected_on_reopening(tmp_path, account_sandbox): + home = tmp_path / "home" + Profile.load_or_create(home, account="credentials") + moved = home / "credentials.json" + (account_sandbox.accounts / "credentials.json").rename(moved) + before = moved.read_bytes() + # The saved name selects the account here, without the argument or the variable. + with pytest.raises(ValueError, match="credentials.json"): + Profile.load_or_create(home, accounts_dir=home) + assert moved.read_bytes() == before + +def test_saved_account_name_gives_way_to_the_variable_when_checking_profile_files(tmp_path, monkeypatch): + home = tmp_path / "home" + Profile.load_or_create(home, account="credentials") + other = Profile.load_or_create(tmp_path / "other-home", accounts_dir=home, account="trading") + monkeypatch.setenv("ALEO_ACCOUNT", "trading") + reopened = Profile.load_or_create(tmp_path / "other-home", accounts_dir=home) + same_secret(reopened.private_key, other.private_key) + + +def test_account_named_like_a_profile_file_works_outside_the_profile_home(tmp_path): + profile = Profile.load_or_create(tmp_path / "home", account="credentials") + profile.save_credentials(jwt="token") + reopened = Profile.load_or_create(tmp_path / "home") + same_secret(reopened.private_key, profile.private_key) + assert reopened.credentials == {"jwt": "token"} + + +def test_other_account_names_may_live_in_the_profile_home(tmp_path): + home = tmp_path / "home" + profile = Profile.load_or_create(home, accounts_dir=home, account="trading") + profile.save_credentials(jwt="token") + reopened = Profile.load_or_create(home, accounts_dir=home) + same_secret(reopened.private_key, profile.private_key) + assert {path.name for path in files_under(home)} == {"profile.json", "credentials.json", "trading.json"} + + +# Protecting keys with encryption or Keychain + +def test_encrypted_account_needs_its_password_on_later_runs(tmp_path, monkeypatch, account_sandbox): + created = Profile.load_or_create(tmp_path / "home", storage="encrypted", password=PASSWORD) + stored = json.loads((account_sandbox.accounts / "default.json").read_text()) + assert stored["key"]["type"] == "encrypted" + assert_key_on_no_disk(created.private_key, tmp_path, account_sandbox.home) + + # Inspecting an existing profile must not require unlocking its key. + locked = Profile.load_or_create(tmp_path / "home") + assert locked.address == created.address + assert failure(lambda: locked.private_key).code == "PASSWORD_REQUIRED" + + same_secret(Profile.load_or_create(tmp_path / "home", password=PASSWORD).private_key, created.private_key) + wrong = Profile.load_or_create(tmp_path / "home", password=OTHER_PASSWORD) + assert failure(lambda: wrong.private_key).code == "WRONG_PASSWORD" + + monkeypatch.setenv("ALEO_ACCOUNT_PASSWORD", PASSWORD) + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + + +def test_encrypted_account_takes_its_password_from_the_variable_when_created(tmp_path, monkeypatch, account_sandbox): + monkeypatch.setenv("ALEO_ACCOUNT_PASSWORD", PASSWORD) + created = Profile.load_or_create(tmp_path / "home", storage="encrypted") + same_secret(keystore.export(password=PASSWORD), created.private_key) + + +def test_encrypted_account_without_a_password_source_creates_nothing(tmp_path, account_sandbox): + error = failure(lambda: Profile.load_or_create(tmp_path / "home", storage="encrypted")) + assert error.code == "PASSWORD_REQUIRED" + assert not (tmp_path / "home").exists() + assert files_under(account_sandbox.home) == [] + + +def test_new_profile_adopts_an_encrypted_account(tmp_path): + account = new_account() + keystore.save(account.private_key, storage="encrypted", password=PASSWORD) + assert failure(lambda: Profile.load_or_create(tmp_path / "locked")).code == "PASSWORD_REQUIRED" + assert not (tmp_path / "locked").exists() + profile = Profile.load_or_create(tmp_path / "home", password=PASSWORD) + assert profile.address == account.address + same_secret(profile.private_key, account.private_key) + + +def test_saved_password_unlocks_later_runs(tmp_path, monkeypatch, account_sandbox): + from aleo.keystore._runtime import runtime + monkeypatch.setattr(runtime, "platform", "darwin") + created = Profile.load_or_create(tmp_path / "home", storage="encrypted", + password=PASSWORD, save_password=True) + assert [entry.split()[0] for entry in account_sandbox.keychain.entries] == ["aleo-account-password"] + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + + +def test_keychain_storage_keeps_the_key_out_of_every_file(tmp_path, monkeypatch, account_sandbox): + from aleo.keystore._runtime import runtime + monkeypatch.setattr(runtime, "platform", "darwin") + created = Profile.load_or_create(tmp_path / "home", storage="keychain") + stored = json.loads((account_sandbox.accounts / "default.json").read_text()) + assert stored["key"]["type"] == "keychain" + assert_key_on_no_disk(created.private_key, tmp_path, account_sandbox.home) + (entry, value), = account_sandbox.keychain.entries.items() + assert entry == f"aleo-account-key {stored['key']['account']}" + same_secret(value, created.private_key) + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + + +def test_keychain_storage_outside_macos_creates_nothing(tmp_path, monkeypatch, account_sandbox): + from aleo.keystore._runtime import runtime + monkeypatch.setattr(runtime, "platform", "linux") + error = failure(lambda: Profile.load_or_create(tmp_path / "home", storage="keychain")) + assert error.code == "KEYCHAIN_UNAVAILABLE" + assert not (tmp_path / "home").exists() + assert files_under(account_sandbox.home) == [] + assert account_sandbox.keychain.entries == {} + + +# Reopening profiles and supporting older files + +def test_legacy_profile_keeps_working_and_is_left_untouched(tmp_path, account_sandbox): + account = new_account() + path = write_legacy_profile(tmp_path / "home", account) + before = path.read_bytes() + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == account.address + same_secret(profile.private_key, account.private_key) + assert profile.network == "testnet" and profile.endpoint == DEFAULT_ENDPOINT + assert path.read_bytes() == before + assert not account_sandbox.accounts.exists() + + +def test_legacy_profile_is_reported_once(tmp_path, caplog): + account = new_account() + path = write_legacy_profile(tmp_path / "home", account) + with caplog.at_level(logging.WARNING, logger="aleo_shield_swap.profile"): + first = Profile.load_or_create(tmp_path / "home") + assert caplog.records == [] # Warn only when the legacy key is used. + first.private_key + first.private_key + Profile.load_or_create(tmp_path / "home").private_key + (record,) = caplog.records + assert record.levelno == logging.WARNING and record.name == "aleo_shield_swap.profile" + message = record.getMessage() + assert f"python -m aleo.keystore migrate --from {path}" in message + assert account.address in message and str(path) in message + if account.private_key in message or account.private_key in caplog.text: + raise AssertionError("the notice contains a private key") + + +def test_each_legacy_profile_is_reported(tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="aleo_shield_swap.profile"): + for name in ("one", "two"): + write_legacy_profile(tmp_path / name, new_account()) + Profile.load_or_create(tmp_path / name).private_key + assert len(caplog.records) == 2 + + +def test_migrated_legacy_profile_reads_the_account_file_without_a_notice(tmp_path, caplog, account_sandbox): + account = new_account() + path = write_legacy_profile(tmp_path / "home", account) + keystore.migrate(path) # Migration keeps the original key unless removal is requested. + with caplog.at_level(logging.WARNING, logger="aleo_shield_swap.profile"): + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + assert caplog.records == [] + + keystore.migrate(path, remove_legacy_key=True) + assert "private_key" not in saved_profile(tmp_path / "home") + assert_key_on_no_disk(account.private_key, tmp_path) + with caplog.at_level(logging.WARNING, logger="aleo_shield_swap.profile"): + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + assert caplog.records == [] + + +def test_legacy_profile_with_the_same_key_in_the_environment_gives_no_notice(tmp_path, monkeypatch, caplog): + account = new_account() + write_legacy_profile(tmp_path / "home", account) + monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY", account.private_key) + with caplog.at_level(logging.WARNING, logger="aleo_shield_swap.profile"): + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + assert caplog.records == [] + + +@pytest.mark.parametrize("legacy", [True, False]) +@pytest.mark.parametrize("variable", ["ALEO_PRIVATE_KEY", "SHIELD_SWAP_PRIVATE_KEY", "ALEO_PRIVATE_KEY_FILE"]) +def test_environment_key_for_another_account_is_an_error(tmp_path, monkeypatch, legacy, variable): + other = new_account() + if legacy: + bound = new_account() + write_legacy_profile(tmp_path / "home", bound) + else: + bound = SimpleNamespace(address=Profile.load_or_create(tmp_path / "home").address) + value = other.private_key + if variable.endswith("_FILE"): + (tmp_path / "other.key").write_text(other.private_key) + value = str(tmp_path / "other.key") + monkeypatch.setenv(variable, value) + + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address == bound.address + error = failure(lambda: profile.private_key) + assert error.code == "ADDRESS_MISMATCH" + assert bound.address in str(error) and other.address in str(error) + if other.private_key in str(error): + raise AssertionError("the error contains a private key") + + +def test_environment_key_for_the_same_account_is_used(tmp_path, monkeypatch): + created = Profile.load_or_create(tmp_path / "home") + key = created.private_key + monkeypatch.setenv("ALEO_PRIVATE_KEY", key) + same_secret(Profile.load_or_create(tmp_path / "home").private_key, key) + assert keystore.load(expected_address=created.address).source == "env" + + +def test_empty_key_variable_is_an_error_for_an_existing_profile(tmp_path, monkeypatch): + Profile.load_or_create(tmp_path / "home") + monkeypatch.setenv("ALEO_PRIVATE_KEY", "") + profile = Profile.load_or_create(tmp_path / "home") + assert failure(lambda: profile.private_key).code == "EMPTY_KEY_SOURCE" + + +def test_account_file_for_another_address_is_an_error(tmp_path, account_sandbox): + profile = Profile.load_or_create(tmp_path / "home") + (account_sandbox.accounts / "default.json").unlink() + other = new_account() + keystore.save(other.private_key) + reloaded = Profile.load_or_create(tmp_path / "home") + error = failure(lambda: reloaded.private_key) + assert error.code == "ADDRESS_MISMATCH" + assert profile.address in str(error) and other.address in str(error) + + +def test_legacy_key_must_match_an_account_file_of_the_same_name(tmp_path): + legacy, other = new_account(), new_account() + write_legacy_profile(tmp_path / "home", legacy) + keystore.save(other.private_key) + profile = Profile.load_or_create(tmp_path / "home") + error = failure(lambda: profile.private_key) + assert error.code == "ADDRESS_MISMATCH" + assert legacy.address in str(error) and other.address in str(error) + + +def test_address_only_account_file_needs_the_key_from_the_environment(tmp_path, monkeypatch): + account = new_account() + monkeypatch.setenv("ALEO_PRIVATE_KEY", account.private_key) + keystore.save(account.private_key, storage="none") + Profile.load_or_create(tmp_path / "home") + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + monkeypatch.delenv("ALEO_PRIVATE_KEY") + profile = Profile.load_or_create(tmp_path / "home") + assert failure(lambda: profile.private_key).code == "KEY_NOT_STORED" + + +# Choosing the account for a saved profile + +def test_recorded_account_name_is_used(tmp_path, lookups): + created = Profile.load_or_create(tmp_path / "home", account="trading") + del lookups[:] + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + assert [call["name"] for call in lookups] == ["trading"] + + +def test_account_variable_beats_the_recorded_name(tmp_path, monkeypatch, account_sandbox, lookups): + created = Profile.load_or_create(tmp_path / "home", account="trading") + monkeypatch.setenv("ALEO_ACCOUNT", "elsewhere") + del lookups[:] + profile = Profile.load_or_create(tmp_path / "home") + error = failure(lambda: profile.private_key) + assert error.code == "ACCOUNT_NOT_FOUND" and "elsewhere.json" in str(error) + # Leave name unset so keystore.load() can use ALEO_ACCOUNT. + assert [call["name"] for call in lookups] == [None] + + # Renaming the account is allowed when its address stays the same. + keystore.save(created.private_key, name="elsewhere") + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + + # An override must not switch the profile to another address. + monkeypatch.setenv("ALEO_ACCOUNT", "stranger") + keystore.save(new_account().private_key, name="stranger") + stranger = Profile.load_or_create(tmp_path / "home") + assert failure(lambda: stranger.private_key).code == "ADDRESS_MISMATCH" + + +def test_account_argument_beats_the_variable_and_the_recorded_name(tmp_path, monkeypatch, lookups): + created = Profile.load_or_create(tmp_path / "home", account="trading") + keystore.save(created.private_key, name="copy") + monkeypatch.setenv("ALEO_ACCOUNT", "missing") + del lookups[:] + same_secret(Profile.load_or_create(tmp_path / "home", account="copy").private_key, created.private_key) + assert [call["name"] for call in lookups] == ["copy"] + + +def test_empty_account_variable_counts_as_unset(tmp_path, monkeypatch, lookups): + created = Profile.load_or_create(tmp_path / "home", account="trading") + monkeypatch.setenv("ALEO_ACCOUNT", "") + del lookups[:] + same_secret(Profile.load_or_create(tmp_path / "home").private_key, created.private_key) + assert [call["name"] for call in lookups] == ["trading"] + + +def test_profile_without_a_recorded_name_selects_default(tmp_path, lookups): + account = new_account() + path = write_legacy_profile(tmp_path / "home", account) + keystore.migrate(path, remove_legacy_key=True) + del lookups[:] + same_secret(Profile.load_or_create(tmp_path / "home").private_key, account.private_key) + assert [call["name"] for call in lookups] == [None] + + +def test_lookup_passes_the_recorded_address_and_the_legacy_key(tmp_path, lookups): + account = new_account() + write_legacy_profile(tmp_path / "home", account) + Profile.load_or_create(tmp_path / "home", accounts_dir=tmp_path / "accounts", password=PASSWORD).private_key + (call,) = lookups + assert call["expected_address"] == account.address + same_secret(call["legacy_key"], account.private_key) + assert call["dir"] == tmp_path / "accounts" + same_secret(call["password"], PASSWORD) + + +# Unlocking once and retrying failed lookups + +def test_key_is_resolved_once_per_object_and_only_when_read(tmp_path, lookups): + Profile.load_or_create(tmp_path / "home") + del lookups[:] + profile = Profile.load_or_create(tmp_path / "home") + assert profile.address and profile.network and profile.credentials == {} + assert lookups == [] # Reading metadata does not unlock the account. + for _ in range(3): + profile.private_key + assert len(lookups) == 1 + Profile.load_or_create(tmp_path / "home").private_key # Each new object must load its own key. + assert len(lookups) == 2 + + +def test_new_profile_keeps_the_key_it_was_created_with(tmp_path, lookups): + profile = Profile.load_or_create(tmp_path / "home", storage="encrypted", password=PASSWORD) + assert len(lookups) == 1 # Creation first checked for an existing account. + profile.private_key + profile.private_key + assert len(lookups) == 1 + + +def test_failed_lookup_is_retried(tmp_path, monkeypatch): + created = Profile.load_or_create(tmp_path / "home", storage="encrypted", password=PASSWORD) + profile = Profile.load_or_create(tmp_path / "home") + assert failure(lambda: profile.private_key).code == "PASSWORD_REQUIRED" + monkeypatch.setenv("ALEO_ACCOUNT_PASSWORD", PASSWORD) + same_secret(profile.private_key, created.private_key) + + +def test_creation_arguments_are_ignored_for_an_existing_profile(tmp_path, account_sandbox): + created = Profile.load_or_create(tmp_path / "home") + again = Profile.load_or_create(tmp_path / "home", network="mainnet", endpoint="https://other.example", + create=False, storage="none", save_password=True) + assert (again.address, again.network, again.endpoint) == (created.address, "testnet", DEFAULT_ENDPOINT) + same_secret(again.private_key, created.private_key) + assert [path.name for path in account_sandbox.accounts.iterdir()] == ["default.json"] + + +def test_repr_and_saved_profile_hold_no_key(tmp_path): + profile = Profile.load_or_create(tmp_path / "home") + key = profile.private_key + if key in repr(profile) or key in (profile.home / "profile.json").read_text(): + raise AssertionError("the profile exposes a private key") + + +# Opening a trading client + +def test_from_profile_signs_with_the_resolved_key(tmp_path, monkeypatch): + account = new_account() + keystore.save(account.private_key, storage="encrypted", password=PASSWORD) + monkeypatch.setenv("ALEO_ACCOUNT_PASSWORD", PASSWORD) + aleo = Mock() + aleo.network_name = "testnet" + monkeypatch.setattr("aleo.Aleo", Mock(return_value=aleo)) + monkeypatch.setattr("aleo.HTTPProvider", Mock()) + + dex = ShieldSwap.from_profile(tmp_path / "home") + + (bound,), _ = aleo.account.from_private_key.call_args + same_secret(bound, account.private_key) + assert dex.profile.address == account.address + assert dex.journal.path == tmp_path / "home" / "journal.jsonl" + assert saved_profile(tmp_path / "home")["account"] == "default" + + +def test_clients_of_two_homes_on_one_account_reserve_different_swap_identities(tmp_path, monkeypatch): + aleo = Mock() + aleo.network_name = "testnet" + monkeypatch.setattr("aleo.Aleo", Mock(return_value=aleo)) + monkeypatch.setattr("aleo.HTTPProvider", Mock()) + # No swap has finalized, so the chain reports every blinded address unused. + monkeypatch.setattr(ShieldSwap, "_blinded_address_used", lambda self, blinded_address: False) + monkeypatch.setattr( + "aleo_shield_swap.client.blinded_identity_at", + lambda aleo, account, program, counter: SimpleNamespace(counter=counter, blinded_address=f"ba{counter}")) + + first = ShieldSwap.from_profile(tmp_path / "one") + second = ShieldSwap.from_profile(tmp_path / "two") + assert first.profile.address == second.profile.address + + counters = [identity.counter for dex in (first, second, first) for identity in dex._reserve_identities(object(), 1)] + assert counters == [0, 1, 2] + assert first.journal.path != second.journal.path + + +def test_client_of_a_second_home_skips_counters_an_earlier_journal_still_has_pending(tmp_path, monkeypatch): + aleo = Mock() + aleo.network_name = "testnet" + monkeypatch.setattr("aleo.Aleo", Mock(return_value=aleo)) + monkeypatch.setattr("aleo.HTTPProvider", Mock()) + # The earlier swaps have not finalized, so the chain cannot report their counters. + monkeypatch.setattr(ShieldSwap, "_blinded_address_used", lambda self, blinded_address: False) + monkeypatch.setattr( + "aleo_shield_swap.client.blinded_identity_at", + lambda aleo, account, program, counter: SimpleNamespace(counter=counter, blinded_address=f"ba{counter}")) + # A journal that reserved counters before the ledger existed. + profile = Profile.load_or_create(tmp_path / "one") + assert Journal(profile.journal_path).reserve_counters(2) == [0, 1] + + ShieldSwap.from_profile(tmp_path / "one") + second = ShieldSwap.from_profile(tmp_path / "two") + assert [identity.counter for identity in second._reserve_identities(object(), 1)] == [2] + + +def test_from_profile_reports_a_locked_account(tmp_path, monkeypatch): + keystore.save(new_account().private_key, storage="encrypted", password=PASSWORD) + monkeypatch.setattr("aleo.Aleo", Mock()) + monkeypatch.setattr("aleo.HTTPProvider", Mock()) + assert failure(lambda: ShieldSwap.from_profile(tmp_path / "home")).code == "PASSWORD_REQUIRED" + assert not (tmp_path / "home").exists() + + +# Profile directories, credentials, and journals def test_env_home_override(tmp_path, monkeypatch): monkeypatch.setenv("SHIELD_SWAP_HOME", str(tmp_path / "envhome")) @@ -24,6 +868,29 @@ def test_env_home_override(tmp_path, monkeypatch): assert p.home == tmp_path / "envhome" +def test_default_home_is_under_the_home_directory(account_sandbox): + p = Profile.load_or_create() + assert p.home == account_sandbox.home / ".shield-swap" + assert (account_sandbox.home / ".shield-swap" / "profile.json").exists() + + +def test_counter_ledger_is_named_by_network_and_address_outside_the_home(tmp_path, account_sandbox): + first = Profile.load_or_create(tmp_path / "one") + second = Profile.load_or_create(tmp_path / "two") + mainnet = Profile.load_or_create(tmp_path / "three", network="mainnet") + counters = account_sandbox.home / ".aleo" / "shield-swap" / "counters" + assert first.counters_path == second.counters_path == counters / "testnet" / f"{first.address}.jsonl" + assert mainnet.counters_path == counters / "mainnet" / f"{mainnet.address}.jsonl" + assert not counters.exists() # reading the path creates nothing + + +def test_counter_ledger_differs_between_accounts(tmp_path): + first = Profile.load_or_create(tmp_path / "one") + other = Profile.load_or_create(tmp_path / "two", account="other") + assert first.address != other.address + assert first.counters_path != other.counters_path + + def test_credentials_roundtrip(tmp_path): p = Profile.load_or_create(tmp_path / "home") assert p.credentials == {} @@ -32,8 +899,7 @@ def test_credentials_roundtrip(tmp_path): p2 = Profile.load_or_create(tmp_path / "home") assert p2.credentials == {"jwt": "j", "dps_api_key": "k", "dps_consumer_id": "c"} - mode = stat.S_IMODE((p.home / "credentials.json").stat().st_mode) - assert mode == 0o600 + assert mode(p.home / "credentials.json") == 0o600 def test_journal_path(tmp_path): @@ -41,32 +907,8 @@ def test_journal_path(tmp_path): assert p.journal_path == p.home / "journal.jsonl" -def test_existing_key_imported_from_env(tmp_path, monkeypatch): - import aleo - pk = aleo.testnet.PrivateKey.random() - monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY", str(pk)) - p = Profile.load_or_create(tmp_path / "home") - assert p.private_key == str(pk) - assert p.address == str(pk.address) - - -def test_existing_key_imported_from_file(tmp_path, monkeypatch): - import aleo - pk = aleo.testnet.PrivateKey.random() - key_file = tmp_path / "key.txt" - key_file.write_text(str(pk) + "\n") - monkeypatch.delenv("SHIELD_SWAP_PRIVATE_KEY", raising=False) - monkeypatch.setenv("SHIELD_SWAP_PRIVATE_KEY_FILE", str(key_file)) - p = Profile.load_or_create(tmp_path / "home") - assert p.address == str(pk.address) - - def test_tilde_in_home_is_expanded(tmp_path, monkeypatch): - """A "~/..." string must not create a literal ~ directory in the cwd — - that would write the private key somewhere no later run looks.""" - from pathlib import Path - from aleo_shield_swap.profile import Profile - + """Expand ~ so a restart can find the profile in the expected home directory.""" monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.chdir(tmp_path) profile = Profile.load_or_create("~/.shield-swap-tilde") @@ -75,8 +917,6 @@ def test_tilde_in_home_is_expanded(tmp_path, monkeypatch): def test_tilde_in_shield_swap_home_is_expanded(tmp_path, monkeypatch): - from aleo_shield_swap.profile import Profile - monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHIELD_SWAP_HOME", "~/from-env") monkeypatch.chdir(tmp_path)