Compare commits
1 Commits
34dabf776a
...
feed6779d2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
feed6779d2 |
218
README.md
218
README.md
@@ -123,12 +123,8 @@ unavailable). The suite lives in `tests/e2e/` and is driven by
|
|||||||
`playwright-core`, whose version must stay matched to the container's Playwright
|
`playwright-core`, whose version must stay matched to the container's Playwright
|
||||||
version — the browsers ship inside the image.
|
version — the browsers ship inside the image.
|
||||||
|
|
||||||
It covers popup load, wallet creation through the UI, the Add Token screen, the
|
It covers popup load, wallet creation through the UI, the Add Token screen and
|
||||||
transaction detail screen for an ERC-20 transfer, and the recovery phrase screen
|
the transaction detail screen for an ERC-20 transfer. All outbound network is
|
||||||
— which wallet types are offered it, that it holds nothing before the password
|
|
||||||
is accepted, that a wrong password reveals nothing, that leaving it by either
|
|
||||||
route wipes it — including a leave taken while the decrypt is still running —
|
|
||||||
and that reopening the popup does not land on it. All outbound network is
|
|
||||||
intercepted at the browser level and served from fixtures in
|
intercepted at the browser level and served from fixtures in
|
||||||
`tests/e2e/network.js`, so the run is deterministic and fully offline;
|
`tests/e2e/network.js`, so the run is deterministic and fully offline;
|
||||||
unrecognised outbound requests are reported as failures rather than silently
|
unrecognised outbound requests are reported as failures rather than silently
|
||||||
@@ -149,11 +145,10 @@ page, which it does not by default — `script/test-e2e` sets
|
|||||||
`PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1` for it. Because that flag is
|
`PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1` for it. Because that flag is
|
||||||
experimental, the harness does not take it on trust. At launch it waits for the
|
experimental, the harness does not take it on trust. At launch it waits for the
|
||||||
background worker's **own** startup request — the phishing blocklist fetch that
|
background worker's **own** startup request — the phishing blocklist fetch that
|
||||||
`src/background/index.js` issues on startup, which on the suite's throwaway
|
`src/background/index.js` issues unconditionally — to arrive in the route
|
||||||
profile always happens because no previous fetch timestamp is persisted — to
|
handler, and aborts the entire suite if none does within 30 seconds
|
||||||
arrive in the route handler, and aborts the entire suite if none does within 30
|
(`tests/e2e/harness.js`). The check is passive on purpose: a synthetic probe
|
||||||
seconds (`tests/e2e/harness.js`). The check is passive on purpose: a synthetic
|
fetched from inside the worker via `worker.evaluate()` was tried first and
|
||||||
probe fetched from inside the worker via `worker.evaluate()` was tried first and
|
|
||||||
rejected, because evaluating in an extension service worker that early kills the
|
rejected, because evaluating in an extension service worker that early kills the
|
||||||
worker outright, destroying the thing being measured. Observing traffic the
|
worker outright, destroying the thing being measured. Observing traffic the
|
||||||
extension already generates perturbs nothing. Losing the race fails closed — the
|
extension already generates perturbs nothing. Losing the race fails closed — the
|
||||||
@@ -213,10 +208,9 @@ src/
|
|||||||
styles/main.css — Tailwind source
|
styles/main.css — Tailwind source
|
||||||
views/ — one JS module per screen (home, send, approval, etc.)
|
views/ — one JS module per screen (home, send, approval, etc.)
|
||||||
shared/ — modules used by both popup and background
|
shared/ — modules used by both popup and background
|
||||||
alarms.js — recurring background jobs (extension alarms API)
|
|
||||||
balances.js — ETH + ERC-20 balance fetching via RPC + Blockscout
|
balances.js — ETH + ERC-20 balance fetching via RPC + Blockscout
|
||||||
constants.js — chain IDs, default RPC endpoint, ERC-20 ABI
|
constants.js — chain IDs, default RPC endpoint, ERC-20 ABI
|
||||||
ens.js — ENS forward/reverse resolution (popup only)
|
ens.js — ENS forward/reverse resolution
|
||||||
prices.js — ETH/USD and token/USD via CoinDesk API
|
prices.js — ETH/USD and token/USD via CoinDesk API
|
||||||
scamlist.js — known fraud contract addresses
|
scamlist.js — known fraud contract addresses
|
||||||
state.js — persisted state (extension storage)
|
state.js — persisted state (extension storage)
|
||||||
@@ -230,74 +224,6 @@ manifest/
|
|||||||
firefox.json — Manifest V2 for Firefox
|
firefox.json — Manifest V2 for Firefox
|
||||||
```
|
```
|
||||||
|
|
||||||
### Background scheduling
|
|
||||||
|
|
||||||
Chrome runs `src/background/index.js` as a Manifest V3 service worker, which the
|
|
||||||
browser terminates after roughly 30 seconds idle and re-evaluates from scratch
|
|
||||||
on the next event. Two consequences shape every recurring job in the background:
|
|
||||||
|
|
||||||
- `setInterval` and `setTimeout` are useless. They are destroyed with the
|
|
||||||
worker, so a job scheduled that way runs until the first idle period and never
|
|
||||||
again. Both recurring jobs — the 60-second balance refresh and the 24-hour
|
|
||||||
phishing blocklist refresh — are scheduled through the extension alarms API
|
|
||||||
(`src/shared/alarms.js`) instead. The browser holds the schedule and wakes the
|
|
||||||
worker to deliver it. Alarm periods are clamped to a one-minute minimum, so
|
|
||||||
the balance refresh is expressed as exactly one minute and nothing is silently
|
|
||||||
slowed down.
|
|
||||||
- Module-level variables do not survive either. Anything that must be remembered
|
|
||||||
across a restart goes in extension storage, including the timestamp of the
|
|
||||||
last phishing list fetch: without it a revived worker would either re-fetch on
|
|
||||||
every wake or, with a naive in-memory guard, never notice that an update is
|
|
||||||
due. `localStorage` does not exist in a service worker at all — the one
|
|
||||||
remaining user of it, `src/shared/ens.js`, runs only in the popup and is
|
|
||||||
marked as such.
|
|
||||||
|
|
||||||
Both jobs also carry a freshness guard, and a guard must never be timed to the
|
|
||||||
alarm period it gates. Each guard is measured from the moment the last run
|
|
||||||
finished, which is one run-duration after the alarm that started it, so a guard
|
|
||||||
of exactly one period vetoes the very next tick and the real cadence becomes two
|
|
||||||
periods. The two jobs solve this differently, because their guards exist for
|
|
||||||
different reasons:
|
|
||||||
|
|
||||||
- The phishing refresh has a 24-hour cache TTL whose job is to keep the worker
|
|
||||||
off the network on the wakes between scheduled refreshes — Chrome revives the
|
|
||||||
worker every ~30 seconds while the browser is busy, and every revival runs the
|
|
||||||
startup path. The scheduled alarm tick is not one of those wakes, so it
|
|
||||||
bypasses the TTL and fetches unconditionally. Shortening the TTL instead would
|
|
||||||
not work: the startup path re-checks it on every wake, so a shorter TTL simply
|
|
||||||
becomes the real refresh rate.
|
|
||||||
- The balance refresh guard exists to skip work an open popup has already done —
|
|
||||||
the popup refreshes every 10 seconds and stamps the same field. That has to
|
|
||||||
keep applying on the scheduled tick, so the guard is shortened to half the
|
|
||||||
alarm period instead of bypassed: comfortably above the popup's 10 seconds, so
|
|
||||||
an open popup still suppresses the background job, and comfortably below the
|
|
||||||
60-second period, so the schedule always wins.
|
|
||||||
|
|
||||||
Two timestamps are persisted for the phishing list, not one. `lastFetchTime`
|
|
||||||
records a fetch that produced a usable delta and drives the TTL.
|
|
||||||
`lastAttemptTime` records that the network was contacted at all, and is written
|
|
||||||
even when the result is unusable — a failed request, or a delta over the 256 KiB
|
|
||||||
cap. Without it those cases leave no freshness mark and the worker re-downloads
|
|
||||||
the full blocklist on every wake, indefinitely; with it, unscheduled retries are
|
|
||||||
floored at one hour. Both are discarded on load if they are in the future, since
|
|
||||||
a stamp from a skewed clock or a restored backup would otherwise suppress
|
|
||||||
updates until that time arrives, permanently and with no way out.
|
|
||||||
|
|
||||||
The startup path (`ensureRecurringAlarms()` plus the phishing list init) runs on
|
|
||||||
`onInstalled`, on `onStartup`, and at the top level of the worker, so every way
|
|
||||||
the background context can start re-establishes the schedule. On a fresh install
|
|
||||||
more than one of those fires, so they share a single in-flight run rather than
|
|
||||||
racing. It is idempotent: an alarm that already exists with the period the code
|
|
||||||
asks for is left alone, because re-creating one restarts its schedule and a busy
|
|
||||||
extension would push the next fire out indefinitely. An alarm carrying a
|
|
||||||
different period — one created by an earlier version — is re-created once, or a
|
|
||||||
period changed in a new release would never reach an existing install.
|
|
||||||
|
|
||||||
Firefox uses Manifest V2 with a persistent background page, where timers would
|
|
||||||
survive. Both browsers are built from one bundle and both take the alarm path,
|
|
||||||
so there is a single code path to reason about; `"alarms"` is declared in both
|
|
||||||
`manifest/chrome.json` and `manifest/firefox.json`.
|
|
||||||
|
|
||||||
### UI Design Philosophy
|
### UI Design Philosophy
|
||||||
|
|
||||||
The UI is inspired by _Universal Paperclips_. It's deliberately minimal,
|
The UI is inspired by _Universal Paperclips_. It's deliberately minimal,
|
||||||
@@ -480,11 +406,8 @@ runtime debug mode is on, or when the active network is a testnet. They are not
|
|||||||
repeated in the element lists below.
|
repeated in the element lists below.
|
||||||
|
|
||||||
Closing and reopening the popup returns to the screen the user was last on only
|
Closing and reopening the popup returns to the screen the user was last on only
|
||||||
for the views listed in `RESTORABLE_VIEWS` (`src/popup/restorableViews.js`).
|
for the views listed in `RESTORABLE_VIEWS` (`src/popup/index.js`). Every other
|
||||||
Every other screen falls back to Home. The screens that display a secret —
|
screen, including ExportPrivKey, falls back to Home.
|
||||||
ExportPrivKey and ShowRecoveryPhrase — are deliberately absent from that list,
|
|
||||||
so the popup can never reopen onto one of them with no password prompt in front
|
|
||||||
of it.
|
|
||||||
|
|
||||||
#### Welcome (`welcome`)
|
#### Welcome (`welcome`)
|
||||||
|
|
||||||
@@ -652,26 +575,16 @@ of it.
|
|||||||
- To: blockie + color dot + full address + etherscan link + ENS name
|
- To: blockie + color dot + full address + etherscan link + ENS name
|
||||||
- Amount: value + symbol (USD in parentheses)
|
- Amount: value + symbol (USD in parentheses)
|
||||||
- Your balance: value + symbol (USD in parentheses)
|
- Your balance: value + symbol (USD in parentheses)
|
||||||
- Network fee: "Estimating..." then two lines, or "Unable to estimate",
|
- Estimated network fee: "Estimating..." then the ETH amount (USD in
|
||||||
fetched async. The first line is what the transfer is expected to cost,
|
parentheses) or "Unable to estimate", fetched async
|
||||||
`gasLimit * gasPrice` (USD in parentheses); the second is the
|
|
||||||
`gasLimit * maxFeePerGas` reserve the node requires, which is what the
|
|
||||||
balance check gates on. The second line is omitted on a network with no
|
|
||||||
type-2 pricing, where the two are the same number, but its space is
|
|
||||||
reserved either way
|
|
||||||
- Warnings: inline warnings from the local checks (scam address, self-send)
|
- Warnings: inline warnings from the local checks (scam address, self-send)
|
||||||
plus four reserved warning boxes made visible by the async checks —
|
plus four reserved warning boxes made visible by the async checks —
|
||||||
recipient with no transaction history, recipient is a contract, burn
|
recipient with no transaction history, recipient is a contract, burn
|
||||||
address, and an Etherscan phishing/scam label
|
address, and an Etherscan phishing/scam label
|
||||||
- Errors (insufficient balance), plus three reserved error boxes — the
|
- Errors (insufficient balance)
|
||||||
amount plus the fee exceeds the balance (ETH transfers), not enough ETH to
|
|
||||||
pay the fee for the transfer (ERC-20 transfers), and the fee could not be
|
|
||||||
estimated. The first two are mutually exclusive per transfer type, so only
|
|
||||||
the applicable one holds space
|
|
||||||
- Password: an inline field on this screen, not a modal, with its own error
|
- Password: an inline field on this screen, not a modal, with its own error
|
||||||
line
|
line
|
||||||
- "Sign & Send" button (disabled if errors, and while the network fee
|
- "Sign & Send" button (disabled if errors)
|
||||||
estimate is pending or unavailable)
|
|
||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
||||||
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
||||||
@@ -692,19 +605,13 @@ of it.
|
|||||||
persisted: closing and reopening the popup resumes the poll, with the elapsed
|
persisted: closing and reopening the popup resumes the poll, with the elapsed
|
||||||
counter and the timeout deadline still measured from the original broadcast. A
|
counter and the timeout deadline still measured from the original broadcast. A
|
||||||
lookup that fails is retried on the next tick rather than counted as a missing
|
lookup that fails is retried on the next tick rather than counted as a missing
|
||||||
receipt, because a failed lookup says nothing about the transaction; but six
|
receipt.
|
||||||
failures in a row (60 seconds at the poll cadence) end the wait, so an RPC
|
|
||||||
that never answers cannot leave it running indefinitely. Any lookup that
|
|
||||||
answers resets that count.
|
|
||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- Receipt found → **SuccessTx**
|
- Receipt found → **SuccessTx**
|
||||||
- A lookup that answers "no receipt" 60 seconds or more after broadcast →
|
- A lookup that answers "no receipt" 60 seconds or more after broadcast →
|
||||||
**ErrorTx** (timeout message)
|
**ErrorTx** (timeout message)
|
||||||
- Six consecutive failed lookups → **ErrorTx**, with a message naming the
|
- Exactly one of the two: a receipt found on the tick that crosses the
|
||||||
unreachable network and pointing at the RPC URL in Settings. This is a
|
deadline wins, and neither outcome can be rendered over the other
|
||||||
different fact from the timeout — the chain was never asked — and says so
|
|
||||||
- Exactly one outcome: a receipt found on the tick that crosses the deadline
|
|
||||||
wins, and no outcome can be rendered over another
|
|
||||||
|
|
||||||
#### SuccessTx (`success-tx`)
|
#### SuccessTx (`success-tx`)
|
||||||
|
|
||||||
@@ -807,13 +714,12 @@ of it.
|
|||||||
- **When**: User tapped the Settings gear.
|
- **When**: User tapped the Settings gear.
|
||||||
- **Elements**:
|
- **Elements**:
|
||||||
- "Back" button, "Settings" heading
|
- "Back" button, "Settings" heading
|
||||||
- Wallets: one row per wallet with its name (tap to rename inline), a
|
- Wallets: one row per wallet with its name (tap to rename inline) and an
|
||||||
`[recovery phrase]` button on HD wallets only, and an `[x]` delete button,
|
`[x]` delete button, plus a "+ Add wallet" button
|
||||||
plus a "+ Add wallet" button
|
|
||||||
- Tracked Tokens: one row per tracked token with an `[x]` remove button,
|
- Tracked Tokens: one row per tracked token with an `[x]` remove button,
|
||||||
plus a "+ Add token" button
|
plus a "+ Add token" button
|
||||||
- Display: "Show tracked tokens with zero balance" checkbox, "UTC
|
- Display: "Show tracked tokens with zero balance" checkbox and a Theme
|
||||||
Timestamps" checkbox, and a Theme selector (System / Light / Dark)
|
selector (System / Light / Dark)
|
||||||
- Network: network selector (Ethereum Mainnet / Sepolia Testnet); switching
|
- Network: network selector (Ethereum Mainnet / Sepolia Testnet); switching
|
||||||
resets the RPC and Blockscout endpoints to that network's defaults
|
resets the RPC and Blockscout endpoints to that network's defaults
|
||||||
- Ethereum RPC: endpoint URL input + "Save" button (validated against
|
- Ethereum RPC: endpoint URL input + "Save" button (validated against
|
||||||
@@ -821,10 +727,10 @@ of it.
|
|||||||
- Blockscout API: endpoint URL input + "Save" button (validated against
|
- Blockscout API: endpoint URL input + "Save" button (validated against
|
||||||
`/stats` before being saved)
|
`/stats` before being saved)
|
||||||
- Token Spam Protection:
|
- Token Spam Protection:
|
||||||
- "Hide fake tokens impersonating a known symbol" checkbox
|
|
||||||
- "Hide tokens with fewer than 1,000 holders" checkbox
|
- "Hide tokens with fewer than 1,000 holders" checkbox
|
||||||
- "Hide transactions from detected fraud contracts" checkbox
|
- "Hide transactions from detected fraud contracts" checkbox
|
||||||
- "Hide dust transactions below N gwei" checkbox + threshold input
|
- "Hide dust transactions below N gwei" checkbox + threshold input
|
||||||
|
- "UTC Timestamps" checkbox
|
||||||
- Allowed Sites: list with remove buttons
|
- Allowed Sites: list with remove buttons
|
||||||
- Denied Sites: list with remove buttons
|
- Denied Sites: list with remove buttons
|
||||||
- About: project link, license, author, version, release date, and the
|
- About: project link, license, author, version, release date, and the
|
||||||
@@ -834,7 +740,6 @@ of it.
|
|||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- "+ Add wallet" → **AddWallet**
|
- "+ Add wallet" → **AddWallet**
|
||||||
- "+ Add token" → **SettingsAddToken**
|
- "+ Add token" → **SettingsAddToken**
|
||||||
- `[recovery phrase]` on an HD wallet → **ShowRecoveryPhrase**
|
|
||||||
- `[x]` on a wallet → **DeleteWallet**
|
- `[x]` on a wallet → **DeleteWallet**
|
||||||
- Tap wallet name → inline rename field (no screen change)
|
- Tap wallet name → inline rename field (no screen change)
|
||||||
- `[x]` on a tracked token or a site → removes it in place (no screen
|
- `[x]` on a tracked token or a site → removes it in place (no screen
|
||||||
@@ -842,33 +747,6 @@ of it.
|
|||||||
- Ten clicks on the version → reveals the Debug well (no screen change)
|
- Ten clicks on the version → reveals the Debug well (no screen change)
|
||||||
- "Back" (or Settings gear again) → previous screen (Home)
|
- "Back" (or Settings gear again) → previous screen (Home)
|
||||||
|
|
||||||
#### ShowRecoveryPhrase (`show-phrase`)
|
|
||||||
|
|
||||||
- **When**: User tapped `[recovery phrase]` on a wallet row in Settings. HD
|
|
||||||
wallets only: key and xprv wallets have no recovery phrase, so their rows do
|
|
||||||
not offer the action at all.
|
|
||||||
- **Elements**:
|
|
||||||
- "Back" button, "Recovery Phrase" heading
|
|
||||||
- Wallet name
|
|
||||||
- Warning box stating that anyone holding these words can take everything in
|
|
||||||
the wallet, from any device, without the password
|
|
||||||
- Error line
|
|
||||||
- Password input + "Reveal" button, shown until the password is accepted
|
|
||||||
- The recovery phrase itself, in full and click-to-copy, shown only after a
|
|
||||||
correct password and in place of the password prompt
|
|
||||||
- **Transitions**:
|
|
||||||
- "Reveal" (correct password) → the phrase replaces the password prompt (no
|
|
||||||
screen change)
|
|
||||||
- "Reveal" (wrong password) → full-sentence error, nothing revealed (no
|
|
||||||
screen change)
|
|
||||||
- "Back" → previous screen (Settings)
|
|
||||||
- **Secret handling**: nothing is decrypted or written into the page until the
|
|
||||||
password is accepted; the phrase is never stored in state, and it is wiped
|
|
||||||
from the page whenever the screen is left by any route, including the Settings
|
|
||||||
gear. A decrypt still running when the screen is left is discarded rather than
|
|
||||||
written. The screen is not restorable, so reopening the popup lands on Home
|
|
||||||
rather than back on the phrase.
|
|
||||||
|
|
||||||
#### DeleteWallet (`delete-wallet-confirm`)
|
#### DeleteWallet (`delete-wallet-confirm`)
|
||||||
|
|
||||||
- **When**: User tapped the `[x]` next to a wallet in Settings.
|
- **When**: User tapped the `[x]` next to a wallet in Settings.
|
||||||
@@ -1031,14 +909,9 @@ CoinDesk price API, and Blockscout API), AutistMask also contacts:
|
|||||||
- **Phishing domain blocklist**: A community-maintained phishing domain
|
- **Phishing domain blocklist**: A community-maintained phishing domain
|
||||||
blocklist is vendored into the extension at build time. At runtime, the
|
blocklist is vendored into the extension at build time. At runtime, the
|
||||||
extension fetches the live list once every 24 hours to detect newly added
|
extension fetches the live list once every 24 hours to detect newly added
|
||||||
domains, plus once on a start where the list is more than 24 hours old. Only
|
domains. Only the delta (domains not already in the vendored list) is kept in
|
||||||
the delta (domains not already in the vendored list) is kept in memory,
|
memory, keeping runtime memory usage small. The delta is persisted to
|
||||||
keeping runtime memory usage small. The delta and the timestamp of the fetch
|
localStorage if it is under 256 KiB.
|
||||||
that produced it are persisted to extension storage if the record is under 256
|
|
||||||
KiB; an oversized delta is dropped along with its timestamp, so a later start
|
|
||||||
fetches again rather than claiming freshness for data it no longer holds. A
|
|
||||||
fetch that fails, or one whose delta was too large to store, is not retried
|
|
||||||
more than once an hour outside the 24-hour schedule.
|
|
||||||
- **Etherscan address labels**: When confirming a transaction, the extension
|
- **Etherscan address labels**: When confirming a transaction, the extension
|
||||||
performs a best-effort lookup of the recipient address on Etherscan to check
|
performs a best-effort lookup of the recipient address on Etherscan to check
|
||||||
for phishing/scam labels. This is a direct page fetch with no API key; the
|
for phishing/scam labels. This is a direct page fetch with no API key; the
|
||||||
@@ -1215,19 +1088,7 @@ indexes it as a real token transfer.
|
|||||||
a spoof and filtered from display. The fake "Ethereum" token in the attack
|
a spoof and filtered from display. The fake "Ethereum" token in the attack
|
||||||
above used symbol "ETH" from contract
|
above used symbol "ETH" from contract
|
||||||
`0xD05339f9Ea5ab9d9F03B9d57F671d2abD1F55c82`, which does not match the known
|
`0xD05339f9Ea5ab9d9F03B9d57F671d2abD1F55c82`, which does not match the known
|
||||||
WETH contract — so it would be caught by this check. Detecting a spoof is also
|
WETH contract — so it would be caught by this check.
|
||||||
what adds a contract to the fraud contract blocklist below; that is the only
|
|
||||||
thing that populates it. In the transaction history the check is the "Hide
|
|
||||||
fake tokens impersonating a known symbol" setting, on by default; with it off,
|
|
||||||
spoofed transfers are shown and no new blocklist entries are learned from
|
|
||||||
them. The send-screen token selector applies the same check unconditionally,
|
|
||||||
because it decides which tokens the user can act on rather than what the
|
|
||||||
history displays. The balance list applies it unconditionally too, but not
|
|
||||||
identically: it exempts symbols that `KNOWN_SYMBOLS` maps to `null`, and
|
|
||||||
`"ETH"` is the only one. So the fake "Ethereum" token above is filtered from
|
|
||||||
the transaction history and from the send selector, but a fake-`ETH` ERC-20
|
|
||||||
that clears the balance list's own 1,000-holder floor — or that the user
|
|
||||||
tracked manually — is still shown in the balance list.
|
|
||||||
|
|
||||||
- **Low-holder token filtering**: Token transfers from ERC-20 contracts with
|
- **Low-holder token filtering**: Token transfers from ERC-20 contracts with
|
||||||
fewer than 1,000 holders are hidden from transaction history by default.
|
fewer than 1,000 holders are hidden from transaction history by default.
|
||||||
@@ -1254,22 +1115,13 @@ indexes it as a real token transfer.
|
|||||||
it. AutistMask hides transactions below a configurable dust threshold
|
it. AutistMask hides transactions below a configurable dust threshold
|
||||||
(default: 100,000 gwei / 0.0001 ETH). This is high enough to filter poisoning
|
(default: 100,000 gwei / 0.0001 ETH). This is high enough to filter poisoning
|
||||||
dust while low enough to preserve any transfer a user would plausibly care
|
dust while low enough to preserve any transfer a user would plausibly care
|
||||||
about. The threshold is user-configurable in Settings; a threshold of `0`
|
about. The threshold is user-configurable in Settings.
|
||||||
hides nothing, exactly as clearing the checkbox does.
|
|
||||||
|
|
||||||
- **User-configurable**: All four filters (known symbol verification, low-holder
|
- **User-configurable**: All of the above filters (known symbol verification,
|
||||||
threshold, fraud contract blocklist, dust threshold) are settings that default
|
low-holder threshold, fraud contract blocklist, dust threshold) are settings
|
||||||
to on but can be individually disabled by the user. AutistMask is designed as
|
that default to on but can be individually disabled by the user. AutistMask is
|
||||||
a sharp tool — users who understand the risks can configure the wallet to show
|
designed as a sharp tool — users who understand the risks can configure the
|
||||||
everything unfiltered, unix-style. All four settings govern the transaction
|
wallet to show everything unfiltered, unix-style.
|
||||||
history; what else each one reaches varies. The known-symbol check also runs
|
|
||||||
unconditionally on the send-screen token selector, and on the balance list
|
|
||||||
except for symbols mapped to `null` (`"ETH"` alone), which the balance list
|
|
||||||
does not filter. The fraud contract blocklist is applied unconditionally on
|
|
||||||
that selector and is not consulted by the balance list at all. The low-holder
|
|
||||||
setting also gates the send selector, while the balance list's own
|
|
||||||
1,000-holder floor is unconditional (see Data Model). The dust threshold
|
|
||||||
applies to the transaction history alone.
|
|
||||||
|
|
||||||
#### Phishing Domain Protection
|
#### Phishing Domain Protection
|
||||||
|
|
||||||
@@ -1281,12 +1133,6 @@ live list once every 24 hours and keeps only the delta (newly added domains not
|
|||||||
in the vendored list) in memory. This architecture keeps runtime memory usage
|
in the vendored list) in memory. This architecture keeps runtime memory usage
|
||||||
small while ensuring fresh coverage of new phishing domains.
|
small while ensuring fresh coverage of new phishing domains.
|
||||||
|
|
||||||
The 24-hour cadence is an alarm, not a timer; the alarm tick fetches
|
|
||||||
unconditionally rather than re-checking the 24-hour cache TTL that gates the
|
|
||||||
startup path; and the fetch timestamps live in extension storage rather than in
|
|
||||||
module variables — see [Background scheduling](#background-scheduling) for why
|
|
||||||
all three are required.
|
|
||||||
|
|
||||||
When a dApp on a blocklisted domain requests a wallet connection, transaction
|
When a dApp on a blocklisted domain requests a wallet connection, transaction
|
||||||
approval, or signature, the approval popup displays a prominent red warning
|
approval, or signature, the approval popup displays a prominent red warning
|
||||||
banner alerting the user. The domain checker matches exact hostnames and all
|
banner alerting the user. The domain checker matches exact hostnames and all
|
||||||
@@ -1342,7 +1188,7 @@ Currently supported:
|
|||||||
|
|
||||||
- [x] Delete wallet (with confirmation)
|
- [x] Delete wallet (with confirmation)
|
||||||
- [ ] Delete address from HD wallet (with confirmation)
|
- [ ] Delete address from HD wallet (with confirmation)
|
||||||
- [x] Show wallet's recovery phrase (requires password)
|
- [ ] Show wallet's recovery phrase (requires password)
|
||||||
|
|
||||||
### Transactions
|
### Transactions
|
||||||
|
|
||||||
|
|||||||
41
TODO.md
41
TODO.md
@@ -44,42 +44,6 @@ undefined identifiers, which is how
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
- 2026-08-11: Known-symbol spoof verification became a Settings toggle
|
|
||||||
(`hideSpoofedSymbols`), on by default, governing the transaction-history
|
|
||||||
filter and the fraud-contract learning it feeds
|
|
||||||
([#176](https://git.eeqj.de/sneak/AutistMask/issues/176)).
|
|
||||||
- 2026-08-11: `script/verify-build` now walks `dist/` NUL-delimited and asserts
|
|
||||||
`dist/` is a real directory, so a path with a trailing space or a newline can
|
|
||||||
no longer carry a debug marker past the unlisted-bundle check
|
|
||||||
([#223](https://git.eeqj.de/sneak/AutistMask/issues/223)).
|
|
||||||
- 2026-08-11: UTC Timestamps checkbox moved from the Token Spam Protection well
|
|
||||||
into Display, next to the theme selector
|
|
||||||
([#212](https://git.eeqj.de/sneak/AutistMask/issues/212)).
|
|
||||||
- 2026-08-11: Network fee counted in the confirmation-screen balance check for
|
|
||||||
both ETH and ERC-20 sends, reserving what the node actually charges a type-2
|
|
||||||
transaction, with the arithmetic in a pure, unit-tested
|
|
||||||
`src/shared/txValidation.js`
|
|
||||||
([#154](https://git.eeqj.de/sneak/AutistMask/issues/154)).
|
|
||||||
- 2026-08-11: A dust threshold of `0` now means "hide nothing" instead of
|
|
||||||
falling back to the 100,000 gwei default, and every address comparison in
|
|
||||||
`src/shared/transactions.js` goes through one case-normalising helper so a
|
|
||||||
checksummed genuine contract is no longer read as a spoof
|
|
||||||
([#179](https://git.eeqj.de/sneak/AutistMask/issues/179)).
|
|
||||||
- 2026-08-11: Password-gated recovery phrase display for HD wallets, reached
|
|
||||||
from the wallet row in Settings, wiped on leaving the screen and excluded from
|
|
||||||
the views the popup can reopen onto
|
|
||||||
([#161](https://git.eeqj.de/sneak/AutistMask/issues/161)).
|
|
||||||
- 2026-08-11: Extended-key import hardened — the base58 checksum is now enforced
|
|
||||||
on every xprv and xpub, and a non-master key is refused with an explanation
|
|
||||||
instead of being derived beneath
|
|
||||||
([#210](https://git.eeqj.de/sneak/AutistMask/issues/210)).
|
|
||||||
- 2026-08-11: the balance refresh and the 24-hour phishing list refresh moved
|
|
||||||
from `setInterval` to the extension alarms API, with the phishing delta and
|
|
||||||
its fetch timestamps persisted to extension storage, so neither job dies with
|
|
||||||
the MV3 service worker. Each job's freshness guard was decoupled from its
|
|
||||||
alarm period at the same time — timed to the period, a guard vetoes its own
|
|
||||||
scheduled tick and halves the real refresh rate
|
|
||||||
([#158](https://git.eeqj.de/sneak/AutistMask/issues/158)).
|
|
||||||
- 2026-08-11: Policy compliance sweep — conditional verbose test rerun, local
|
- 2026-08-11: Policy compliance sweep — conditional verbose test rerun, local
|
||||||
Tailwind binary instead of `npx`, `--frozen-lockfile` on `make install`, and
|
Tailwind binary instead of `npx`, `--frozen-lockfile` on `make install`, and
|
||||||
the Makefile-only targets documented in the README
|
the Makefile-only targets documented in the README
|
||||||
@@ -108,9 +72,8 @@ undefined identifiers, which is how
|
|||||||
([#195](https://git.eeqj.de/sneak/AutistMask/issues/195)).
|
([#195](https://git.eeqj.de/sneak/AutistMask/issues/195)).
|
||||||
- 2026-08-11: WaitTx lifecycle: a receipt and the 60-second timeout can no
|
- 2026-08-11: WaitTx lifecycle: a receipt and the 60-second timeout can no
|
||||||
longer both render on one tick, no timer or in-flight lookup outlives its
|
longer both render on one tick, no timer or in-flight lookup outlives its
|
||||||
wait, a failed receipt lookup no longer counts as a timeout (but six in a row
|
wait, a failed receipt lookup no longer counts as a timeout, and the wait now
|
||||||
end the wait, reported as an unreachable network rather than as a timeout),
|
resumes after a popup close
|
||||||
and the wait now resumes after a popup close
|
|
||||||
([#155](https://git.eeqj.de/sneak/AutistMask/issues/155)).
|
([#155](https://git.eeqj.de/sneak/AutistMask/issues/155)).
|
||||||
- 2026-08-11: Wallet deletion repairs its own state — `hasWallet` follows the
|
- 2026-08-11: Wallet deletion repairs its own state — `hasWallet` follows the
|
||||||
remaining wallets, the selection only moves when it was deleted, and the
|
remaining wallets, the selection only moves when it was deleted, and the
|
||||||
|
|||||||
@@ -130,14 +130,10 @@ live list to pick up newly added domains, keeping only the entries not already
|
|||||||
in the bundled copy (persisted locally if under 256 KiB). This endpoint is not
|
in the bundled copy (persisted locally if under 256 KiB). This endpoint is not
|
||||||
user-configurable.
|
user-configurable.
|
||||||
|
|
||||||
When it is contacted: when the background script starts, if the last fetch was
|
When it is contacted: once when the background script starts, and every 24 hours
|
||||||
more than 24 hours ago, and every 24 hours after that. The time of the last
|
after that. It is a plain download of a public file — nothing about you is sent,
|
||||||
fetch is remembered across browser and background restarts, so restarting does
|
but the host sees your IP address. If the fetch fails, the bundled copy is still
|
||||||
not cause a re-download. If a fetch fails, or the list is too large to keep, the
|
used.
|
||||||
extension waits an hour before trying again outside that 24-hour schedule rather
|
|
||||||
than retrying on every restart. It is a plain download of a public file —
|
|
||||||
nothing about you is sent, but the host sees your IP address. If the fetch
|
|
||||||
fails, the bundled copy is still used.
|
|
||||||
|
|
||||||
**Etherscan address labels** (`etherscan.io`; `sepolia.etherscan.io` on Sepolia)
|
**Etherscan address labels** (`etherscan.io`; `sepolia.etherscan.io` on Sepolia)
|
||||||
|
|
||||||
@@ -269,10 +265,7 @@ The confirmation screen shows:
|
|||||||
- **From and To addresses** with identicons and Etherscan links
|
- **From and To addresses** with identicons and Etherscan links
|
||||||
- **Amount** with USD estimate
|
- **Amount** with USD estimate
|
||||||
- **Your current balance** with USD estimate
|
- **Your current balance** with USD estimate
|
||||||
- **Network fee** — what the transfer is expected to cost, in ETH with a USD
|
- **Estimated network fee** in ETH with USD estimate
|
||||||
estimate, and below it the larger amount reserved until it confirms. The
|
|
||||||
reserve is what the network requires up front and what the balance check gates
|
|
||||||
on; the refund of the difference is why the two differ
|
|
||||||
- **Warnings** if the recipient is a contract, a burn address, one of your own
|
- **Warnings** if the recipient is a contract, a burn address, one of your own
|
||||||
addresses, on the bundled scam-address list, or labelled as a phisher on
|
addresses, on the bundled scam-address list, or labelled as a phisher on
|
||||||
Etherscan
|
Etherscan
|
||||||
@@ -330,14 +323,7 @@ by default:
|
|||||||
**Known token symbol verification.** AutistMask ships a list of roughly 500
|
**Known token symbol verification.** AutistMask ships a list of roughly 500
|
||||||
legitimate ERC-20 tokens with their contract addresses. If a transaction or
|
legitimate ERC-20 tokens with their contract addresses. If a transaction or
|
||||||
balance claims to involve a known symbol (like "ETH" or "USDT") but comes from
|
balance claims to involve a known symbol (like "ETH" or "USDT") but comes from
|
||||||
an unrecognized contract, it is identified as a spoof and hidden. In your
|
an unrecognized contract, it is identified as a spoof and hidden.
|
||||||
transaction history this is the "Hide fake tokens impersonating a known symbol"
|
|
||||||
setting, which you can switch off; doing so also stops new entries being added
|
|
||||||
to the fraud contract blocklist below, since detecting a spoof is what fills it.
|
|
||||||
The send token list always applies the check. Your balances apply it too, with
|
|
||||||
one exception: a token claiming the symbol "ETH" is not filtered there, so a
|
|
||||||
fake "ETH" token can still show up in your balance list even though it is hidden
|
|
||||||
from your transaction history and from the send token list.
|
|
||||||
|
|
||||||
**Low-holder token filtering.** Tokens with fewer than 1,000 holders are hidden
|
**Low-holder token filtering.** Tokens with fewer than 1,000 holders are hidden
|
||||||
from transaction history and the send token list, and are left out of your
|
from transaction history and the send token list, and are left out of your
|
||||||
@@ -373,16 +359,16 @@ Click the gear icon on the home screen to access settings:
|
|||||||
- **Wallets**: Your wallets, and "+ Add wallet".
|
- **Wallets**: Your wallets, and "+ Add wallet".
|
||||||
- **Tracked Tokens**: The ERC-20 tokens tracked across all addresses, and "+ Add
|
- **Tracked Tokens**: The ERC-20 tokens tracked across all addresses, and "+ Add
|
||||||
token".
|
token".
|
||||||
- **Display**: Toggle whether tracked tokens with zero balance are shown, switch
|
- **Display**: Toggle whether tracked tokens with zero balance are shown, and
|
||||||
timestamps to UTC, and choose the theme (System, Light, or Dark).
|
choose the theme (System, Light, or Dark).
|
||||||
- **Network**: Switch between Ethereum Mainnet and Sepolia Testnet. Switching
|
- **Network**: Switch between Ethereum Mainnet and Sepolia Testnet. Switching
|
||||||
resets the RPC and Blockscout endpoints to that network's defaults.
|
resets the RPC and Blockscout endpoints to that network's defaults.
|
||||||
- **Ethereum RPC**: Change the Ethereum node endpoint. Default is a public RPC.
|
- **Ethereum RPC**: Change the Ethereum node endpoint. Default is a public RPC.
|
||||||
You can use your own node for maximum privacy.
|
You can use your own node for maximum privacy.
|
||||||
- **Blockscout API**: Change the Blockscout instance used for token balances and
|
- **Blockscout API**: Change the Blockscout instance used for token balances and
|
||||||
transaction history. You can use a self-hosted instance.
|
transaction history. You can use a self-hosted instance.
|
||||||
- **Token Spam Protection**: Toggle individual scam filters and set the dust
|
- **Token Spam Protection**: Toggle individual scam filters, set the dust
|
||||||
transaction threshold.
|
transaction threshold, and switch timestamps to UTC.
|
||||||
- **Allowed Sites / Denied Sites**: View and manage web3 site permissions.
|
- **Allowed Sites / Denied Sites**: View and manage web3 site permissions.
|
||||||
- **About**: License, author, version, release date, and a link to the commit
|
- **About**: License, author, version, release date, and a link to the commit
|
||||||
this build came from.
|
this build came from.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "AutistMask",
|
"name": "AutistMask",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Minimal Ethereum wallet for Chrome",
|
"description": "Minimal Ethereum wallet for Chrome",
|
||||||
"permissions": ["storage", "activeTab", "alarms"],
|
"permissions": ["storage", "activeTab"],
|
||||||
"host_permissions": ["<all_urls>"],
|
"host_permissions": ["<all_urls>"],
|
||||||
"action": {
|
"action": {
|
||||||
"default_popup": "src/popup/index.html"
|
"default_popup": "src/popup/index.html"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "AutistMask",
|
"name": "AutistMask",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Minimal Ethereum wallet for Firefox",
|
"description": "Minimal Ethereum wallet for Firefox",
|
||||||
"permissions": ["storage", "activeTab", "alarms", "<all_urls>"],
|
"permissions": ["storage", "activeTab", "<all_urls>"],
|
||||||
"browser_action": {
|
"browser_action": {
|
||||||
"default_popup": "src/popup/index.html"
|
"default_popup": "src/popup/index.html"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,18 +22,6 @@ set -eu
|
|||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
# Absolute path to this script, resolved before anything cd's anywhere.
|
|
||||||
# check_unlisted_bundles re-invokes it through xargs, and $0 on its own may be
|
|
||||||
# relative to a directory we are about to leave.
|
|
||||||
SELF="$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")"
|
|
||||||
|
|
||||||
# Internal re-entry flag; see scan_dist_paths.
|
|
||||||
SCAN_FLAG="--scan-dist-paths"
|
|
||||||
|
|
||||||
# A literal newline, for the is_listed guard.
|
|
||||||
NEWLINE='
|
|
||||||
'
|
|
||||||
|
|
||||||
MANIFEST="dist/constants-bundles.txt"
|
MANIFEST="dist/constants-bundles.txt"
|
||||||
MARKER_ON="autistmask-build-debug=on"
|
MARKER_ON="autistmask-build-debug=on"
|
||||||
MARKER_OFF="autistmask-build-debug=off"
|
MARKER_OFF="autistmask-build-debug=off"
|
||||||
@@ -41,20 +29,11 @@ MARKER_OFF="autistmask-build-debug=off"
|
|||||||
# Set by read_marker.
|
# Set by read_marker.
|
||||||
MARKER=""
|
MARKER=""
|
||||||
|
|
||||||
# Temporary file holding the NUL-delimited dist/ listing, removed by the EXIT
|
|
||||||
# trap because fail() exits from wherever it is called.
|
|
||||||
LISTING=""
|
|
||||||
|
|
||||||
fail() {
|
fail() {
|
||||||
echo "verify-build: FAIL: $*" >&2
|
echo "verify-build: FAIL: $*" >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
[ -z "$LISTING" ] || rm -f "$LISTING"
|
|
||||||
}
|
|
||||||
trap cleanup EXIT
|
|
||||||
|
|
||||||
# Is the literal $1 present in the file $2? Match (grep exit 0) and no-match
|
# Is the literal $1 present in the file $2? Match (grep exit 0) and no-match
|
||||||
# (exit 1) are answers about the emitted output. Anything else (exit 2: the
|
# (exit 1) are answers about the emitted output. Anything else (exit 2: the
|
||||||
# file could not be read) is not an answer at all, and must not be reported as
|
# file could not be read) is not an answer at all, and must not be reported as
|
||||||
@@ -79,17 +58,7 @@ has_marker() {
|
|||||||
# manifest could not be read and is not an answer at all. Without this, an
|
# manifest could not be read and is not an answer at all. Without this, an
|
||||||
# unreadable manifest reads as "this file is not listed" and every emitted
|
# unreadable manifest reads as "this file is not listed" and every emitted
|
||||||
# bundle gets reported as an unlisted one.
|
# bundle gets reported as an unlisted one.
|
||||||
#
|
|
||||||
# A path containing a newline is answered without asking grep, because grep
|
|
||||||
# would read the pattern as two patterns and report a match on either. That is
|
|
||||||
# how such a path escaped this check even once the walk stopped splitting it:
|
|
||||||
# the half before the newline matched a listed line and the file was skipped.
|
|
||||||
# The manifest is line-delimited, so it cannot name such a path at all, and
|
|
||||||
# "not listed" is the only true answer.
|
|
||||||
is_listed() {
|
is_listed() {
|
||||||
case "$1" in
|
|
||||||
*"$NEWLINE"*) return 1 ;;
|
|
||||||
esac
|
|
||||||
_il_status=0
|
_il_status=0
|
||||||
grep -q -x -F -e "$1" -- "$MANIFEST" || _il_status=$?
|
grep -q -x -F -e "$1" -- "$MANIFEST" || _il_status=$?
|
||||||
case "$_il_status" in
|
case "$_il_status" in
|
||||||
@@ -148,66 +117,35 @@ read_marker() {
|
|||||||
# an endsWith(".js") test; repeating that literal here would mean a bundle
|
# an endsWith(".js") test; repeating that literal here would mean a bundle
|
||||||
# emitted under some other extension escaped the manifest AND this check at
|
# emitted under some other extension escaped the manifest AND this check at
|
||||||
# once, which is the correlated blind spot the two-source design exists to
|
# once, which is the correlated blind spot the two-source design exists to
|
||||||
# avoid. Every regular file and every symlink under dist/ is searched — that
|
# avoid. Every file under dist/ is searched, so build.js's filter is the only
|
||||||
# is the whole of what a build emits — so build.js's filter is the only place
|
# place the assumption lives and this check is what catches it being wrong.
|
||||||
# the assumption lives and this check is what catches it being wrong.
|
|
||||||
#
|
#
|
||||||
# That claim only holds if the walk is exhaustive and every name survives it
|
# That claim only holds if the walk is exhaustive, so two things are enforced
|
||||||
# intact, so four things are enforced here rather than assumed:
|
# here rather than assumed:
|
||||||
#
|
#
|
||||||
# - the walk is NUL-delimited and the paths reach the check as arguments, so
|
|
||||||
# no name can be reshaped on the way in. Read line by line, a name with a
|
|
||||||
# trailing space lost it to read's field splitting and the remnant then
|
|
||||||
# matched a manifest line, and a name containing a newline arrived as a
|
|
||||||
# listed path plus an empty one. Both left a marker-carrying, unlisted file
|
|
||||||
# unchecked while the script still reported success. Delivering such a name
|
|
||||||
# intact is only half of it; is_listed also has to keep it out of grep's
|
|
||||||
# pattern, for the same reason.
|
|
||||||
# - find's exit status is checked. A subtree it cannot descend is reported on
|
# - find's exit status is checked. A subtree it cannot descend is reported on
|
||||||
# stderr and then simply missing from the listing, so an unchecked status
|
# stderr and then simply missing from the listing, so an unchecked status
|
||||||
# turns "could not look" into "nothing was there" — the same conflation
|
# turns "could not look" into "nothing was there" — the same conflation
|
||||||
# has_marker exists to prevent. The status cannot be read off a pipeline,
|
# has_marker exists to prevent. The status cannot be read off a pipeline
|
||||||
# so the listing lands in a file that xargs then reads back.
|
# ending in sort, so the sort is a separate step.
|
||||||
# - symlinks are walked too (-type l), not skipped. A marker-carrying bundle
|
# - symlinks are walked too (-type l), not skipped. A marker-carrying bundle
|
||||||
# reachable under an unlisted path in dist/ is a stale manifest whether the
|
# reachable under an unlisted path in dist/ is a stale manifest whether the
|
||||||
# path is a link or a file, and grep reads through the link. A link that
|
# path is a link or a file, and grep reads through the link. A link that
|
||||||
# cannot be read through — dangling, or pointing at a directory — fails
|
# cannot be read through — dangling, or pointing at a directory — fails
|
||||||
# hard via has_marker's exit-2 path, which is the fail-closed answer: the
|
# hard via has_marker's exit-2 path, which is the fail-closed answer: the
|
||||||
# build emits neither, so their DEBUG state is unproven, not fine.
|
# build emits neither, so their DEBUG state is unproven, not fine.
|
||||||
# - dist/ itself must be a directory and not a symlink, which main asserts
|
|
||||||
# before anything reads through it. find does not follow a symlink named on
|
|
||||||
# its own command line, so a linked dist/ collapses this walk to one entry
|
|
||||||
# and cross-checks nothing.
|
|
||||||
#
|
|
||||||
# Types other than regular files and symlinks are left out on purpose: a build
|
|
||||||
# emits none of them, and grep on a fifo would hang rather than fail.
|
|
||||||
check_unlisted_bundles() {
|
check_unlisted_bundles() {
|
||||||
LISTING="$(mktemp "${TMPDIR:-/tmp}/verify-build-dist.XXXXXX")" ||
|
|
||||||
fail "could not create a temporary file for the dist/ listing, so the
|
|
||||||
tree was never walked. Refusing to report success."
|
|
||||||
|
|
||||||
_find_status=0
|
_find_status=0
|
||||||
find dist \( -type f -o -type l \) -print0 >"$LISTING" || _find_status=$?
|
_listing="$(find dist \( -type f -o -type l \) -print)" || _find_status=$?
|
||||||
[ "$_find_status" -eq 0 ] ||
|
[ "$_find_status" -eq 0 ] ||
|
||||||
fail "find exited $_find_status enumerating dist/, so part of the tree
|
fail "find exited $_find_status enumerating dist/, so part of the tree
|
||||||
was never walked and nothing was established about the files in it. Any
|
was never walked and nothing was established about the files in it. Any
|
||||||
unlisted bundle there went unchecked. That is a permissions or I/O fault on
|
unlisted bundle there went unchecked. That is a permissions or I/O fault on
|
||||||
the artifact, not a stale manifest. Refusing to report success."
|
the artifact, not a stale manifest. Refusing to report success."
|
||||||
|
_listing="$(printf '%s\n' "$_listing" | sort)"
|
||||||
|
|
||||||
_scan_status=0
|
while read -r _file; do
|
||||||
xargs -0 "$SELF" "$SCAN_FLAG" <"$LISTING" || _scan_status=$?
|
[ -n "$_file" ] || continue
|
||||||
[ "$_scan_status" -eq 0 ] ||
|
|
||||||
fail "the unlisted-bundle scan exited $_scan_status: either a path
|
|
||||||
under dist/ failed the check reported above, or the scan could not be run
|
|
||||||
at all. Refusing to report success."
|
|
||||||
}
|
|
||||||
|
|
||||||
# The per-path half of check_unlisted_bundles. It runs in a re-invocation of
|
|
||||||
# this script, so it uses the same is_listed and has_marker as the rest of the
|
|
||||||
# file rather than a second copy of them that could drift. Paths arrive as
|
|
||||||
# arguments and are never split, joined or trimmed.
|
|
||||||
scan_dist_paths() {
|
|
||||||
for _file in "$@"; do
|
|
||||||
if is_listed "$_file"; then
|
if is_listed "$_file"; then
|
||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
@@ -216,7 +154,9 @@ scan_dist_paths() {
|
|||||||
fail "$_file carries a debug marker but is absent from $MANIFEST,
|
fail "$_file carries a debug marker but is absent from $MANIFEST,
|
||||||
so the manifest no longer describes the emitted bundles."
|
so the manifest no longer describes the emitted bundles."
|
||||||
fi
|
fi
|
||||||
done
|
done <<EOF
|
||||||
|
$_listing
|
||||||
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
# The requested mode, read from our own environment using build.js's exact
|
# The requested mode, read from our own environment using build.js's exact
|
||||||
@@ -233,32 +173,9 @@ expected_marker() {
|
|||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
|
|
||||||
# Internal re-entry from check_unlisted_bundles' xargs. Not part of the
|
|
||||||
# command-line interface: nothing else invokes it, and it is a distinct
|
|
||||||
# entry point rather than a mode flag threaded through the checks below.
|
|
||||||
if [ "${1-}" = "$SCAN_FLAG" ]; then
|
|
||||||
shift
|
|
||||||
scan_dist_paths "$@"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
expected="$(expected_marker)"
|
expected="$(expected_marker)"
|
||||||
echo "Verifying emitted bundles (expecting $expected)..."
|
echo "Verifying emitted bundles (expecting $expected)..."
|
||||||
|
|
||||||
# Asserted here rather than left to grep. A symlinked dist/ used to fail
|
|
||||||
# only because GNU grep exits 2 on a directory, so check_unlisted_bundles'
|
|
||||||
# single entry hit has_marker's I/O path by luck; under a grep that exits 1
|
|
||||||
# instead, the whole cross-check would have collapsed into a pass.
|
|
||||||
if [ -h dist ]; then
|
|
||||||
fail "dist is a symlink, not a directory. find does not follow a
|
|
||||||
symlink named on its own command line, so the unlisted-bundle cross-check
|
|
||||||
would see one entry instead of the emitted tree and establish nothing about
|
|
||||||
it. Refusing to report success."
|
|
||||||
fi
|
|
||||||
[ -d dist ] ||
|
|
||||||
fail "dist is not a directory, so there is no emitted tree to verify.
|
|
||||||
build.js writes it; run make build first."
|
|
||||||
|
|
||||||
[ -f "$MANIFEST" ] ||
|
[ -f "$MANIFEST" ] ||
|
||||||
fail "$MANIFEST is missing. build.js writes it at the end of a
|
fail "$MANIFEST is missing. build.js writes it at the end of a
|
||||||
successful build; run make build first."
|
successful build; run make build first."
|
||||||
|
|||||||
@@ -12,20 +12,13 @@ const {
|
|||||||
currentNetwork,
|
currentNetwork,
|
||||||
} = require("../shared/state");
|
} = require("../shared/state");
|
||||||
const { refreshBalances, getProvider } = require("../shared/balances");
|
const { refreshBalances, getProvider } = require("../shared/balances");
|
||||||
const { debugFetch, log } = require("../shared/log");
|
const { debugFetch } = require("../shared/log");
|
||||||
const { verifySignedTx, verifySignature } = require("../shared/approvalVerify");
|
const { verifySignedTx, verifySignature } = require("../shared/approvalVerify");
|
||||||
const {
|
const {
|
||||||
isPhishingDomain,
|
isPhishingDomain,
|
||||||
refreshPhishingListOnSchedule,
|
updatePhishingList,
|
||||||
initPhishingList,
|
startPeriodicRefresh,
|
||||||
} = require("../shared/phishingDomains");
|
} = require("../shared/phishingDomains");
|
||||||
const {
|
|
||||||
BALANCE_REFRESH_ALARM,
|
|
||||||
PHISHING_REFRESH_ALARM,
|
|
||||||
BALANCE_REFRESH_PERIOD_MINUTES,
|
|
||||||
ensureRecurringAlarms,
|
|
||||||
registerAlarmHandlers,
|
|
||||||
} = require("../shared/alarms");
|
|
||||||
|
|
||||||
const storageApi =
|
const storageApi =
|
||||||
typeof browser !== "undefined"
|
typeof browser !== "undefined"
|
||||||
@@ -598,22 +591,12 @@ async function broadcastAccountsChanged() {
|
|||||||
// Background balance refresh: every 60 seconds when the popup isn't open.
|
// Background balance refresh: every 60 seconds when the popup isn't open.
|
||||||
// When the popup IS open, its 10-second interval keeps lastBalanceRefresh
|
// When the popup IS open, its 10-second interval keeps lastBalanceRefresh
|
||||||
// fresh, so this naturally skips.
|
// fresh, so this naturally skips.
|
||||||
//
|
const BACKGROUND_REFRESH_INTERVAL = 60000;
|
||||||
// The alarm period alone sets the cadence; this guard only suppresses a
|
|
||||||
// refresh something else has just done, so it must stay strictly shorter than
|
|
||||||
// the period. Timed to the period it would veto every tick it gates —
|
|
||||||
// lastBalanceRefresh is stamped after the refresh runs, so a tick one period
|
|
||||||
// after the last one always lands inside a guard of equal length and the real
|
|
||||||
// cadence becomes two periods. Half the period keeps it comfortably above the
|
|
||||||
// popup's 10-second refresh, so an open popup still suppresses the background
|
|
||||||
// job, and comfortably below the alarm period, so the schedule always wins.
|
|
||||||
const BALANCE_REFRESH_PERIOD_MS = BALANCE_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
|
||||||
const RECENT_BALANCE_REFRESH_MS = Math.floor(BALANCE_REFRESH_PERIOD_MS / 2);
|
|
||||||
|
|
||||||
async function backgroundRefresh() {
|
async function backgroundRefresh() {
|
||||||
await loadState();
|
await loadState();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - (state.lastBalanceRefresh || 0) < RECENT_BALANCE_REFRESH_MS)
|
if (now - (state.lastBalanceRefresh || 0) < BACKGROUND_REFRESH_INTERVAL)
|
||||||
return;
|
return;
|
||||||
if (state.wallets.length === 0) return;
|
if (state.wallets.length === 0) return;
|
||||||
await refreshBalances(
|
await refreshBalances(
|
||||||
@@ -626,58 +609,12 @@ async function backgroundRefresh() {
|
|||||||
await saveState();
|
await saveState();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both recurring jobs run off alarms, not timers. On Chrome MV3 this file is
|
setInterval(backgroundRefresh, BACKGROUND_REFRESH_INTERVAL);
|
||||||
// a service worker that the browser terminates after about 30 seconds idle,
|
|
||||||
// so a setInterval would only ever survive until the first idle period and
|
|
||||||
// module-level state does not outlive it. Alarms are held by the browser and
|
|
||||||
// wake the worker to deliver them.
|
|
||||||
registerAlarmHandlers({
|
|
||||||
[BALANCE_REFRESH_ALARM]: backgroundRefresh,
|
|
||||||
// The scheduled refresh, which restores persisted state on a freshly
|
|
||||||
// revived worker and then fetches unconditionally. The freshness guards
|
|
||||||
// belong to the startup path; applying them here would make the tick skip
|
|
||||||
// itself.
|
|
||||||
[PHISHING_REFRESH_ALARM]: refreshPhishingListOnSchedule,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Everything the background context needs re-established on start. This runs
|
// Fetch the phishing domain blocklist delta on startup and refresh every 24h.
|
||||||
// on a fresh install, on browser startup, and on every revival of a
|
// The vendored blocklist is bundled at build time; this fetches only new entries.
|
||||||
// terminated worker, so it must be idempotent: ensureRecurringAlarms() only
|
updatePhishingList();
|
||||||
// creates alarms that are missing or carrying a stale period, and
|
startPeriodicRefresh();
|
||||||
// initPhishingList() fetches only when the persisted timestamps say the list
|
|
||||||
// is stale.
|
|
||||||
//
|
|
||||||
// On a fresh install the top-level call and the onInstalled listener both run,
|
|
||||||
// close enough together that both could see an alarm missing and create it.
|
|
||||||
// Sharing one in-flight run makes the "create only when missing" check
|
|
||||||
// race-free; the memo is dropped once it settles so a later onStartup runs
|
|
||||||
// again.
|
|
||||||
let backgroundJobsRun = null;
|
|
||||||
|
|
||||||
function startBackgroundJobs() {
|
|
||||||
if (backgroundJobsRun) return backgroundJobsRun;
|
|
||||||
backgroundJobsRun = Promise.all([
|
|
||||||
ensureRecurringAlarms(),
|
|
||||||
initPhishingList(),
|
|
||||||
])
|
|
||||||
.catch((err) => {
|
|
||||||
// An alarm that failed to schedule means a recurring job silently
|
|
||||||
// never runs again; it must not be an unhandled rejection.
|
|
||||||
log.errorf("background job startup failed:", err);
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
backgroundJobsRun = null;
|
|
||||||
});
|
|
||||||
return backgroundJobsRun;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (runtime.onInstalled) {
|
|
||||||
runtime.onInstalled.addListener(startBackgroundJobs);
|
|
||||||
}
|
|
||||||
if (runtime.onStartup) {
|
|
||||||
runtime.onStartup.addListener(startBackgroundJobs);
|
|
||||||
}
|
|
||||||
startBackgroundJobs();
|
|
||||||
|
|
||||||
// When approval window is closed without a response, treat as rejection
|
// When approval window is closed without a response, treat as rejection
|
||||||
if (windowsApi && windowsApi.onRemoved) {
|
if (windowsApi && windowsApi.onRemoved) {
|
||||||
|
|||||||
@@ -136,9 +136,7 @@
|
|||||||
<div id="add-wallet-section-xprv" class="hidden">
|
<div id="add-wallet-section-xprv" class="hidden">
|
||||||
<p class="mb-2">
|
<p class="mb-2">
|
||||||
Paste your extended private key (xprv) below. This will
|
Paste your extended private key (xprv) below. This will
|
||||||
import the HD wallet and scan for used addresses. It
|
import the HD wallet and scan for used addresses.
|
||||||
must be the master key for the wallet; an account-level
|
|
||||||
or child key is not supported.
|
|
||||||
</p>
|
</p>
|
||||||
<div class="mb-2">
|
<div class="mb-2">
|
||||||
<input
|
<input
|
||||||
@@ -584,18 +582,10 @@
|
|||||||
<div id="confirm-balance" class="text-xs"></div>
|
<div id="confirm-balance" class="text-xs"></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="confirm-fee" class="mb-3" style="visibility: hidden">
|
<div id="confirm-fee" class="mb-3" style="visibility: hidden">
|
||||||
<div class="text-xs text-muted mb-1">Network fee</div>
|
<div class="text-xs text-muted mb-1">
|
||||||
<div id="confirm-fee-amount" class="text-xs"></div>
|
Estimated network fee
|
||||||
<!-- Holds its one line of space from the first paint, so
|
|
||||||
the reserve appearing when the estimate lands moves
|
|
||||||
nothing. The placeholder is never seen. -->
|
|
||||||
<div
|
|
||||||
id="confirm-fee-reserve"
|
|
||||||
class="text-xs text-muted"
|
|
||||||
style="visibility: hidden"
|
|
||||||
>
|
|
||||||
reserve pending
|
|
||||||
</div>
|
</div>
|
||||||
|
<div id="confirm-fee-amount" class="text-xs"></div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
id="confirm-warnings"
|
id="confirm-warnings"
|
||||||
@@ -657,31 +647,6 @@
|
|||||||
class="mb-2 border border-border border-dashed p-2"
|
class="mb-2 border border-border border-dashed p-2"
|
||||||
style="visibility: hidden; min-height: 1.25rem"
|
style="visibility: hidden; min-height: 1.25rem"
|
||||||
></div>
|
></div>
|
||||||
<div
|
|
||||||
id="confirm-amount-fee-error"
|
|
||||||
class="mb-2 border border-border border-dashed p-2 text-xs"
|
|
||||||
style="visibility: hidden"
|
|
||||||
>
|
|
||||||
Your balance does not cover this amount plus the network
|
|
||||||
fee. Please go back and send a smaller amount.
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
id="confirm-gas-error"
|
|
||||||
class="mb-2 border border-border border-dashed p-2 text-xs"
|
|
||||||
style="visibility: hidden"
|
|
||||||
>
|
|
||||||
You do not have enough ETH to pay the network fee for this
|
|
||||||
transfer. Please add ETH to this address and try again.
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
id="confirm-fee-unknown-error"
|
|
||||||
class="mb-2 border border-border border-dashed p-2 text-xs"
|
|
||||||
style="visibility: hidden"
|
|
||||||
>
|
|
||||||
The network fee could not be estimated, so this transaction
|
|
||||||
cannot be checked against your balance. Please go back and
|
|
||||||
try again.
|
|
||||||
</div>
|
|
||||||
<div class="mb-2">
|
<div class="mb-2">
|
||||||
<label class="block mb-1 text-xs">Password</label>
|
<label class="block mb-1 text-xs">Password</label>
|
||||||
<input
|
<input
|
||||||
@@ -904,12 +869,6 @@
|
|||||||
/>
|
/>
|
||||||
Show tracked tokens with zero balance
|
Show tracked tokens with zero balance
|
||||||
</label>
|
</label>
|
||||||
<label
|
|
||||||
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
|
||||||
>
|
|
||||||
<input type="checkbox" id="settings-utc-timestamps" />
|
|
||||||
UTC Timestamps
|
|
||||||
</label>
|
|
||||||
<div class="text-xs flex items-center gap-1">
|
<div class="text-xs flex items-center gap-1">
|
||||||
<label for="settings-theme">Theme:</label>
|
<label for="settings-theme">Theme:</label>
|
||||||
<select
|
<select
|
||||||
@@ -989,15 +948,6 @@
|
|||||||
transfers and prevent interaction with suspicious
|
transfers and prevent interaction with suspicious
|
||||||
tokens.
|
tokens.
|
||||||
</p>
|
</p>
|
||||||
<label
|
|
||||||
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
id="settings-hide-spoofed-symbols"
|
|
||||||
/>
|
|
||||||
Hide fake tokens impersonating a known symbol
|
|
||||||
</label>
|
|
||||||
<label
|
<label
|
||||||
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
||||||
>
|
>
|
||||||
@@ -1029,6 +979,12 @@
|
|||||||
/>
|
/>
|
||||||
<span class="text-xs text-muted">gwei</span>
|
<span class="text-xs text-muted">gwei</span>
|
||||||
</div>
|
</div>
|
||||||
|
<label
|
||||||
|
class="text-xs flex items-center gap-1 cursor-pointer mb-1"
|
||||||
|
>
|
||||||
|
<input type="checkbox" id="settings-utc-timestamps" />
|
||||||
|
UTC Timestamps
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="bg-well p-3 mx-1 mb-3">
|
<div class="bg-well p-3 mx-1 mb-3">
|
||||||
@@ -1142,52 +1098,6 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ============ SHOW RECOVERY PHRASE ============ -->
|
|
||||||
<div id="view-show-phrase" class="view hidden">
|
|
||||||
<button
|
|
||||||
id="btn-show-phrase-back"
|
|
||||||
class="border border-border px-2 py-1 hover:bg-fg hover:text-bg cursor-pointer mb-2"
|
|
||||||
>
|
|
||||||
< Back
|
|
||||||
</button>
|
|
||||||
<h2 class="font-bold mb-1">Recovery Phrase</h2>
|
|
||||||
<p class="text-xs mb-3" id="show-phrase-wallet-name"></p>
|
|
||||||
<div
|
|
||||||
class="text-xs mb-3 border border-border border-dashed p-2"
|
|
||||||
>
|
|
||||||
Anyone who has these words can take every coin and token in
|
|
||||||
this wallet, from any device, without your password. Never
|
|
||||||
type them into a website and never show them to anyone.
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
id="show-phrase-flash"
|
|
||||||
class="text-xs text-red-500 mb-2 min-h-[1.25rem]"
|
|
||||||
style="visibility: hidden"
|
|
||||||
></div>
|
|
||||||
<div id="show-phrase-password-section" class="mb-2">
|
|
||||||
<label class="block mb-1">Password</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="show-phrase-password"
|
|
||||||
class="border border-border p-1 w-full font-mono text-sm bg-bg text-fg"
|
|
||||||
placeholder="Enter your password to continue"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
id="btn-show-phrase-reveal"
|
|
||||||
class="border border-border px-2 py-1 hover:bg-fg hover:text-bg cursor-pointer mt-2"
|
|
||||||
>
|
|
||||||
Reveal
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div id="show-phrase-result" class="hidden">
|
|
||||||
<div
|
|
||||||
id="show-phrase-value"
|
|
||||||
class="bg-danger-well rounded p-2 font-mono text-xs break-all cursor-pointer mb-1"
|
|
||||||
title="Click to copy"
|
|
||||||
></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ============ SETTINGS: ADD TOKEN ============ -->
|
<!-- ============ SETTINGS: ADD TOKEN ============ -->
|
||||||
<div id="view-settings-addtoken" class="view hidden">
|
<div id="view-settings-addtoken" class="view hidden">
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -15,10 +15,6 @@ const {
|
|||||||
clearViewStack,
|
clearViewStack,
|
||||||
} = require("./views/helpers");
|
} = require("./views/helpers");
|
||||||
const { applyTheme } = require("./theme");
|
const { applyTheme } = require("./theme");
|
||||||
// Views that can be fully re-rendered from persisted state. All others fall
|
|
||||||
// back to the nearest restorable parent; see the module for why the
|
|
||||||
// secret-bearing views are absent.
|
|
||||||
const { RESTORABLE_VIEWS } = require("./restorableViews");
|
|
||||||
|
|
||||||
const home = require("./views/home");
|
const home = require("./views/home");
|
||||||
const welcome = require("./views/welcome");
|
const welcome = require("./views/welcome");
|
||||||
@@ -103,6 +99,22 @@ const ctx = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Views that can be fully re-rendered from persisted state.
|
||||||
|
// All others fall back to the nearest restorable parent.
|
||||||
|
const RESTORABLE_VIEWS = new Set([
|
||||||
|
"main",
|
||||||
|
"address",
|
||||||
|
"address-token",
|
||||||
|
"receive",
|
||||||
|
"settings",
|
||||||
|
"settings-addtoken",
|
||||||
|
"confirm-tx",
|
||||||
|
"transaction",
|
||||||
|
"wait-tx",
|
||||||
|
"success-tx",
|
||||||
|
"error-tx",
|
||||||
|
]);
|
||||||
|
|
||||||
function needsAddress(view) {
|
function needsAddress(view) {
|
||||||
return (
|
return (
|
||||||
view === "address" ||
|
view === "address" ||
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
// Views the popup may reopen onto.
|
|
||||||
//
|
|
||||||
// The popup persists the current view so that reopening the toolbar popup
|
|
||||||
// lands the user back where they were. Only views that can be fully
|
|
||||||
// re-rendered from persisted state belong here; every other view falls back
|
|
||||||
// to the nearest restorable parent (src/popup/index.js restoreView()).
|
|
||||||
//
|
|
||||||
// A view that displays a secret must NEVER be listed. Restoring onto one
|
|
||||||
// would put a private key or a recovery phrase on screen with no password
|
|
||||||
// prompt in front of it, on a popup the user may have reopened by accident.
|
|
||||||
// That is why "export-privkey" and "show-phrase" are absent.
|
|
||||||
//
|
|
||||||
// Kept in its own module, with no dependencies, so tests can assert the
|
|
||||||
// exclusion directly rather than trusting a reading of the popup entry
|
|
||||||
// point, which cannot be required outside a browser.
|
|
||||||
const RESTORABLE_VIEWS = new Set([
|
|
||||||
"main",
|
|
||||||
"address",
|
|
||||||
"address-token",
|
|
||||||
"receive",
|
|
||||||
"settings",
|
|
||||||
"settings-addtoken",
|
|
||||||
"confirm-tx",
|
|
||||||
"transaction",
|
|
||||||
"wait-tx",
|
|
||||||
"success-tx",
|
|
||||||
"error-tx",
|
|
||||||
]);
|
|
||||||
|
|
||||||
module.exports = { RESTORABLE_VIEWS };
|
|
||||||
@@ -6,7 +6,6 @@ const {
|
|||||||
addressFromPrivateKey,
|
addressFromPrivateKey,
|
||||||
hdWalletFromXprv,
|
hdWalletFromXprv,
|
||||||
isValidXprv,
|
isValidXprv,
|
||||||
isMasterExtendedKey,
|
|
||||||
} = require("../../shared/wallet");
|
} = require("../../shared/wallet");
|
||||||
const { encryptWithPassword } = require("../../shared/vault");
|
const { encryptWithPassword } = require("../../shared/vault");
|
||||||
const { state, saveState } = require("../../shared/state");
|
const { state, saveState } = require("../../shared/state");
|
||||||
@@ -214,25 +213,14 @@ async function importXprvKey(ctx) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isValidXprv(xprv)) {
|
if (!isValidXprv(xprv)) {
|
||||||
showFlash(
|
showFlash("Invalid extended private key.");
|
||||||
"That extended private key is not valid. Please check it and try again.",
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!isMasterExtendedKey(xprv)) {
|
|
||||||
showFlash(
|
|
||||||
"That is an account-level or child key, which cannot be imported. " +
|
|
||||||
"Please paste the master extended private key for the wallet.",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = hdWalletFromXprv(xprv);
|
result = hdWalletFromXprv(xprv);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showFlash(
|
showFlash("Invalid extended private key.");
|
||||||
"That extended private key is not valid. Please check it and try again.",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { xpub, firstAddress } = result;
|
const { xpub, firstAddress } = result;
|
||||||
|
|||||||
@@ -148,7 +148,6 @@ async function loadTransactions(address) {
|
|||||||
state.blockscoutUrl,
|
state.blockscoutUrl,
|
||||||
);
|
);
|
||||||
const result = filterTransactions(rawTxs, {
|
const result = filterTransactions(rawTxs, {
|
||||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -222,7 +222,6 @@ async function loadTransactions(address, tokenId) {
|
|||||||
state.blockscoutUrl,
|
state.blockscoutUrl,
|
||||||
);
|
);
|
||||||
const result = filterTransactions(rawTxs, {
|
const result = filterTransactions(rawTxs, {
|
||||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -32,24 +32,11 @@ const {
|
|||||||
getFullWarnings,
|
getFullWarnings,
|
||||||
} = require("../../shared/addressWarnings");
|
} = require("../../shared/addressWarnings");
|
||||||
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
||||||
const {
|
|
||||||
CODES,
|
|
||||||
FEE_PENDING,
|
|
||||||
FEE_KNOWN,
|
|
||||||
FEE_UNAVAILABLE,
|
|
||||||
feeReserveWei,
|
|
||||||
feeEstimateWei,
|
|
||||||
validateTransfer,
|
|
||||||
} = require("../../shared/txValidation");
|
|
||||||
const { log } = require("../../shared/log");
|
const { log } = require("../../shared/log");
|
||||||
const makeBlockie = require("ethereum-blockies-base64");
|
const makeBlockie = require("ethereum-blockies-base64");
|
||||||
const txStatus = require("./txStatus");
|
const txStatus = require("./txStatus");
|
||||||
|
|
||||||
let pendingTx = null;
|
let pendingTx = null;
|
||||||
// Network fee for the transaction currently on screen. Reset by show() and
|
|
||||||
// filled in by estimateGas() when the estimate resolves or fails.
|
|
||||||
let feeStatus = FEE_PENDING;
|
|
||||||
let feeWei = null;
|
|
||||||
|
|
||||||
function restore() {
|
function restore() {
|
||||||
const d = state.viewData;
|
const d = state.viewData;
|
||||||
@@ -80,8 +67,6 @@ function valueWithUsd(text, usdAmount) {
|
|||||||
|
|
||||||
function show(txInfo) {
|
function show(txInfo) {
|
||||||
pendingTx = txInfo;
|
pendingTx = txInfo;
|
||||||
feeStatus = FEE_PENDING;
|
|
||||||
feeWei = null;
|
|
||||||
|
|
||||||
const isErc20 = txInfo.token !== "ETH";
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
||||||
@@ -168,14 +153,50 @@ function show(txInfo) {
|
|||||||
warningsEl.style.visibility = "hidden";
|
warningsEl.style.visibility = "hidden";
|
||||||
}
|
}
|
||||||
|
|
||||||
// The two fee messages are mutually exclusive per transaction type, and
|
// Check for errors
|
||||||
// the type is known here, before the first paint. Drop the one that can
|
const errors = [];
|
||||||
// never apply and reserve the space of the one that can, so the async
|
if (isErc20) {
|
||||||
// estimate landing later never moves anything.
|
const tokenBal = parseFloat(txInfo.tokenBalance || "0");
|
||||||
$("confirm-amount-fee-error").classList.toggle("hidden", isErc20);
|
if (parseFloat(txInfo.amount) > tokenBal) {
|
||||||
$("confirm-gas-error").classList.toggle("hidden", !isErc20);
|
errors.push(
|
||||||
|
"Insufficient " +
|
||||||
|
symbol +
|
||||||
|
" balance. You have " +
|
||||||
|
txInfo.tokenBalance +
|
||||||
|
" " +
|
||||||
|
symbol +
|
||||||
|
" but are trying to send " +
|
||||||
|
txInfo.amount +
|
||||||
|
" " +
|
||||||
|
symbol +
|
||||||
|
".",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (parseFloat(txInfo.amount) > parseFloat(txInfo.balance)) {
|
||||||
|
errors.push(
|
||||||
|
"Insufficient balance. You have " +
|
||||||
|
txInfo.balance +
|
||||||
|
" ETH but are trying to send " +
|
||||||
|
txInfo.amount +
|
||||||
|
" ETH.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
renderValidation(txInfo);
|
const errorsEl = $("confirm-errors");
|
||||||
|
const sendBtn = $("btn-confirm-send");
|
||||||
|
if (errors.length > 0) {
|
||||||
|
errorsEl.innerHTML = errors
|
||||||
|
.map((e) => `<div class="text-xs">${e}</div>`)
|
||||||
|
.join("");
|
||||||
|
errorsEl.style.visibility = "visible";
|
||||||
|
sendBtn.disabled = true;
|
||||||
|
sendBtn.classList.add("text-muted");
|
||||||
|
} else {
|
||||||
|
errorsEl.innerHTML = "";
|
||||||
|
errorsEl.style.visibility = "hidden";
|
||||||
|
sendBtn.disabled = false;
|
||||||
|
sendBtn.classList.remove("text-muted");
|
||||||
|
}
|
||||||
|
|
||||||
// Reset password field and error
|
// Reset password field and error
|
||||||
$("confirm-tx-password").value = "";
|
$("confirm-tx-password").value = "";
|
||||||
@@ -184,7 +205,6 @@ function show(txInfo) {
|
|||||||
// Gas estimate — show placeholder then fetch async
|
// Gas estimate — show placeholder then fetch async
|
||||||
$("confirm-fee").style.visibility = "visible";
|
$("confirm-fee").style.visibility = "visible";
|
||||||
$("confirm-fee-amount").textContent = "Estimating...";
|
$("confirm-fee-amount").textContent = "Estimating...";
|
||||||
setVisible("confirm-fee-reserve", false);
|
|
||||||
state.viewData = { pendingTx: txInfo };
|
state.viewData = { pendingTx: txInfo };
|
||||||
showView("confirm-tx");
|
showView("confirm-tx");
|
||||||
attachCopyHandlers("view-confirm-tx");
|
attachCopyHandlers("view-confirm-tx");
|
||||||
@@ -204,101 +224,11 @@ function show(txInfo) {
|
|||||||
checkRecipientHistory(txInfo);
|
checkRecipientHistory(txInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render the balance check for the transaction on screen. Called once during
|
|
||||||
// show() and again when the fee estimate resolves or fails. Every element it
|
|
||||||
// touches already occupies its space, so re-running it never moves anything.
|
|
||||||
function renderValidation(txInfo) {
|
|
||||||
const isErc20 = txInfo.token !== "ETH";
|
|
||||||
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
|
||||||
|
|
||||||
const { canSend, codes } = validateTransfer({
|
|
||||||
isErc20,
|
|
||||||
amount: txInfo.amount,
|
|
||||||
ethBalance: txInfo.balance,
|
|
||||||
tokenBalance: txInfo.tokenBalance,
|
|
||||||
feeStatus,
|
|
||||||
feeWei,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Messages carrying the user's own numbers are built here; the fixed
|
|
||||||
// sentences live in the reserved elements in index.html.
|
|
||||||
const messages = [];
|
|
||||||
if (codes.includes(CODES.AMOUNT_INVALID)) {
|
|
||||||
messages.push("Please enter a valid amount to send.");
|
|
||||||
}
|
|
||||||
if (codes.includes(CODES.INSUFFICIENT_TOKEN)) {
|
|
||||||
messages.push(
|
|
||||||
"Insufficient " +
|
|
||||||
symbol +
|
|
||||||
" balance. You have " +
|
|
||||||
txInfo.tokenBalance +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
" but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
".",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (codes.includes(CODES.INSUFFICIENT_ETH)) {
|
|
||||||
messages.push(
|
|
||||||
"Insufficient balance. You have " +
|
|
||||||
txInfo.balance +
|
|
||||||
" ETH but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" ETH.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorsEl = $("confirm-errors");
|
|
||||||
if (messages.length > 0) {
|
|
||||||
errorsEl.innerHTML = messages
|
|
||||||
.map((m) => `<div class="text-xs">${escapeHtml(m)}</div>`)
|
|
||||||
.join("");
|
|
||||||
errorsEl.style.visibility = "visible";
|
|
||||||
} else {
|
|
||||||
errorsEl.innerHTML = "";
|
|
||||||
errorsEl.style.visibility = "hidden";
|
|
||||||
}
|
|
||||||
|
|
||||||
setVisible(
|
|
||||||
"confirm-amount-fee-error",
|
|
||||||
codes.includes(CODES.INSUFFICIENT_ETH_WITH_FEE),
|
|
||||||
);
|
|
||||||
setVisible(
|
|
||||||
"confirm-gas-error",
|
|
||||||
codes.includes(CODES.INSUFFICIENT_ETH_FOR_FEE),
|
|
||||||
);
|
|
||||||
setVisible(
|
|
||||||
"confirm-fee-unknown-error",
|
|
||||||
codes.includes(CODES.FEE_UNAVAILABLE),
|
|
||||||
);
|
|
||||||
|
|
||||||
// While the estimate is in flight there is no error to show — the fee
|
|
||||||
// line already reads "Estimating..." — but sending stays blocked so a
|
|
||||||
// transaction the fee would break cannot be signed in the meantime.
|
|
||||||
const sendBtn = $("btn-confirm-send");
|
|
||||||
sendBtn.disabled = !canSend;
|
|
||||||
sendBtn.classList.toggle("text-muted", !canSend);
|
|
||||||
}
|
|
||||||
|
|
||||||
function setVisible(id, visible) {
|
|
||||||
$(id).style.visibility = visible ? "visible" : "hidden";
|
|
||||||
}
|
|
||||||
|
|
||||||
// A fee in wei as an ETH string, truncated to 6 decimal places.
|
|
||||||
function formatFeeEth(wei) {
|
|
||||||
const parts = formatEther(wei).split(".");
|
|
||||||
const dec =
|
|
||||||
parts.length > 1 ? parts[1].slice(0, 6).replace(/0+$/, "") || "0" : "0";
|
|
||||||
return parts[0] + "." + dec + " ETH";
|
|
||||||
}
|
|
||||||
|
|
||||||
async function estimateGas(txInfo) {
|
async function estimateGas(txInfo) {
|
||||||
try {
|
try {
|
||||||
const provider = getProvider(state.rpcUrl);
|
const provider = getProvider(state.rpcUrl);
|
||||||
const feeData = await provider.getFeeData();
|
const feeData = await provider.getFeeData();
|
||||||
|
const gasPrice = feeData.gasPrice;
|
||||||
let gasLimit;
|
let gasLimit;
|
||||||
|
|
||||||
if (txInfo.token === "ETH") {
|
if (txInfo.token === "ETH") {
|
||||||
@@ -316,55 +246,21 @@ async function estimateGas(txInfo) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// What the node will require to be reserved, which is what the gate
|
const gasCostWei = gasLimit * gasPrice;
|
||||||
// must be: the send pins no fee fields, so it is broadcast as a
|
const gasCostEth = formatEther(gasCostWei);
|
||||||
// type-2 transaction priced at maxFeePerGas.
|
// Format to 6 significant decimal places
|
||||||
const gasCostWei = feeReserveWei(gasLimit, feeData);
|
const parts = gasCostEth.split(".");
|
||||||
if (gasCostWei === null) {
|
const dec =
|
||||||
throw new Error("no usable gas price from the provider");
|
parts.length > 1
|
||||||
}
|
? parts[1].slice(0, 6).replace(/0+$/, "") || "0"
|
||||||
// What the transaction is expected to cost, which is a different and
|
: "0";
|
||||||
// usually much smaller number. Both are shown: quoting only the
|
const feeStr = parts[0] + "." + dec + " ETH";
|
||||||
// reserve overstates the typical cost by roughly double on mainnet,
|
|
||||||
// and quoting only the estimate contradicts the balance check.
|
|
||||||
const estimateWei = feeEstimateWei(gasLimit, feeData);
|
|
||||||
// The user may have left this transaction while the estimate was in
|
|
||||||
// flight; a stale fee must not reach the screen or the balance check.
|
|
||||||
if (pendingTx !== txInfo) return;
|
|
||||||
|
|
||||||
const ethPrice = getPrice("ETH");
|
const ethPrice = getPrice("ETH");
|
||||||
const usd = (wei) =>
|
const feeUsd = ethPrice ? parseFloat(gasCostEth) * ethPrice : null;
|
||||||
ethPrice ? parseFloat(formatEther(wei)) * ethPrice : null;
|
$("confirm-fee-amount").textContent = valueWithUsd(feeStr, feeUsd);
|
||||||
|
|
||||||
if (estimateWei !== null && estimateWei < gasCostWei) {
|
|
||||||
$("confirm-fee-amount").textContent = valueWithUsd(
|
|
||||||
"~" + formatFeeEth(estimateWei),
|
|
||||||
usd(estimateWei),
|
|
||||||
);
|
|
||||||
$("confirm-fee-reserve").textContent =
|
|
||||||
"up to " + formatFeeEth(gasCostWei) + " reserved";
|
|
||||||
setVisible("confirm-fee-reserve", true);
|
|
||||||
} else {
|
|
||||||
// No spread to report: either there is no estimate, or the node
|
|
||||||
// quotes a gas price at or above maxFeePerGas, so the expected
|
|
||||||
// cost is not below the reserve. Show the reserve alone.
|
|
||||||
$("confirm-fee-amount").textContent = valueWithUsd(
|
|
||||||
formatFeeEth(gasCostWei),
|
|
||||||
usd(gasCostWei),
|
|
||||||
);
|
|
||||||
setVisible("confirm-fee-reserve", false);
|
|
||||||
}
|
|
||||||
feeStatus = FEE_KNOWN;
|
|
||||||
feeWei = gasCostWei;
|
|
||||||
renderValidation(txInfo);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.errorf("gas estimation failed:", e.message);
|
log.errorf("gas estimation failed:", e.message);
|
||||||
if (pendingTx !== txInfo) return;
|
|
||||||
$("confirm-fee-amount").textContent = "Unable to estimate";
|
$("confirm-fee-amount").textContent = "Unable to estimate";
|
||||||
setVisible("confirm-fee-reserve", false);
|
|
||||||
feeStatus = FEE_UNAVAILABLE;
|
|
||||||
feeWei = null;
|
|
||||||
renderValidation(txInfo);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,20 +31,8 @@ const VIEWS = [
|
|||||||
"approve-tx",
|
"approve-tx",
|
||||||
"approve-sign",
|
"approve-sign",
|
||||||
"export-privkey",
|
"export-privkey",
|
||||||
"show-phrase",
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// Cleanup callbacks for views that hold a secret in the DOM. The view
|
|
||||||
// registers one for itself and showView() runs it whenever that view is
|
|
||||||
// navigated away from, so the secret is wiped no matter which control
|
|
||||||
// caused the navigation — "Back", the settings gear, or a jump from
|
|
||||||
// anywhere else. A per-button clear would only cover the one path.
|
|
||||||
const viewLeaveHandlers = new Map();
|
|
||||||
|
|
||||||
function onViewLeave(name, fn) {
|
|
||||||
viewLeaveHandlers.set(name, fn);
|
|
||||||
}
|
|
||||||
|
|
||||||
function $(id) {
|
function $(id) {
|
||||||
return document.getElementById(id);
|
return document.getElementById(id);
|
||||||
}
|
}
|
||||||
@@ -62,11 +50,6 @@ function hideError(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function showView(name) {
|
function showView(name) {
|
||||||
const leaving = state.currentView;
|
|
||||||
if (leaving && leaving !== name) {
|
|
||||||
const onLeave = viewLeaveHandlers.get(leaving);
|
|
||||||
if (onLeave) onLeave();
|
|
||||||
}
|
|
||||||
for (const v of VIEWS) {
|
for (const v of VIEWS) {
|
||||||
const el = document.getElementById(`view-${v}`);
|
const el = document.getElementById(`view-${v}`);
|
||||||
if (el) {
|
if (el) {
|
||||||
@@ -448,12 +431,10 @@ function flashCopyFeedback(el) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
VIEWS,
|
|
||||||
$,
|
$,
|
||||||
showError,
|
showError,
|
||||||
hideError,
|
hideError,
|
||||||
showView,
|
showView,
|
||||||
onViewLeave,
|
|
||||||
updateDebugBanner,
|
updateDebugBanner,
|
||||||
setRenderMain,
|
setRenderMain,
|
||||||
pushCurrentView,
|
pushCurrentView,
|
||||||
|
|||||||
@@ -163,7 +163,6 @@ async function loadHomeTxs(ctx) {
|
|||||||
if (allAddresses.length === 0) return;
|
if (allAddresses.length === 0) return;
|
||||||
|
|
||||||
const filters = {
|
const filters = {
|
||||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ const { NETWORKS, SUPPORTED_CHAIN_IDS } = require("../../shared/networks");
|
|||||||
const { onChainSwitch } = require("../../shared/chainSwitch");
|
const { onChainSwitch } = require("../../shared/chainSwitch");
|
||||||
const { log, debugFetch, setRuntimeDebug } = require("../../shared/log");
|
const { log, debugFetch, setRuntimeDebug } = require("../../shared/log");
|
||||||
const deleteWallet = require("./deleteWallet");
|
const deleteWallet = require("./deleteWallet");
|
||||||
const showPhrase = require("./showPhrase");
|
|
||||||
const { walletHasRecoveryPhrase } = require("../../shared/wallet");
|
|
||||||
const {
|
const {
|
||||||
BUILD_VERSION,
|
BUILD_VERSION,
|
||||||
BUILD_LICENSE,
|
BUILD_LICENSE,
|
||||||
@@ -101,14 +99,7 @@ function renderWalletListSettings() {
|
|||||||
const name = escapeHtml(wallet.name || "Wallet " + (idx + 1));
|
const name = escapeHtml(wallet.name || "Wallet " + (idx + 1));
|
||||||
html += `<div class="flex justify-between items-center text-xs py-1 border-b border-border-light">`;
|
html += `<div class="flex justify-between items-center text-xs py-1 border-b border-border-light">`;
|
||||||
html += `<span class="settings-wallet-name cursor-pointer underline decoration-dashed" data-idx="${idx}">${name}</span>`;
|
html += `<span class="settings-wallet-name cursor-pointer underline decoration-dashed" data-idx="${idx}">${name}</span>`;
|
||||||
html += `<span class="flex items-center gap-1 flex-shrink-0">`;
|
|
||||||
// Key and xprv wallets have no recovery phrase, so they are never
|
|
||||||
// offered the action at all.
|
|
||||||
if (walletHasRecoveryPhrase(wallet)) {
|
|
||||||
html += `<button class="btn-show-phrase border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}" title="Show recovery phrase">[recovery phrase]</button>`;
|
|
||||||
}
|
|
||||||
html += `<button class="btn-delete-wallet border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}">[x]</button>`;
|
html += `<button class="btn-delete-wallet border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}">[x]</button>`;
|
||||||
html += `</span>`;
|
|
||||||
html += `</div>`;
|
html += `</div>`;
|
||||||
});
|
});
|
||||||
container.innerHTML = html;
|
container.innerHTML = html;
|
||||||
@@ -120,15 +111,6 @@ function renderWalletListSettings() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
container.querySelectorAll(".btn-show-phrase").forEach((btn) => {
|
|
||||||
btn.addEventListener("click", () => {
|
|
||||||
const idx = parseInt(btn.dataset.idx, 10);
|
|
||||||
// No pushCurrentView() here: showPhrase.show() refuses
|
|
||||||
// non-HD wallets and pushes only when it navigates.
|
|
||||||
showPhrase.show(idx);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Inline rename on click
|
// Inline rename on click
|
||||||
container.querySelectorAll(".settings-wallet-name").forEach((span) => {
|
container.querySelectorAll(".settings-wallet-name").forEach((span) => {
|
||||||
span.addEventListener("click", () => {
|
span.addEventListener("click", () => {
|
||||||
@@ -209,7 +191,6 @@ function renderSiteLists() {
|
|||||||
|
|
||||||
function init(ctx) {
|
function init(ctx) {
|
||||||
deleteWallet.init(ctx);
|
deleteWallet.init(ctx);
|
||||||
showPhrase.init();
|
|
||||||
|
|
||||||
$("btn-save-rpc").addEventListener("click", async () => {
|
$("btn-save-rpc").addEventListener("click", async () => {
|
||||||
const url = $("settings-rpc").value.trim();
|
const url = $("settings-rpc").value.trim();
|
||||||
@@ -303,12 +284,6 @@ function init(ctx) {
|
|||||||
applyTheme(state.theme);
|
applyTheme(state.theme);
|
||||||
});
|
});
|
||||||
|
|
||||||
$("settings-hide-spoofed-symbols").checked = state.hideSpoofedSymbols;
|
|
||||||
$("settings-hide-spoofed-symbols").addEventListener("change", async () => {
|
|
||||||
state.hideSpoofedSymbols = $("settings-hide-spoofed-symbols").checked;
|
|
||||||
await saveState();
|
|
||||||
});
|
|
||||||
|
|
||||||
$("settings-hide-low-holders").checked = state.hideLowHolderTokens;
|
$("settings-hide-low-holders").checked = state.hideLowHolderTokens;
|
||||||
$("settings-hide-low-holders").addEventListener("change", async () => {
|
$("settings-hide-low-holders").addEventListener("change", async () => {
|
||||||
state.hideLowHolderTokens = $("settings-hide-low-holders").checked;
|
state.hideLowHolderTokens = $("settings-hide-low-holders").checked;
|
||||||
@@ -329,17 +304,11 @@ function init(ctx) {
|
|||||||
|
|
||||||
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
||||||
$("settings-dust-threshold").addEventListener("change", async () => {
|
$("settings-dust-threshold").addEventListener("change", async () => {
|
||||||
const raw = $("settings-dust-threshold").value.trim();
|
const val = parseInt($("settings-dust-threshold").value, 10);
|
||||||
const val = Number(raw);
|
if (!isNaN(val) && val >= 0) {
|
||||||
// 0 is accepted and means "hide nothing". Empty, negative,
|
|
||||||
// fractional and non-numeric input is rejected outright rather than
|
|
||||||
// coerced, and the field is put back to the stored threshold so it
|
|
||||||
// never shows a value the wallet is not using.
|
|
||||||
if (raw !== "" && Number.isInteger(val) && val >= 0) {
|
|
||||||
state.dustThresholdGwei = val;
|
state.dustThresholdGwei = val;
|
||||||
await saveState();
|
await saveState();
|
||||||
}
|
}
|
||||||
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
$("settings-utc-timestamps").checked = state.utcTimestamps;
|
$("settings-utc-timestamps").checked = state.utcTimestamps;
|
||||||
|
|||||||
@@ -1,154 +0,0 @@
|
|||||||
// Recovery phrase display for HD wallets.
|
|
||||||
//
|
|
||||||
// The phrase is the secret that owns every address in the wallet, so it is
|
|
||||||
// handled under four rules:
|
|
||||||
//
|
|
||||||
// 1. Only an HD wallet reaches this screen (walletHasRecoveryPhrase).
|
|
||||||
// 2. Nothing is decrypted, and nothing is written into the DOM, until
|
|
||||||
// decryptWithPassword has accepted the password.
|
|
||||||
// 3. Leaving the screen by any path wipes it, via the onViewLeave hook,
|
|
||||||
// and a decrypt still in flight when that happens is discarded
|
|
||||||
// instead of written (revealGeneration).
|
|
||||||
// 4. The phrase never reaches the logger. This module deliberately does
|
|
||||||
// not import src/shared/log.js, and the failed-decrypt path reports a
|
|
||||||
// fixed sentence rather than the caught error.
|
|
||||||
//
|
|
||||||
// The phrase is also never assigned to `state`, so it cannot be persisted
|
|
||||||
// to extension storage, and "show-phrase" is excluded from RESTORABLE_VIEWS
|
|
||||||
// so the popup can never reopen onto it.
|
|
||||||
|
|
||||||
const {
|
|
||||||
$,
|
|
||||||
showView,
|
|
||||||
showFlash,
|
|
||||||
flashCopyFeedback,
|
|
||||||
goBack,
|
|
||||||
onViewLeave,
|
|
||||||
pushCurrentView,
|
|
||||||
} = require("./helpers");
|
|
||||||
const { state } = require("../../shared/state");
|
|
||||||
const { decryptWithPassword } = require("../../shared/vault");
|
|
||||||
const { walletHasRecoveryPhrase } = require("../../shared/wallet");
|
|
||||||
|
|
||||||
const VIEW = "show-phrase";
|
|
||||||
|
|
||||||
let walletIndex = null;
|
|
||||||
|
|
||||||
// Bumped by every clear(), which is what leaving the screen runs. reveal()
|
|
||||||
// captures it before awaiting the decrypt and refuses to touch the DOM if
|
|
||||||
// it has moved: a decrypt still in flight when the screen is left would
|
|
||||||
// otherwise write the phrase *after* the wipe, with nothing scheduled to
|
|
||||||
// wipe it again, leaving it in the hidden view for the life of the popup.
|
|
||||||
let revealGeneration = 0;
|
|
||||||
|
|
||||||
// True only if the reveal that captured `generation` is still the live one:
|
|
||||||
// the screen has not been left, cleared, or re-entered for another wallet
|
|
||||||
// since it started.
|
|
||||||
function isCurrentReveal(generation) {
|
|
||||||
return (
|
|
||||||
generation === revealGeneration &&
|
|
||||||
walletIndex !== null &&
|
|
||||||
state.currentView === VIEW
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail(message) {
|
|
||||||
$("show-phrase-flash").textContent = message;
|
|
||||||
$("show-phrase-flash").style.visibility = "visible";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wipe every trace of the phrase and drop the wallet selection. Safe to
|
|
||||||
// call when nothing was ever revealed, and safe to call twice.
|
|
||||||
function clear() {
|
|
||||||
walletIndex = null;
|
|
||||||
revealGeneration += 1;
|
|
||||||
$("show-phrase-value").textContent = "";
|
|
||||||
$("show-phrase-password").value = "";
|
|
||||||
$("show-phrase-result").classList.add("hidden");
|
|
||||||
$("show-phrase-password-section").classList.remove("hidden");
|
|
||||||
$("show-phrase-flash").textContent = "";
|
|
||||||
$("show-phrase-flash").style.visibility = "hidden";
|
|
||||||
}
|
|
||||||
|
|
||||||
function show(walletIdx) {
|
|
||||||
const wallet = state.wallets[walletIdx];
|
|
||||||
if (!walletHasRecoveryPhrase(wallet)) {
|
|
||||||
showFlash("This wallet does not have a recovery phrase.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
clear();
|
|
||||||
walletIndex = walletIdx;
|
|
||||||
$("show-phrase-wallet-name").textContent =
|
|
||||||
wallet.name || "Wallet " + (walletIdx + 1);
|
|
||||||
// Pushed here rather than by the caller: this function can return
|
|
||||||
// without navigating, and a push that happened anyway would leave an
|
|
||||||
// entry on the stack that no screen transition matches.
|
|
||||||
pushCurrentView();
|
|
||||||
showView(VIEW);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function reveal() {
|
|
||||||
const password = $("show-phrase-password").value;
|
|
||||||
if (!password) {
|
|
||||||
fail("Please enter your password.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (walletIndex === null) {
|
|
||||||
fail("No wallet is selected.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const wallet = state.wallets[walletIndex];
|
|
||||||
if (!walletHasRecoveryPhrase(wallet)) {
|
|
||||||
fail("This wallet does not have a recovery phrase.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const btn = $("btn-show-phrase-reveal");
|
|
||||||
btn.disabled = true;
|
|
||||||
btn.classList.add("text-muted");
|
|
||||||
const generation = revealGeneration;
|
|
||||||
try {
|
|
||||||
const phrase = await decryptWithPassword(
|
|
||||||
wallet.encryptedSecret,
|
|
||||||
password,
|
|
||||||
);
|
|
||||||
// The only suspension point in this view, and the only place a
|
|
||||||
// secret is written: if the screen was left while the decrypt ran,
|
|
||||||
// the wipe has already happened and this write must not land.
|
|
||||||
if (!isCurrentReveal(generation)) return;
|
|
||||||
$("show-phrase-password").value = "";
|
|
||||||
$("show-phrase-password-section").classList.add("hidden");
|
|
||||||
$("show-phrase-value").textContent = phrase;
|
|
||||||
$("show-phrase-result").classList.remove("hidden");
|
|
||||||
$("show-phrase-flash").textContent = "";
|
|
||||||
$("show-phrase-flash").style.visibility = "hidden";
|
|
||||||
} catch {
|
|
||||||
if (!isCurrentReveal(generation)) return;
|
|
||||||
// Deliberately not the caught error: the message is fixed so that
|
|
||||||
// nothing derived from the ciphertext or the attempt can surface.
|
|
||||||
fail("That password is not correct. Please try again.");
|
|
||||||
} finally {
|
|
||||||
btn.disabled = false;
|
|
||||||
btn.classList.remove("text-muted");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
onViewLeave(VIEW, clear);
|
|
||||||
|
|
||||||
$("btn-show-phrase-back").addEventListener("click", () => {
|
|
||||||
goBack();
|
|
||||||
});
|
|
||||||
|
|
||||||
$("btn-show-phrase-reveal").addEventListener("click", reveal);
|
|
||||||
|
|
||||||
$("show-phrase-value").addEventListener("click", () => {
|
|
||||||
const phrase = $("show-phrase-value").textContent;
|
|
||||||
if (!phrase) return;
|
|
||||||
navigator.clipboard.writeText(phrase);
|
|
||||||
showFlash("Copied!");
|
|
||||||
flashCopyFeedback($("show-phrase-value"));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, show };
|
|
||||||
@@ -21,16 +21,6 @@ const { log } = require("../../shared/log");
|
|||||||
const POLL_INTERVAL_MS = 10000;
|
const POLL_INTERVAL_MS = 10000;
|
||||||
const TIMEOUT_MS = 60000;
|
const TIMEOUT_MS = 60000;
|
||||||
|
|
||||||
// How many receipt lookups may fail in a row before the wait is ended and
|
|
||||||
// the failure reported. A lookup that throws says nothing about the
|
|
||||||
// transaction, so one must not end the wait — but an RPC that never answers
|
|
||||||
// (a mistyped URL in settings is the ordinary case) must not leave the wait
|
|
||||||
// running forever either, least of all a persisted one that every popup
|
|
||||||
// open would resume. Six is 60 seconds at the poll cadence: the same
|
|
||||||
// patience the confirmation deadline gets. Any lookup that answers, with a
|
|
||||||
// receipt or with null, resets the count.
|
|
||||||
const MAX_CONSECUTIVE_LOOKUP_FAILURES = 6;
|
|
||||||
|
|
||||||
let ctx;
|
let ctx;
|
||||||
let elapsedTimer = null;
|
let elapsedTimer = null;
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
@@ -109,7 +99,6 @@ function startWait(txInfo, txHash, broadcastTime, pollNow) {
|
|||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
const provider = getProvider(state.rpcUrl);
|
const provider = getProvider(state.rpcUrl);
|
||||||
let consecutiveFailures = 0;
|
|
||||||
|
|
||||||
async function poll() {
|
async function poll() {
|
||||||
if (id !== waitId) return;
|
if (id !== waitId) return;
|
||||||
@@ -135,25 +124,8 @@ function startWait(txInfo, txHash, broadcastTime, pollNow) {
|
|||||||
showSuccess(txInfo, txHash, receipt.blockNumber);
|
showSuccess(txInfo, txHash, receipt.blockNumber);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!answered) {
|
// Keep polling until a lookup actually answers; the next tick may.
|
||||||
consecutiveFailures++;
|
if (!answered) return;
|
||||||
// The failure is the user's news, and it is a different fact
|
|
||||||
// from "the transaction did not confirm" — the chain was never
|
|
||||||
// asked. Ending the wait here is what keeps it bounded and
|
|
||||||
// gives the user a Done button to leave by.
|
|
||||||
if (consecutiveFailures >= MAX_CONSECUTIVE_LOOKUP_FAILURES) {
|
|
||||||
showError(
|
|
||||||
txInfo,
|
|
||||||
txHash,
|
|
||||||
"The network could not be reached to check this transaction — " +
|
|
||||||
MAX_CONSECUTIVE_LOOKUP_FAILURES +
|
|
||||||
" lookups failed in a row. Check the RPC URL in Settings. The transaction may still have confirmed — check Etherscan.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Otherwise keep polling: the next tick may answer.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
consecutiveFailures = 0;
|
|
||||||
if (Date.now() - broadcastTime >= TIMEOUT_MS) {
|
if (Date.now() - broadcastTime >= TIMEOUT_MS) {
|
||||||
showError(
|
showError(
|
||||||
txInfo,
|
txInfo,
|
||||||
@@ -177,26 +149,16 @@ function showWait(txInfo, txHash) {
|
|||||||
// Resume a wait persisted by a previous popup session. The deadline still
|
// Resume a wait persisted by a previous popup session. The deadline still
|
||||||
// runs from the original broadcast, so a wait that has already outlived it
|
// runs from the original broadcast, so a wait that has already outlived it
|
||||||
// resolves on the immediate first poll rather than restarting the clock.
|
// resolves on the immediate first poll rather than restarting the clock.
|
||||||
// Returns false when there is nothing resumable to resume. Every field
|
// Returns false when there is nothing resumable to resume: the whole
|
||||||
// startWait() goes on to use is validated, not just the presence of the
|
// payload is validated, because startWait() dereferences txInfo and does
|
||||||
// containers: txInfo.to reaches addressTitle(), which calls
|
// arithmetic on broadcastTime, and a partial one would throw out of
|
||||||
// address.toLowerCase(), and txInfo.amount is rendered into the summary, so
|
// restoreView() or leave an unexitable wait counting "NaNs".
|
||||||
// an object merely missing one of them throws a TypeError out of
|
|
||||||
// restoreView() — which init() does not guard, skipping the rest of popup
|
|
||||||
// init and leaving wait-tx on screen with no back control. A non-numeric
|
|
||||||
// broadcastTime leaves an unexitable wait counting "NaNs". txInfo.token and
|
|
||||||
// txInfo.tokenSymbol are deliberately unchecked: they are compared and
|
|
||||||
// coalesced rather than dereferenced, and tokenSymbol is null for ETH.
|
|
||||||
function restoreWait() {
|
function restoreWait() {
|
||||||
const d = state.viewData;
|
const d = state.viewData;
|
||||||
if (!d || !d.pendingWait) return false;
|
if (!d || !d.pendingWait) return false;
|
||||||
const w = d.pendingWait;
|
const w = d.pendingWait;
|
||||||
if (!w.hash) return false;
|
if (!w.hash) return false;
|
||||||
// typeof [] is "object", so an array passes an object check.
|
if (!w.txInfo || typeof w.txInfo !== "object") return false;
|
||||||
const info = w.txInfo;
|
|
||||||
if (!info || typeof info !== "object" || Array.isArray(info)) return false;
|
|
||||||
if (typeof info.to !== "string" || !info.to) return false;
|
|
||||||
if (typeof info.amount !== "string" || !info.amount) return false;
|
|
||||||
if (typeof w.broadcastTime !== "number" || !isFinite(w.broadcastTime)) {
|
if (typeof w.broadcastTime !== "number" || !isFinite(w.broadcastTime)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,114 +0,0 @@
|
|||||||
// Periodic scheduling for the background context.
|
|
||||||
//
|
|
||||||
// The Chrome MV3 service worker is terminated after roughly 30 seconds idle,
|
|
||||||
// which takes every setInterval/setTimeout with it. The extension alarms API
|
|
||||||
// is the mechanism that survives: the browser holds the schedule and wakes
|
|
||||||
// the worker to deliver onAlarm. Firefox MV2 runs a persistent background
|
|
||||||
// page where timers would survive, but alarms behave identically there, so
|
|
||||||
// both targets share this path and both manifests declare the "alarms"
|
|
||||||
// permission.
|
|
||||||
//
|
|
||||||
// Periods are whole minutes at or above the browser-enforced one-minute
|
|
||||||
// minimum, so nothing here is silently clamped to a slower cadence.
|
|
||||||
//
|
|
||||||
// Trap for anyone changing a period: each job also carries a freshness guard
|
|
||||||
// that can veto its own scheduled tick. A guard timed to the alarm period
|
|
||||||
// halves the real cadence, because the guard is measured from when the last
|
|
||||||
// run finished and the alarm fires one run-duration earlier than that. Every
|
|
||||||
// guard must therefore either be strictly shorter than the period it gates or
|
|
||||||
// be bypassed on the scheduled tick — see backgroundRefresh() in
|
|
||||||
// src/background/index.js and updatePhishingList() in shared/phishingDomains.js.
|
|
||||||
|
|
||||||
const BALANCE_REFRESH_ALARM = "autistmask-balance-refresh";
|
|
||||||
const PHISHING_REFRESH_ALARM = "autistmask-phishing-refresh";
|
|
||||||
|
|
||||||
const MIN_ALARM_PERIOD_MINUTES = 1;
|
|
||||||
const BALANCE_REFRESH_PERIOD_MINUTES = 1;
|
|
||||||
const PHISHING_REFRESH_PERIOD_MINUTES = 24 * 60;
|
|
||||||
|
|
||||||
// Resolved on use rather than captured at module load: the worker is torn
|
|
||||||
// down and re-evaluated repeatedly, and tests install a stub after requiring
|
|
||||||
// the module.
|
|
||||||
function alarmsApi() {
|
|
||||||
if (typeof browser !== "undefined" && browser.alarms) return browser.alarms;
|
|
||||||
if (typeof chrome !== "undefined" && chrome.alarms) return chrome.alarms;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create an alarm unless one with the requested period already exists.
|
|
||||||
*
|
|
||||||
* The existence check is load-bearing: creating an alarm resets its schedule,
|
|
||||||
* and this runs on every worker wake. Creating unconditionally would push the
|
|
||||||
* next fire time out on every incoming message, so a busy extension would
|
|
||||||
* never see the alarm fire at all.
|
|
||||||
*
|
|
||||||
* The period comparison is equally load-bearing in the other direction: an
|
|
||||||
* alarm created by an older version keeps its old period forever unless a
|
|
||||||
* changed constant re-creates it, so a period edit would never reach an
|
|
||||||
* existing install. Re-creating on a period change happens once and then
|
|
||||||
* settles into the existence check above.
|
|
||||||
*
|
|
||||||
* @param {string} name
|
|
||||||
* @param {number} periodInMinutes
|
|
||||||
* @returns {Promise<boolean>} true if the alarm was created by this call.
|
|
||||||
*/
|
|
||||||
async function ensureAlarm(name, periodInMinutes) {
|
|
||||||
const api = alarmsApi();
|
|
||||||
if (!api) return false;
|
|
||||||
const period = Math.max(periodInMinutes, MIN_ALARM_PERIOD_MINUTES);
|
|
||||||
const existing = await api.get(name);
|
|
||||||
if (existing && existing.periodInMinutes === period) return false;
|
|
||||||
api.create(name, {
|
|
||||||
periodInMinutes: period,
|
|
||||||
delayInMinutes: period,
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ensure both recurring background jobs are scheduled. Safe to call on every
|
|
||||||
* worker start, on onInstalled and on onStartup.
|
|
||||||
*
|
|
||||||
* @returns {Promise<{balance: boolean, phishing: boolean}>} which alarms this
|
|
||||||
* call had to create.
|
|
||||||
*/
|
|
||||||
async function ensureRecurringAlarms() {
|
|
||||||
const balance = await ensureAlarm(
|
|
||||||
BALANCE_REFRESH_ALARM,
|
|
||||||
BALANCE_REFRESH_PERIOD_MINUTES,
|
|
||||||
);
|
|
||||||
const phishing = await ensureAlarm(
|
|
||||||
PHISHING_REFRESH_ALARM,
|
|
||||||
PHISHING_REFRESH_PERIOD_MINUTES,
|
|
||||||
);
|
|
||||||
return { balance, phishing };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register per-alarm handlers. One listener dispatches by alarm name so the
|
|
||||||
* worker only ever installs a single onAlarm listener.
|
|
||||||
*
|
|
||||||
* @param {Object<string, function>} handlers
|
|
||||||
* @returns {boolean} true if the listener was installed.
|
|
||||||
*/
|
|
||||||
function registerAlarmHandlers(handlers) {
|
|
||||||
const api = alarmsApi();
|
|
||||||
if (!api || !api.onAlarm) return false;
|
|
||||||
api.onAlarm.addListener((alarm) => {
|
|
||||||
const handler = handlers[alarm && alarm.name];
|
|
||||||
if (handler) handler();
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
BALANCE_REFRESH_ALARM,
|
|
||||||
PHISHING_REFRESH_ALARM,
|
|
||||||
MIN_ALARM_PERIOD_MINUTES,
|
|
||||||
BALANCE_REFRESH_PERIOD_MINUTES,
|
|
||||||
PHISHING_REFRESH_PERIOD_MINUTES,
|
|
||||||
ensureAlarm,
|
|
||||||
ensureRecurringAlarms,
|
|
||||||
registerAlarmHandlers,
|
|
||||||
};
|
|
||||||
@@ -1,11 +1,6 @@
|
|||||||
// Cached ENS reverse resolution.
|
// Cached ENS reverse resolution.
|
||||||
// Resolves addresses to ENS names via ethers provider.lookupAddress(),
|
// Resolves addresses to ENS names via ethers provider.lookupAddress(),
|
||||||
// caching results in localStorage with a 12-hour TTL.
|
// caching results in localStorage with a 12-hour TTL.
|
||||||
//
|
|
||||||
// POPUP ONLY. localStorage does not exist in the Chrome MV3 service worker,
|
|
||||||
// so this module must not be pulled into src/background/. Anything the
|
|
||||||
// background context needs to cache goes in extension storage instead (see
|
|
||||||
// shared/phishingDomains.js).
|
|
||||||
|
|
||||||
const { getProvider } = require("./balances");
|
const { getProvider } = require("./balances");
|
||||||
const { log } = require("./log");
|
const { log } = require("./log");
|
||||||
|
|||||||
@@ -8,14 +8,8 @@
|
|||||||
// The domain-checker checks the in-memory delta first (fresh/recent scam
|
// The domain-checker checks the in-memory delta first (fresh/recent scam
|
||||||
// sites), then falls back to the vendored list.
|
// sites), then falls back to the vendored list.
|
||||||
//
|
//
|
||||||
// If the delta and its fetch timestamp fit in 256 KiB they are persisted to
|
// If the delta is under 256 KiB it is persisted to localStorage so it
|
||||||
// extension storage, so they survive termination of the MV3 service worker.
|
// survives extension/service-worker restarts.
|
||||||
// Extension storage, not localStorage: localStorage does not exist in a
|
|
||||||
// service worker, so the previous persistence never ran on Chrome at all.
|
|
||||||
// The stored timestamps are what keep a restarted worker from re-fetching on
|
|
||||||
// every wake while still noticing an overdue update. Those guards apply to the
|
|
||||||
// startup path only; the 24-hour alarm tick bypasses them, or it would veto
|
|
||||||
// its own refresh — see updatePhishingList().
|
|
||||||
|
|
||||||
const vendoredConfig = require("./phishingBlocklist.json");
|
const vendoredConfig = require("./phishingBlocklist.json");
|
||||||
|
|
||||||
@@ -23,14 +17,7 @@ const BLOCKLIST_URL =
|
|||||||
"https://raw.githubusercontent.com/MetaMask/eth-phishing-detect/main/src/config.json";
|
"https://raw.githubusercontent.com/MetaMask/eth-phishing-detect/main/src/config.json";
|
||||||
|
|
||||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
const REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
// Floor on how often an unscheduled path may hit the network. The worker is
|
|
||||||
// revived every ~30 seconds while the browser is busy, and every revival runs
|
|
||||||
// the startup path; without a persisted record of the last attempt, any state
|
|
||||||
// that leaves lastFetchTime unset — a fetch that failed, or a delta too large
|
|
||||||
// to store — would download the full list on every single wake.
|
|
||||||
const MIN_FETCH_ATTEMPT_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
|
|
||||||
|
|
||||||
const DELTA_STORAGE_KEY = "phishing-delta";
|
const DELTA_STORAGE_KEY = "phishing-delta";
|
||||||
const MAX_DELTA_BYTES = 256 * 1024; // 256 KiB
|
const MAX_DELTA_BYTES = 256 * 1024; // 256 KiB
|
||||||
|
|
||||||
@@ -42,104 +29,45 @@ const vendoredBlacklist = new Set(
|
|||||||
// Delta set — only entries from live list that are NOT in vendored.
|
// Delta set — only entries from live list that are NOT in vendored.
|
||||||
let deltaBlacklist = new Set();
|
let deltaBlacklist = new Set();
|
||||||
let lastFetchTime = 0;
|
let lastFetchTime = 0;
|
||||||
let lastAttemptTime = 0;
|
|
||||||
let fetchPromise = null;
|
let fetchPromise = null;
|
||||||
let loadPromise = null;
|
let refreshTimer = null;
|
||||||
|
|
||||||
// Resolved on use rather than captured at module load, so a test can install
|
|
||||||
// a stub after requiring the module and so the popup — which has no reason to
|
|
||||||
// touch the delta — does not fail to load where the API is absent.
|
|
||||||
function storageApi() {
|
|
||||||
if (typeof browser !== "undefined" && browser.storage) {
|
|
||||||
return browser.storage.local;
|
|
||||||
}
|
|
||||||
if (typeof chrome !== "undefined" && chrome.storage) {
|
|
||||||
return chrome.storage.local;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sanitise a timestamp read back from storage.
|
* Load delta entries from localStorage on startup.
|
||||||
*
|
* Called once during module initialization in the background script.
|
||||||
* A value in the future is permanent poison: every guard here measures elapsed
|
|
||||||
* time as `Date.now() - stamp` and tests only the lower bound, so a stamp a
|
|
||||||
* year ahead suppresses updates for a year with no path that ever clears it.
|
|
||||||
* Clock skew and a restored profile backup both produce one. Since these
|
|
||||||
* timestamps only ever gate work, discarding an impossible one is safe: it
|
|
||||||
* costs at most a single extra fetch and restores a sane value immediately.
|
|
||||||
*
|
|
||||||
* @param {unknown} value
|
|
||||||
* @returns {number} the timestamp, or 0 if it is unusable.
|
|
||||||
*/
|
*/
|
||||||
function sanitizeTimestamp(value) {
|
function loadDeltaFromStorage() {
|
||||||
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
|
|
||||||
if (value <= 0 || value > Date.now()) return 0;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load the persisted delta and its timestamps from extension storage.
|
|
||||||
* Runs once per worker lifetime; every entry point funnels through
|
|
||||||
* ensureDeltaLoaded() so a wake from termination restores state exactly once.
|
|
||||||
*
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function loadDeltaFromStorage() {
|
|
||||||
const storage = storageApi();
|
|
||||||
if (!storage) return;
|
|
||||||
try {
|
try {
|
||||||
const result = await storage.get(DELTA_STORAGE_KEY);
|
const raw = localStorage.getItem(DELTA_STORAGE_KEY);
|
||||||
const data = result && result[DELTA_STORAGE_KEY];
|
if (!raw) return;
|
||||||
if (!data) return;
|
const data = JSON.parse(raw);
|
||||||
if (Array.isArray(data.blacklist)) {
|
if (data.blacklist && Array.isArray(data.blacklist)) {
|
||||||
deltaBlacklist = new Set(
|
deltaBlacklist = new Set(
|
||||||
data.blacklist.map((d) => d.toLowerCase()),
|
data.blacklist.map((d) => d.toLowerCase()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
lastFetchTime = sanitizeTimestamp(data.lastFetchTime);
|
|
||||||
lastAttemptTime = sanitizeTimestamp(data.lastAttemptTime);
|
|
||||||
} catch {
|
} catch {
|
||||||
// Storage unavailable or corrupt — start empty and re-fetch.
|
// localStorage unavailable or corrupt — start empty
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureDeltaLoaded() {
|
|
||||||
if (!loadPromise) loadPromise = loadDeltaFromStorage();
|
|
||||||
return loadPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist the delta and its timestamps if they fit within MAX_DELTA_BYTES.
|
* Persist delta to localStorage if it fits within MAX_DELTA_BYTES.
|
||||||
*
|
|
||||||
* The 256 KiB cap covers the delta and its freshness claim: when the delta is
|
|
||||||
* too large to keep, lastFetchTime goes with it, so the next start re-fetches
|
|
||||||
* rather than trusting a freshness claim for a delta it no longer holds.
|
|
||||||
* lastAttemptTime is written either way — it records that the network was
|
|
||||||
* contacted, which stays true whatever became of the response, and it is what
|
|
||||||
* stops a permanently oversized list from downloading on every worker wake.
|
|
||||||
*
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
*/
|
||||||
async function saveDeltaToStorage() {
|
function saveDeltaToStorage() {
|
||||||
const storage = storageApi();
|
|
||||||
if (!storage) return;
|
|
||||||
try {
|
try {
|
||||||
const data = {
|
const data = {
|
||||||
blacklist: Array.from(deltaBlacklist),
|
blacklist: Array.from(deltaBlacklist),
|
||||||
lastFetchTime,
|
|
||||||
lastAttemptTime,
|
|
||||||
};
|
};
|
||||||
const json = JSON.stringify(data);
|
const json = JSON.stringify(data);
|
||||||
if (json.length < MAX_DELTA_BYTES) {
|
if (json.length < MAX_DELTA_BYTES) {
|
||||||
await storage.set({ [DELTA_STORAGE_KEY]: data });
|
localStorage.setItem(DELTA_STORAGE_KEY, json);
|
||||||
} else if (lastAttemptTime > 0) {
|
|
||||||
await storage.set({ [DELTA_STORAGE_KEY]: { lastAttemptTime } });
|
|
||||||
} else {
|
} else {
|
||||||
await storage.remove(DELTA_STORAGE_KEY);
|
// Too large — remove stale key if present
|
||||||
|
localStorage.removeItem(DELTA_STORAGE_KEY);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Storage unavailable — skip silently
|
// localStorage unavailable — skip silently
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +76,6 @@ async function saveDeltaToStorage() {
|
|||||||
* Used for both live fetches and testing.
|
* Used for both live fetches and testing.
|
||||||
*
|
*
|
||||||
* @param {{ blacklist?: string[] }} config
|
* @param {{ blacklist?: string[] }} config
|
||||||
* @returns {Promise<void>} resolves once the delta has been persisted.
|
|
||||||
*/
|
*/
|
||||||
function loadConfig(config) {
|
function loadConfig(config) {
|
||||||
const liveBlacklist = (config.blacklist || []).map((d) => d.toLowerCase());
|
const liveBlacklist = (config.blacklist || []).map((d) => d.toLowerCase());
|
||||||
@@ -159,7 +86,7 @@ function loadConfig(config) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
lastFetchTime = Date.now();
|
lastFetchTime = Date.now();
|
||||||
return saveDeltaToStorage();
|
saveDeltaToStorage();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -184,11 +111,6 @@ function hostnameVariants(hostname) {
|
|||||||
* Check if a hostname is on the phishing blocklist.
|
* Check if a hostname is on the phishing blocklist.
|
||||||
* Checks delta first (fresh/recent scam sites), then vendored list.
|
* Checks delta first (fresh/recent scam sites), then vendored list.
|
||||||
*
|
*
|
||||||
* Synchronous by design — callers answer an approval prompt with it. On a
|
|
||||||
* worker that has just woken, the persisted delta may still be loading; the
|
|
||||||
* vendored list, which is bundled and always present, carries the check until
|
|
||||||
* it lands.
|
|
||||||
*
|
|
||||||
* @param {string} hostname - The hostname to check.
|
* @param {string} hostname - The hostname to check.
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
@@ -205,59 +127,28 @@ function isPhishingDomain(hostname) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the latest blocklist and compute delta against vendored data.
|
* Fetch the latest blocklist and compute delta against vendored data.
|
||||||
* De-duplicates concurrent fetches. Results are cached for CACHE_TTL_MS,
|
* De-duplicates concurrent fetches. Results are cached for CACHE_TTL_MS.
|
||||||
* counted from the persisted timestamp so the cache outlives the worker.
|
|
||||||
*
|
*
|
||||||
* `force` is what makes the 24-hour alarm actually refresh every 24 hours.
|
|
||||||
* The alarm fires one period after the previous alarm, but lastFetchTime is
|
|
||||||
* stamped when that fetch *completed*, so an unforced tick lands one fetch
|
|
||||||
* latency inside its own TTL, skips, and turns the real cadence into 48 hours.
|
|
||||||
* Shortening the TTL instead would not fix it: the worker wakes every ~30
|
|
||||||
* seconds and the startup path re-checks the TTL each time, so a shortened TTL
|
|
||||||
* simply becomes the real cadence. The TTL is there to stop redundant fetches
|
|
||||||
* on wake, and the scheduled tick is not redundant, so it bypasses it.
|
|
||||||
*
|
|
||||||
* @param {{force?: boolean}} [opts] force: fetch unless one is already in
|
|
||||||
* flight, ignoring both the freshness and the retry guard. For the scheduled
|
|
||||||
* alarm tick only.
|
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async function updatePhishingList({ force = false } = {}) {
|
async function updatePhishingList() {
|
||||||
// A worker that has just been revived knows nothing until the persisted
|
// Skip if recently fetched
|
||||||
// record is back in memory; without this the freshness check below would
|
if (Date.now() - lastFetchTime < CACHE_TTL_MS && lastFetchTime > 0) {
|
||||||
// always see 0 and re-fetch on every wake.
|
return;
|
||||||
await ensureDeltaLoaded();
|
|
||||||
|
|
||||||
if (!force) {
|
|
||||||
const now = Date.now();
|
|
||||||
// Skip if recently fetched.
|
|
||||||
if (lastFetchTime > 0 && now - lastFetchTime < CACHE_TTL_MS) return;
|
|
||||||
// Skip if the network was contacted recently and the result was not
|
|
||||||
// usable — a failed fetch or an oversized delta leaves lastFetchTime
|
|
||||||
// unset, and without this every wake would retry.
|
|
||||||
if (
|
|
||||||
lastAttemptTime > 0 &&
|
|
||||||
now - lastAttemptTime < MIN_FETCH_ATTEMPT_INTERVAL_MS
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// De-duplicate concurrent calls
|
// De-duplicate concurrent calls
|
||||||
if (fetchPromise) return fetchPromise;
|
if (fetchPromise) return fetchPromise;
|
||||||
|
|
||||||
fetchPromise = (async () => {
|
fetchPromise = (async () => {
|
||||||
lastAttemptTime = Date.now();
|
|
||||||
try {
|
try {
|
||||||
const resp = await fetch(BLOCKLIST_URL);
|
const resp = await fetch(BLOCKLIST_URL);
|
||||||
if (!resp.ok) throw new Error("HTTP " + resp.status);
|
if (!resp.ok) throw new Error("HTTP " + resp.status);
|
||||||
const config = await resp.json();
|
const config = await resp.json();
|
||||||
await loadConfig(config);
|
loadConfig(config);
|
||||||
} catch {
|
} catch {
|
||||||
// Silently fail — vendored list still provides coverage. Persist
|
// Silently fail — vendored list still provides coverage.
|
||||||
// the attempt so a persistently failing fetch is retried on the
|
// We'll retry next time.
|
||||||
// schedule rather than on every wake.
|
|
||||||
await saveDeltaToStorage();
|
|
||||||
} finally {
|
} finally {
|
||||||
fetchPromise = null;
|
fetchPromise = null;
|
||||||
}
|
}
|
||||||
@@ -267,29 +158,12 @@ async function updatePhishingList({ force = false } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restore persisted state and fetch if the list is overdue.
|
* Start periodic refresh of the phishing list.
|
||||||
*
|
* Should be called once from the background script on startup.
|
||||||
* Called from the background script every time it starts — a fresh install,
|
|
||||||
* a browser start, and every revival of a terminated service worker all land
|
|
||||||
* here. The recurring 24-hour schedule itself is an alarm (see
|
|
||||||
* shared/alarms.js), not a timer, because timers die with the worker.
|
|
||||||
*
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
*/
|
||||||
async function initPhishingList() {
|
function startPeriodicRefresh() {
|
||||||
await ensureDeltaLoaded();
|
if (refreshTimer) return;
|
||||||
return updatePhishingList();
|
refreshTimer = setInterval(updatePhishingList, REFRESH_INTERVAL_MS);
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The 24-hour alarm tick. Separate from initPhishingList() because this is the
|
|
||||||
* scheduled refresh and must not be vetoed by the guards that exist to keep
|
|
||||||
* the unscheduled startup path off the network.
|
|
||||||
*
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function refreshPhishingListOnSchedule() {
|
|
||||||
return updatePhishingList({ force: true });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -316,22 +190,21 @@ function getDeltaSize() {
|
|||||||
function _reset() {
|
function _reset() {
|
||||||
deltaBlacklist = new Set();
|
deltaBlacklist = new Set();
|
||||||
lastFetchTime = 0;
|
lastFetchTime = 0;
|
||||||
lastAttemptTime = 0;
|
|
||||||
fetchPromise = null;
|
fetchPromise = null;
|
||||||
loadPromise = null;
|
if (refreshTimer) {
|
||||||
|
clearInterval(refreshTimer);
|
||||||
|
refreshTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Load persisted delta on module initialization
|
||||||
|
loadDeltaFromStorage();
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
isPhishingDomain,
|
isPhishingDomain,
|
||||||
updatePhishingList,
|
updatePhishingList,
|
||||||
refreshPhishingListOnSchedule,
|
startPeriodicRefresh,
|
||||||
initPhishingList,
|
|
||||||
loadDeltaFromStorage,
|
|
||||||
loadConfig,
|
loadConfig,
|
||||||
CACHE_TTL_MS,
|
|
||||||
MIN_FETCH_ATTEMPT_INTERVAL_MS,
|
|
||||||
DELTA_STORAGE_KEY,
|
|
||||||
MAX_DELTA_BYTES,
|
|
||||||
getBlocklistSize,
|
getBlocklistSize,
|
||||||
getDeltaSize,
|
getDeltaSize,
|
||||||
hostnameVariants,
|
hostnameVariants,
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ const DEFAULT_STATE = {
|
|||||||
deniedSites: {},
|
deniedSites: {},
|
||||||
rememberSiteChoice: true,
|
rememberSiteChoice: true,
|
||||||
showZeroBalanceTokens: true,
|
showZeroBalanceTokens: true,
|
||||||
hideSpoofedSymbols: true,
|
|
||||||
hideLowHolderTokens: true,
|
hideLowHolderTokens: true,
|
||||||
hideFraudContracts: true,
|
hideFraudContracts: true,
|
||||||
hideDustTransactions: true,
|
hideDustTransactions: true,
|
||||||
@@ -62,7 +61,6 @@ async function saveState() {
|
|||||||
deniedSites: state.deniedSites,
|
deniedSites: state.deniedSites,
|
||||||
rememberSiteChoice: state.rememberSiteChoice,
|
rememberSiteChoice: state.rememberSiteChoice,
|
||||||
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
||||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
@@ -114,12 +112,6 @@ async function loadState() {
|
|||||||
saved.showZeroBalanceTokens !== undefined
|
saved.showZeroBalanceTokens !== undefined
|
||||||
? saved.showZeroBalanceTokens
|
? saved.showZeroBalanceTokens
|
||||||
: true;
|
: true;
|
||||||
// A profile written before this setting existed has no key for it.
|
|
||||||
// It is a safety filter, so absent must load as on, not as undefined.
|
|
||||||
state.hideSpoofedSymbols =
|
|
||||||
saved.hideSpoofedSymbols !== undefined
|
|
||||||
? saved.hideSpoofedSymbols
|
|
||||||
: true;
|
|
||||||
state.hideLowHolderTokens =
|
state.hideLowHolderTokens =
|
||||||
saved.hideLowHolderTokens !== undefined
|
saved.hideLowHolderTokens !== undefined
|
||||||
? saved.hideLowHolderTokens
|
? saved.hideLowHolderTokens
|
||||||
|
|||||||
@@ -10,14 +10,6 @@ const { formatEther, formatUnits } = require("ethers");
|
|||||||
const { log, debugFetch } = require("./log");
|
const { log, debugFetch } = require("./log");
|
||||||
const { KNOWN_SYMBOLS, TOKEN_BY_ADDRESS } = require("./tokenList");
|
const { KNOWN_SYMBOLS, TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||||
|
|
||||||
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
|
||||||
// over the address, not part of its identity. Every address comparison in
|
|
||||||
// this file goes through this helper, so an address arriving in checksummed
|
|
||||||
// or upper-case form can never be read as a different address.
|
|
||||||
function normalizeAddress(addr) {
|
|
||||||
return (addr || "").toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTxValue(val) {
|
function formatTxValue(val) {
|
||||||
const parts = val.split(".");
|
const parts = val.split(".");
|
||||||
if (parts.length === 1) return val + ".0000";
|
if (parts.length === 1) return val + ".0000";
|
||||||
@@ -38,10 +30,10 @@ function parseTx(tx, addrLower) {
|
|||||||
let exactValue = formatEther(rawWei);
|
let exactValue = formatEther(rawWei);
|
||||||
let rawAmount = rawWei;
|
let rawAmount = rawWei;
|
||||||
let rawUnit = "wei";
|
let rawUnit = "wei";
|
||||||
let direction = normalizeAddress(from) === addrLower ? "sent" : "received";
|
let direction = from.toLowerCase() === addrLower ? "sent" : "received";
|
||||||
let directionLabel = direction === "sent" ? "Sent" : "Received";
|
let directionLabel = direction === "sent" ? "Sent" : "Received";
|
||||||
if (toIsContract && method && method !== "transfer") {
|
if (toIsContract && method && method !== "transfer") {
|
||||||
const token = TOKEN_BY_ADDRESS.get(normalizeAddress(to));
|
const token = TOKEN_BY_ADDRESS.get(to.toLowerCase());
|
||||||
if (token) {
|
if (token) {
|
||||||
symbol = token.symbol;
|
symbol = token.symbol;
|
||||||
}
|
}
|
||||||
@@ -95,8 +87,7 @@ function parseTokenTransfer(tt, addrLower) {
|
|||||||
const to = tt.to?.hash || "";
|
const to = tt.to?.hash || "";
|
||||||
const decimals = parseInt(tt.total?.decimals || "18", 10);
|
const decimals = parseInt(tt.total?.decimals || "18", 10);
|
||||||
const rawVal = tt.total?.value || "0";
|
const rawVal = tt.total?.value || "0";
|
||||||
const direction =
|
const direction = from.toLowerCase() === addrLower ? "sent" : "received";
|
||||||
normalizeAddress(from) === addrLower ? "sent" : "received";
|
|
||||||
const sym = tt.token?.symbol || "?";
|
const sym = tt.token?.symbol || "?";
|
||||||
return {
|
return {
|
||||||
hash: tt.transaction_hash,
|
hash: tt.transaction_hash,
|
||||||
@@ -113,9 +104,11 @@ function parseTokenTransfer(tt, addrLower) {
|
|||||||
direction: direction,
|
direction: direction,
|
||||||
directionLabel: direction === "sent" ? "Sent" : "Received",
|
directionLabel: direction === "sent" ? "Sent" : "Received",
|
||||||
isError: false,
|
isError: false,
|
||||||
contractAddress: normalizeAddress(
|
contractAddress: (
|
||||||
tt.token?.address_hash || tt.token?.address || "",
|
tt.token?.address_hash ||
|
||||||
),
|
tt.token?.address ||
|
||||||
|
""
|
||||||
|
).toLowerCase(),
|
||||||
holders: parseInt(tt.token?.holders_count || "0", 10),
|
holders: parseInt(tt.token?.holders_count || "0", 10),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -201,7 +194,7 @@ function mergeTransactions(txs, tokenTransfers) {
|
|||||||
|
|
||||||
async function fetchRecentTransactions(address, blockscoutUrl, count = 25) {
|
async function fetchRecentTransactions(address, blockscoutUrl, count = 25) {
|
||||||
log.debugf("fetchRecentTransactions", address);
|
log.debugf("fetchRecentTransactions", address);
|
||||||
const addrLower = normalizeAddress(address);
|
const addrLower = address.toLowerCase();
|
||||||
|
|
||||||
const [txResp, ttResp] = await Promise.all([
|
const [txResp, ttResp] = await Promise.all([
|
||||||
debugFetch(blockscoutUrl + "/addresses/" + address + "/transactions"),
|
debugFetch(blockscoutUrl + "/addresses/" + address + "/transactions"),
|
||||||
@@ -250,45 +243,34 @@ function isSpoofedSymbol(tx) {
|
|||||||
if (!KNOWN_SYMBOLS.has(symbol)) return false;
|
if (!KNOWN_SYMBOLS.has(symbol)) return false;
|
||||||
const legit = KNOWN_SYMBOLS.get(symbol);
|
const legit = KNOWN_SYMBOLS.get(symbol);
|
||||||
if (legit === null) return true; // "ETH" as ERC-20 is always fake
|
if (legit === null) return true; // "ETH" as ERC-20 is always fake
|
||||||
return normalizeAddress(tx.contractAddress) !== normalizeAddress(legit);
|
return tx.contractAddress !== legit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pure filter function. Takes raw transactions and filter settings,
|
// Pure filter function. Takes raw transactions and filter settings,
|
||||||
// returns { transactions, newFraudContracts }.
|
// returns { transactions, newFraudContracts }.
|
||||||
function filterTransactions(txs, filters = {}) {
|
function filterTransactions(txs, filters = {}) {
|
||||||
const fraudSet = new Set(
|
const fraudSet = new Set(
|
||||||
(filters.fraudContracts || []).map(normalizeAddress),
|
(filters.fraudContracts || []).map((a) => a.toLowerCase()),
|
||||||
);
|
);
|
||||||
// The dust threshold defaults only when it is unset (nullish): a
|
|
||||||
// threshold of 0 is a real value meaning "hide nothing", since no
|
|
||||||
// transaction has a value below 0 gwei. It is therefore equivalent to
|
|
||||||
// clearing the hide-dust checkbox, and the two controls cannot override
|
|
||||||
// each other in either direction.
|
|
||||||
const dustThresholdGwei = filters.dustThresholdGwei ?? 100000;
|
|
||||||
const newFraud = [];
|
const newFraud = [];
|
||||||
const filtered = [];
|
const filtered = [];
|
||||||
// Fail-safe, unlike the three flags below: this one is off only when the
|
|
||||||
// caller says so explicitly, so a caller that omits the key keeps the
|
|
||||||
// check rather than silently losing it. The setting also governs the
|
|
||||||
// blocklist learning below, which exists only to serve this check —
|
|
||||||
// leaving learning on while the check is off would re-hide the very rows
|
|
||||||
// the user asked to see, through the fraud-contract rule.
|
|
||||||
const hideSpoofed = filters.hideSpoofedSymbols !== false;
|
|
||||||
|
|
||||||
for (const tx of txs) {
|
for (const tx of txs) {
|
||||||
const contract = normalizeAddress(tx.contractAddress);
|
// Always filter spoofed known symbols and record the fraud contract
|
||||||
|
if (isSpoofedSymbol(tx)) {
|
||||||
// Filter spoofed known symbols and record the fraud contract
|
if (tx.contractAddress && !fraudSet.has(tx.contractAddress)) {
|
||||||
if (hideSpoofed && isSpoofedSymbol(tx)) {
|
fraudSet.add(tx.contractAddress);
|
||||||
if (contract && !fraudSet.has(contract)) {
|
newFraud.push(tx.contractAddress);
|
||||||
fraudSet.add(contract);
|
|
||||||
newFraud.push(contract);
|
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter fraud contracts if setting is on
|
// Filter fraud contracts if setting is on
|
||||||
if (filters.hideFraudContracts && contract && fraudSet.has(contract)) {
|
if (
|
||||||
|
filters.hideFraudContracts &&
|
||||||
|
tx.contractAddress &&
|
||||||
|
fraudSet.has(tx.contractAddress)
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,7 +291,7 @@ function filterTransactions(txs, filters = {}) {
|
|||||||
filters.hideDustTransactions &&
|
filters.hideDustTransactions &&
|
||||||
!tx.isContractCall &&
|
!tx.isContractCall &&
|
||||||
tx.valueGwei !== null &&
|
tx.valueGwei !== null &&
|
||||||
tx.valueGwei < dustThresholdGwei
|
tx.valueGwei < (filters.dustThresholdGwei || 100000)
|
||||||
) {
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,171 +0,0 @@
|
|||||||
// Balance arithmetic for the transaction confirmation screen.
|
|
||||||
//
|
|
||||||
// Pure: no DOM, no network, no state. Everything is exact integer math on
|
|
||||||
// 18-decimal fixed point (wei for ETH), so it can be unit tested directly
|
|
||||||
// instead of through the confirmation view. The caller maps the returned
|
|
||||||
// codes to the reserved message elements on the screen.
|
|
||||||
//
|
|
||||||
// Human decimal strings ("1.25") are scaled to 18 decimals for comparison.
|
|
||||||
// That scale is independent of a token's own decimals: both the amount and
|
|
||||||
// the token balance arrive as human decimal strings, so comparing them at a
|
|
||||||
// common scale is exact.
|
|
||||||
|
|
||||||
const { parseUnits } = require("ethers");
|
|
||||||
|
|
||||||
const SCALE_DECIMALS = 18;
|
|
||||||
|
|
||||||
// Whether the asynchronous fee estimate has arrived yet.
|
|
||||||
const FEE_PENDING = "pending";
|
|
||||||
const FEE_KNOWN = "known";
|
|
||||||
const FEE_UNAVAILABLE = "unavailable";
|
|
||||||
|
|
||||||
const CODES = {
|
|
||||||
// The amount is not a non-negative number we can do exact arithmetic on.
|
|
||||||
AMOUNT_INVALID: "amount-invalid",
|
|
||||||
// ERC-20: the token amount exceeds the token balance.
|
|
||||||
INSUFFICIENT_TOKEN: "insufficient-token",
|
|
||||||
// ETH: the amount alone already exceeds the ETH balance.
|
|
||||||
INSUFFICIENT_ETH: "insufficient-eth",
|
|
||||||
// ETH: the amount fits, the amount plus the network fee does not.
|
|
||||||
INSUFFICIENT_ETH_WITH_FEE: "insufficient-eth-with-fee",
|
|
||||||
// ERC-20: the token balance covers the transfer, the ETH balance does
|
|
||||||
// not cover the network fee it costs.
|
|
||||||
INSUFFICIENT_ETH_FOR_FEE: "insufficient-eth-for-fee",
|
|
||||||
// The fee estimate has not arrived yet.
|
|
||||||
FEE_PENDING: "fee-pending",
|
|
||||||
// The fee estimate failed. Unknown is never treated as zero.
|
|
||||||
FEE_UNAVAILABLE: "fee-unavailable",
|
|
||||||
};
|
|
||||||
|
|
||||||
// The fee that must be reserved for a transaction, in wei: the amount the
|
|
||||||
// node will require, not the amount the transaction is expected to cost.
|
|
||||||
//
|
|
||||||
// A send that pins no fee fields is populated by ethers as a type-2
|
|
||||||
// (EIP-1559) transaction, and a node validates that against
|
|
||||||
// `value + gasLimit * maxFeePerGas`. ethers derives maxFeePerGas as
|
|
||||||
// `baseFeePerGas * 2 + maxPriorityFeePerGas`, so reserving `gasPrice`
|
|
||||||
// (roughly `baseFee + tip`) under-reserves by about `gasLimit * baseFee` and
|
|
||||||
// lets through a transaction the node then rejects with "insufficient funds
|
|
||||||
// for gas * price + value". gasPrice is the fallback only for a network that
|
|
||||||
// offers no type-2 pricing at all.
|
|
||||||
//
|
|
||||||
// Returns null when no usable price is available, which the caller must treat
|
|
||||||
// as a failed estimate rather than as a free transaction.
|
|
||||||
function feeReserveWei(gasLimit, feeData) {
|
|
||||||
if (typeof gasLimit !== "bigint" || gasLimit < 0n) return null;
|
|
||||||
const price = feeData?.maxFeePerGas ?? feeData?.gasPrice;
|
|
||||||
if (typeof price !== "bigint" || price < 0n) return null;
|
|
||||||
return gasLimit * price;
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the transaction is expected to actually cost, in wei — not what must
|
|
||||||
// be reserved for it. A type-2 transaction is charged `baseFee + tip` per gas
|
|
||||||
// and refunded the rest of the cap, and `eth_gasPrice` reports roughly that,
|
|
||||||
// so gasPrice is the estimate and maxFeePerGas is the reserve. On a network
|
|
||||||
// with no type-2 pricing the two are the same number.
|
|
||||||
//
|
|
||||||
// Display only: nothing gates on this. Returns null on the same unusable
|
|
||||||
// inputs as feeReserveWei().
|
|
||||||
function feeEstimateWei(gasLimit, feeData) {
|
|
||||||
if (typeof gasLimit !== "bigint" || gasLimit < 0n) return null;
|
|
||||||
const price = feeData?.gasPrice ?? feeData?.maxFeePerGas;
|
|
||||||
if (typeof price !== "bigint" || price < 0n) return null;
|
|
||||||
return gasLimit * price;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Scale a human decimal string to 18-decimal fixed point. Returns null when
|
|
||||||
// the value is not a decimal number or carries more precision than the scale
|
|
||||||
// can hold, which the caller must treat as unusable rather than as zero.
|
|
||||||
function toFixedPoint(value) {
|
|
||||||
if (typeof value !== "string" && typeof value !== "number") return null;
|
|
||||||
const text = String(value).trim();
|
|
||||||
if (text === "") return null;
|
|
||||||
try {
|
|
||||||
return parseUnits(text, SCALE_DECIMALS);
|
|
||||||
} catch (e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate a pending transfer against the balances that must cover it.
|
|
||||||
//
|
|
||||||
// isErc20 — token transfer rather than a native ETH transfer
|
|
||||||
// amount — human decimal string being sent, non-negative. Anything
|
|
||||||
// else, a negative value included, is an unusable amount
|
|
||||||
// rather than an amount that passes every comparison.
|
|
||||||
// ethBalance — human decimal string, the sender's ETH balance
|
|
||||||
// tokenBalance — human decimal string, the sender's token balance
|
|
||||||
// feeStatus — FEE_PENDING, FEE_KNOWN or FEE_UNAVAILABLE. Anything else
|
|
||||||
// is treated as FEE_UNAVAILABLE.
|
|
||||||
// feeWei — the fee reserve in wei from feeReserveWei(), as a
|
|
||||||
// non-negative bigint, when FEE_KNOWN. Any other value makes
|
|
||||||
// the fee unavailable rather than zero.
|
|
||||||
//
|
|
||||||
// Returns { canSend, codes }. Every code blocks sending: canSend is true
|
|
||||||
// only when nothing was found.
|
|
||||||
function validateTransfer({
|
|
||||||
isErc20 = false,
|
|
||||||
amount,
|
|
||||||
ethBalance,
|
|
||||||
tokenBalance,
|
|
||||||
feeStatus = FEE_PENDING,
|
|
||||||
feeWei = null,
|
|
||||||
} = {}) {
|
|
||||||
const codes = [];
|
|
||||||
|
|
||||||
const amountFp = toFixedPoint(amount);
|
|
||||||
const ethFp = toFixedPoint(ethBalance) ?? 0n;
|
|
||||||
|
|
||||||
// A negative amount parses to a valid bigint, so every comparison below
|
|
||||||
// is trivially false and the send clears the screen — then dies at encode
|
|
||||||
// time in parseEther(). Unusable, on the same footing as a malformed fee.
|
|
||||||
if (amountFp === null || amountFp < 0n) {
|
|
||||||
codes.push(CODES.AMOUNT_INVALID);
|
|
||||||
return { canSend: false, codes };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fail closed. Anything that is not a usable fee under a recognised
|
|
||||||
// status — a malformed feeWei, or a status this module does not know —
|
|
||||||
// is an unavailable estimate, never a fee of zero. Every such input errs
|
|
||||||
// in the direction that lets money out, so none of them is trusted.
|
|
||||||
const known =
|
|
||||||
feeStatus === FEE_KNOWN && typeof feeWei === "bigint" && feeWei >= 0n;
|
|
||||||
let status = feeStatus;
|
|
||||||
if (feeStatus === FEE_KNOWN && !known) status = FEE_UNAVAILABLE;
|
|
||||||
if (status !== FEE_KNOWN && status !== FEE_PENDING) {
|
|
||||||
status = FEE_UNAVAILABLE;
|
|
||||||
}
|
|
||||||
|
|
||||||
const feeFp = known ? feeWei : null;
|
|
||||||
|
|
||||||
if (isErc20) {
|
|
||||||
const tokenFp = toFixedPoint(tokenBalance) ?? 0n;
|
|
||||||
if (amountFp > tokenFp) codes.push(CODES.INSUFFICIENT_TOKEN);
|
|
||||||
if (feeFp !== null && feeFp > ethFp) {
|
|
||||||
codes.push(CODES.INSUFFICIENT_ETH_FOR_FEE);
|
|
||||||
}
|
|
||||||
} else if (amountFp > ethFp) {
|
|
||||||
codes.push(CODES.INSUFFICIENT_ETH);
|
|
||||||
} else if (feeFp !== null && amountFp + feeFp > ethFp) {
|
|
||||||
codes.push(CODES.INSUFFICIENT_ETH_WITH_FEE);
|
|
||||||
}
|
|
||||||
|
|
||||||
// An unknown fee is never assumed to be zero: sending stays blocked
|
|
||||||
// until the estimate arrives, and stays blocked if it never does.
|
|
||||||
if (status === FEE_PENDING) codes.push(CODES.FEE_PENDING);
|
|
||||||
if (status === FEE_UNAVAILABLE) codes.push(CODES.FEE_UNAVAILABLE);
|
|
||||||
|
|
||||||
return { canSend: codes.length === 0, codes };
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
CODES,
|
|
||||||
FEE_PENDING,
|
|
||||||
FEE_KNOWN,
|
|
||||||
FEE_UNAVAILABLE,
|
|
||||||
SCALE_DECIMALS,
|
|
||||||
feeReserveWei,
|
|
||||||
feeEstimateWei,
|
|
||||||
toFixedPoint,
|
|
||||||
validateTransfer,
|
|
||||||
};
|
|
||||||
@@ -16,60 +16,8 @@ function generateMnemonic() {
|
|||||||
return m.phrase;
|
return m.phrase;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every extended key (xprv or xpub) entering the app goes through this.
|
|
||||||
//
|
|
||||||
// ethers' HDNodeWallet.fromExtendedKey does NOT verify the base58 checksum
|
|
||||||
// when the decoded payload is the usual 82 bytes, which is exactly the case
|
|
||||||
// the checksum exists to catch: a key with a one-character typo parses into a
|
|
||||||
// *different* wallet instead of being rejected. Re-encoding the parsed node
|
|
||||||
// reproduces a well-formed key byte for byte, checksum included, so comparing
|
|
||||||
// the round trip against the input rejects any altered character. Measured by
|
|
||||||
// the sweep in tests/wallet.test.js over every single-character substitution
|
|
||||||
// of the BIP-32 vector 1 master key: 199 parse without the round-trip
|
|
||||||
// comparison, 0 with it.
|
|
||||||
//
|
|
||||||
// Returns the parsed node, or null if the key is not a well-formed extended
|
|
||||||
// key. Callers turn null into a user-facing error; none of them may fall back
|
|
||||||
// to fromExtendedKey directly.
|
|
||||||
function parseExtendedKey(key) {
|
|
||||||
if (typeof key !== "string") return null;
|
|
||||||
try {
|
|
||||||
const node = HDNodeWallet.fromExtendedKey(key);
|
|
||||||
return node.extendedKey === key ? node : null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A master key is at depth 0. Only from there is BIP44_ETH_PATH the absolute
|
|
||||||
// path it names; deriving it under an account-level or child key yields
|
|
||||||
// addresses that correspond to nothing the user holds.
|
|
||||||
const MASTER_DEPTH = 0;
|
|
||||||
|
|
||||||
// Parse an extended private key that the BIP-44 Ethereum account path can be
|
|
||||||
// derived from, or throw. Both callers derive BIP44_ETH_PATH from the result.
|
|
||||||
function masterXprvOrThrow(key) {
|
|
||||||
const node = parseExtendedKey(key);
|
|
||||||
if (!node) {
|
|
||||||
throw new Error("Not a valid extended private key (xprv).");
|
|
||||||
}
|
|
||||||
if (!node.privateKey) {
|
|
||||||
throw new Error("Not an extended private key (xprv).");
|
|
||||||
}
|
|
||||||
if (node.depth !== MASTER_DEPTH) {
|
|
||||||
throw new Error(
|
|
||||||
"Not a master extended private key (xprv): an account-level or " +
|
|
||||||
"child key cannot be imported.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
function deriveAddressFromXpub(xpub, index) {
|
function deriveAddressFromXpub(xpub, index) {
|
||||||
const node = parseExtendedKey(xpub);
|
const node = HDNodeWallet.fromExtendedKey(xpub);
|
||||||
if (!node) {
|
|
||||||
throw new Error("Not a valid extended key.");
|
|
||||||
}
|
|
||||||
return node.deriveChild(index).address;
|
return node.deriveChild(index).address;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,28 +29,23 @@ function hdWalletFromMnemonic(mnemonic) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hdWalletFromXprv(xprv) {
|
function hdWalletFromXprv(xprv) {
|
||||||
// BIP44_ETH_PATH is absolute ("m/..."), which ethers will only derive from
|
const root = HDNodeWallet.fromExtendedKey(xprv);
|
||||||
// a depth-0 node. The relative form this used to derive would have been
|
if (!root.privateKey) {
|
||||||
// applied *beneath* an account-level key instead of being refused.
|
throw new Error("Not an extended private key (xprv).");
|
||||||
const node = masterXprvOrThrow(xprv).derivePath(BIP44_ETH_PATH);
|
}
|
||||||
|
const node = root.derivePath("44'/60'/0'/0");
|
||||||
const xpub = node.neuter().extendedKey;
|
const xpub = node.neuter().extendedKey;
|
||||||
const firstAddress = node.deriveChild(0).address;
|
const firstAddress = node.deriveChild(0).address;
|
||||||
return { xpub, firstAddress };
|
return { xpub, firstAddress };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Well-formed extended private key. Says nothing about depth: the import view
|
|
||||||
// reports a non-master key separately, since "check it for a typo" is the
|
|
||||||
// wrong advice for a key the user copied correctly.
|
|
||||||
function isValidXprv(key) {
|
function isValidXprv(key) {
|
||||||
const node = parseExtendedKey(key);
|
try {
|
||||||
return !!(node && node.privateKey);
|
const node = HDNodeWallet.fromExtendedKey(key);
|
||||||
}
|
return !!node.privateKey;
|
||||||
|
} catch {
|
||||||
// Whether an extended key is a master key, i.e. the one BIP44_ETH_PATH can be
|
return false;
|
||||||
// derived from. False for anything parseExtendedKey rejects.
|
}
|
||||||
function isMasterExtendedKey(key) {
|
|
||||||
const node = parseExtendedKey(key);
|
|
||||||
return !!node && node.depth === MASTER_DEPTH;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function addressFromPrivateKey(key) {
|
function addressFromPrivateKey(key) {
|
||||||
@@ -120,8 +63,8 @@ function getSignerForAddress(walletData, addrIndex, decryptedSecret) {
|
|||||||
return node.deriveChild(addrIndex);
|
return node.deriveChild(addrIndex);
|
||||||
}
|
}
|
||||||
if (walletData.type === "xprv") {
|
if (walletData.type === "xprv") {
|
||||||
const node =
|
const root = HDNodeWallet.fromExtendedKey(decryptedSecret);
|
||||||
masterXprvOrThrow(decryptedSecret).derivePath(BIP44_ETH_PATH);
|
const node = root.derivePath("44'/60'/0'/0");
|
||||||
return node.deriveChild(addrIndex);
|
return node.deriveChild(addrIndex);
|
||||||
}
|
}
|
||||||
return new Wallet(decryptedSecret);
|
return new Wallet(decryptedSecret);
|
||||||
@@ -131,24 +74,13 @@ function isValidMnemonic(mnemonic) {
|
|||||||
return Mnemonic.isValidMnemonic(mnemonic);
|
return Mnemonic.isValidMnemonic(mnemonic);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only an HD wallet has a recovery phrase. A "key" wallet holds a bare
|
|
||||||
// private key and an "xprv" wallet an extended private key; neither can be
|
|
||||||
// turned back into words, so neither may ever be offered the phrase display.
|
|
||||||
// Written as an allowlist on purpose: a wallet type added later is excluded
|
|
||||||
// until someone decides otherwise.
|
|
||||||
function walletHasRecoveryPhrase(walletData) {
|
|
||||||
return !!walletData && walletData.type === "hd";
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
generateMnemonic,
|
generateMnemonic,
|
||||||
deriveAddressFromXpub,
|
deriveAddressFromXpub,
|
||||||
hdWalletFromMnemonic,
|
hdWalletFromMnemonic,
|
||||||
hdWalletFromXprv,
|
hdWalletFromXprv,
|
||||||
isValidXprv,
|
isValidXprv,
|
||||||
isMasterExtendedKey,
|
|
||||||
addressFromPrivateKey,
|
addressFromPrivateKey,
|
||||||
getSignerForAddress,
|
getSignerForAddress,
|
||||||
isValidMnemonic,
|
isValidMnemonic,
|
||||||
walletHasRecoveryPhrase,
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,468 +0,0 @@
|
|||||||
// Scheduling for the background context.
|
|
||||||
//
|
|
||||||
// The Chrome MV3 service worker is terminated after roughly 30 seconds idle,
|
|
||||||
// so anything scheduled with setInterval/setTimeout dies with it. These tests
|
|
||||||
// pin the recurring jobs to the alarms API and to the re-registration path a
|
|
||||||
// revived worker runs.
|
|
||||||
|
|
||||||
// A controllable clock plus a stubbed balance refresh, so a cadence test can
|
|
||||||
// measure the interval between refreshes that actually happened rather than
|
|
||||||
// asserting the interval someone intended.
|
|
||||||
let mockNow = 0;
|
|
||||||
const mockBalanceRefreshAt = [];
|
|
||||||
|
|
||||||
// jest.resetModules() clears the call record of every jest.fn, and loading the
|
|
||||||
// worker is exactly that call — so anything that must be counted across a load
|
|
||||||
// is counted here rather than read off a mock.
|
|
||||||
let mockSetIntervalCalls = 0;
|
|
||||||
|
|
||||||
// Extension storage reads do not take a constant amount of time, and that is
|
|
||||||
// what makes a guard timed to the alarm period bite: backgroundRefresh()
|
|
||||||
// stamps its freshness marker after awaiting loadState(), so any read that is
|
|
||||||
// quicker than the previous one puts the next tick inside a guard of exactly
|
|
||||||
// one period and the tick is skipped. A simulation with a constant latency
|
|
||||||
// would sit exactly on the boundary and hide the bug.
|
|
||||||
const MOCK_STORAGE_LATENCIES_MS = [7, 3, 11, 2, 9, 4, 13, 1, 6, 5];
|
|
||||||
const MOCK_MAX_STORAGE_LATENCY_MS = Math.max(...MOCK_STORAGE_LATENCIES_MS);
|
|
||||||
let mockStorageJitter = false;
|
|
||||||
let mockStorageOpCount = 0;
|
|
||||||
|
|
||||||
function mockStorageTick() {
|
|
||||||
if (!mockStorageJitter) return;
|
|
||||||
mockNow +=
|
|
||||||
MOCK_STORAGE_LATENCIES_MS[
|
|
||||||
mockStorageOpCount++ % MOCK_STORAGE_LATENCIES_MS.length
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
jest.mock("../src/shared/balances", () => ({
|
|
||||||
refreshBalances: jest.fn(async () => {
|
|
||||||
mockBalanceRefreshAt.push(Date.now());
|
|
||||||
}),
|
|
||||||
getProvider: jest.fn(() => ({})),
|
|
||||||
}));
|
|
||||||
|
|
||||||
function makeAlarmsStub() {
|
|
||||||
const alarms = new Map();
|
|
||||||
const listeners = [];
|
|
||||||
const stub = {
|
|
||||||
created: [],
|
|
||||||
alarms,
|
|
||||||
create: jest.fn((name, info) => {
|
|
||||||
stub.created.push({ name, info });
|
|
||||||
alarms.set(name, { name, ...info });
|
|
||||||
}),
|
|
||||||
get: jest.fn(async (name) => alarms.get(name)),
|
|
||||||
clear: jest.fn(async (name) => alarms.delete(name)),
|
|
||||||
onAlarm: {
|
|
||||||
addListener: jest.fn((fn) => listeners.push(fn)),
|
|
||||||
},
|
|
||||||
fire: (name) => {
|
|
||||||
for (const fn of listeners) fn({ name });
|
|
||||||
},
|
|
||||||
listenerCount: () => listeners.length,
|
|
||||||
};
|
|
||||||
return stub;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("alarms module", () => {
|
|
||||||
let alarmsStub;
|
|
||||||
let alarmsMod;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.resetModules();
|
|
||||||
alarmsStub = makeAlarmsStub();
|
|
||||||
global.chrome = { alarms: alarmsStub };
|
|
||||||
alarmsMod = require("../src/shared/alarms");
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
delete global.chrome;
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ensureRecurringAlarms schedules both recurring jobs", async () => {
|
|
||||||
const created = await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(created).toEqual({ balance: true, phishing: true });
|
|
||||||
|
|
||||||
const names = alarmsStub.created.map((c) => c.name).sort();
|
|
||||||
expect(names).toEqual(
|
|
||||||
[
|
|
||||||
alarmsMod.BALANCE_REFRESH_ALARM,
|
|
||||||
alarmsMod.PHISHING_REFRESH_ALARM,
|
|
||||||
].sort(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the balance refresh keeps its 60-second cadence", async () => {
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
const balance = alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM);
|
|
||||||
expect(balance.periodInMinutes).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the phishing refresh keeps its 24-hour cadence", async () => {
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
const phishing = alarmsStub.alarms.get(
|
|
||||||
alarmsMod.PHISHING_REFRESH_ALARM,
|
|
||||||
);
|
|
||||||
expect(phishing.periodInMinutes).toBe(24 * 60);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("no period is below the browser-enforced minimum", async () => {
|
|
||||||
// A period under one minute is silently clamped by the browser, so a
|
|
||||||
// request for one would mean the documented cadence is not the real
|
|
||||||
// one. Every period must be a whole minute at or above the minimum.
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
for (const { info } of alarmsStub.created) {
|
|
||||||
expect(info.periodInMinutes).toBeGreaterThanOrEqual(
|
|
||||||
alarmsMod.MIN_ALARM_PERIOD_MINUTES,
|
|
||||||
);
|
|
||||||
expect(Number.isInteger(info.periodInMinutes)).toBe(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a revived worker does not reset an existing alarm's schedule", async () => {
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(alarmsStub.create).toHaveBeenCalledTimes(2);
|
|
||||||
|
|
||||||
// Every wake re-runs the startup path. Re-creating an alarm restarts
|
|
||||||
// its period, so a busy extension would push the next fire out
|
|
||||||
// forever and the job would never run.
|
|
||||||
const again = await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(again).toEqual({ balance: false, phishing: false });
|
|
||||||
expect(alarmsStub.create).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a missing alarm is re-created on the next start", async () => {
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
await alarmsStub.clear(alarmsMod.BALANCE_REFRESH_ALARM);
|
|
||||||
|
|
||||||
const again = await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(again).toEqual({ balance: true, phishing: false });
|
|
||||||
expect(
|
|
||||||
alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM),
|
|
||||||
).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an alarm left over with a stale period is re-created", async () => {
|
|
||||||
// An install carries its alarms across an extension update, so a
|
|
||||||
// period changed in a new release only ever reaches users if the
|
|
||||||
// stale one is reconciled.
|
|
||||||
alarmsStub.create(alarmsMod.PHISHING_REFRESH_ALARM, {
|
|
||||||
periodInMinutes: 7 * 24 * 60,
|
|
||||||
});
|
|
||||||
alarmsStub.create.mockClear();
|
|
||||||
|
|
||||||
const created = await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(created.phishing).toBe(true);
|
|
||||||
expect(
|
|
||||||
alarmsStub.alarms.get(alarmsMod.PHISHING_REFRESH_ALARM)
|
|
||||||
.periodInMinutes,
|
|
||||||
).toBe(alarmsMod.PHISHING_REFRESH_PERIOD_MINUTES);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("reconciling a period settles instead of re-creating forever", async () => {
|
|
||||||
alarmsStub.create(alarmsMod.BALANCE_REFRESH_ALARM, {
|
|
||||||
periodInMinutes: 30,
|
|
||||||
});
|
|
||||||
await alarmsMod.ensureRecurringAlarms();
|
|
||||||
alarmsStub.create.mockClear();
|
|
||||||
|
|
||||||
const again = await alarmsMod.ensureRecurringAlarms();
|
|
||||||
expect(again).toEqual({ balance: false, phishing: false });
|
|
||||||
expect(alarmsStub.create).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("handlers are dispatched by alarm name from one listener", () => {
|
|
||||||
const balance = jest.fn();
|
|
||||||
const phishing = jest.fn();
|
|
||||||
expect(
|
|
||||||
alarmsMod.registerAlarmHandlers({
|
|
||||||
[alarmsMod.BALANCE_REFRESH_ALARM]: balance,
|
|
||||||
[alarmsMod.PHISHING_REFRESH_ALARM]: phishing,
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
expect(alarmsStub.listenerCount()).toBe(1);
|
|
||||||
|
|
||||||
alarmsStub.fire(alarmsMod.BALANCE_REFRESH_ALARM);
|
|
||||||
expect(balance).toHaveBeenCalledTimes(1);
|
|
||||||
expect(phishing).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
alarmsStub.fire(alarmsMod.PHISHING_REFRESH_ALARM);
|
|
||||||
expect(phishing).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
alarmsStub.fire("some-other-extension-alarm");
|
|
||||||
expect(balance).toHaveBeenCalledTimes(1);
|
|
||||||
expect(phishing).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Firefox MV2 gets the same treatment via browser.alarms", async () => {
|
|
||||||
// Both targets are built from one bundle. MV2 has a persistent
|
|
||||||
// background page, but it takes the alarm path too, so the schedule
|
|
||||||
// is the same code on both browsers.
|
|
||||||
jest.resetModules();
|
|
||||||
const firefoxAlarms = makeAlarmsStub();
|
|
||||||
global.browser = { alarms: firefoxAlarms };
|
|
||||||
try {
|
|
||||||
const mod = require("../src/shared/alarms");
|
|
||||||
const created = await mod.ensureRecurringAlarms();
|
|
||||||
expect(created).toEqual({ balance: true, phishing: true });
|
|
||||||
expect(firefoxAlarms.created).toHaveLength(2);
|
|
||||||
// The Chrome stub must not have been touched.
|
|
||||||
expect(alarmsStub.create).not.toHaveBeenCalled();
|
|
||||||
} finally {
|
|
||||||
delete global.browser;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a context without the alarms API degrades instead of throwing", async () => {
|
|
||||||
jest.resetModules();
|
|
||||||
delete global.chrome;
|
|
||||||
const mod = require("../src/shared/alarms");
|
|
||||||
await expect(mod.ensureRecurringAlarms()).resolves.toEqual({
|
|
||||||
balance: false,
|
|
||||||
phishing: false,
|
|
||||||
});
|
|
||||||
expect(mod.registerAlarmHandlers({})).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Loads the background worker against stubbed browser APIs. The returned
|
|
||||||
// store is the extension storage the worker sees, so a test can seed wallet
|
|
||||||
// state and read back what the worker persisted.
|
|
||||||
function loadBackground(initialStore = {}) {
|
|
||||||
const storageStore = initialStore;
|
|
||||||
const alarmsStub = makeAlarmsStub();
|
|
||||||
const listeners = { onInstalled: [], onStartup: [] };
|
|
||||||
global.chrome = {
|
|
||||||
alarms: alarmsStub,
|
|
||||||
storage: {
|
|
||||||
local: {
|
|
||||||
get: async (key) => {
|
|
||||||
mockStorageTick();
|
|
||||||
return Object.prototype.hasOwnProperty.call(
|
|
||||||
storageStore,
|
|
||||||
key,
|
|
||||||
)
|
|
||||||
? { [key]: storageStore[key] }
|
|
||||||
: {};
|
|
||||||
},
|
|
||||||
set: async (items) => {
|
|
||||||
mockStorageTick();
|
|
||||||
Object.assign(storageStore, items);
|
|
||||||
},
|
|
||||||
remove: async (key) => {
|
|
||||||
delete storageStore[key];
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
runtime: {
|
|
||||||
onMessage: { addListener: jest.fn() },
|
|
||||||
onConnect: { addListener: jest.fn() },
|
|
||||||
onInstalled: {
|
|
||||||
addListener: jest.fn((fn) => listeners.onInstalled.push(fn)),
|
|
||||||
},
|
|
||||||
onStartup: {
|
|
||||||
addListener: jest.fn((fn) => listeners.onStartup.push(fn)),
|
|
||||||
},
|
|
||||||
getURL: (p) => "chrome-extension://test/" + p,
|
|
||||||
lastError: null,
|
|
||||||
},
|
|
||||||
windows: {
|
|
||||||
onRemoved: { addListener: jest.fn() },
|
|
||||||
create: jest.fn(),
|
|
||||||
},
|
|
||||||
tabs: { query: jest.fn(), sendMessage: jest.fn() },
|
|
||||||
action: { setPopup: jest.fn() },
|
|
||||||
};
|
|
||||||
global.fetch = jest.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
json: async () => ({ blacklist: [] }),
|
|
||||||
}));
|
|
||||||
jest.resetModules();
|
|
||||||
require("../src/background/index");
|
|
||||||
return { alarmsStub, listeners, store: storageStore };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush the promise chains the startup path and the alarm handlers run on.
|
|
||||||
async function settle() {
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("background worker scheduling", () => {
|
|
||||||
let alarmsStub;
|
|
||||||
let timers;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockSetIntervalCalls = 0;
|
|
||||||
timers = {
|
|
||||||
setInterval: jest
|
|
||||||
.spyOn(global, "setInterval")
|
|
||||||
.mockImplementation(() => {
|
|
||||||
mockSetIntervalCalls++;
|
|
||||||
return 0;
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
timers.setInterval.mockRestore();
|
|
||||||
delete global.chrome;
|
|
||||||
delete global.fetch;
|
|
||||||
jest.resetModules();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("startup schedules the recurring jobs as alarms, not timers", async () => {
|
|
||||||
alarmsStub = loadBackground().alarmsStub;
|
|
||||||
// Let the startup path's promises settle.
|
|
||||||
await settle();
|
|
||||||
|
|
||||||
const names = alarmsStub.created.map((c) => c.name).sort();
|
|
||||||
const {
|
|
||||||
BALANCE_REFRESH_ALARM,
|
|
||||||
PHISHING_REFRESH_ALARM,
|
|
||||||
} = require("../src/shared/alarms");
|
|
||||||
expect(names).toEqual(
|
|
||||||
[BALANCE_REFRESH_ALARM, PHISHING_REFRESH_ALARM].sort(),
|
|
||||||
);
|
|
||||||
expect(mockSetIntervalCalls).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an onAlarm listener is installed on startup", async () => {
|
|
||||||
alarmsStub = loadBackground().alarmsStub;
|
|
||||||
await settle();
|
|
||||||
expect(alarmsStub.listenerCount()).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("onInstalled and onStartup both re-establish the schedule", async () => {
|
|
||||||
const loaded = loadBackground();
|
|
||||||
alarmsStub = loaded.alarmsStub;
|
|
||||||
await settle();
|
|
||||||
|
|
||||||
expect(loaded.listeners.onInstalled).toHaveLength(1);
|
|
||||||
expect(loaded.listeners.onStartup).toHaveLength(1);
|
|
||||||
|
|
||||||
// A browser start after the alarms were dropped must put them back.
|
|
||||||
alarmsStub.alarms.clear();
|
|
||||||
alarmsStub.created.length = 0;
|
|
||||||
loaded.listeners.onStartup[0]();
|
|
||||||
await settle();
|
|
||||||
expect(alarmsStub.created).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the install-time listener and the top-level call share one run", async () => {
|
|
||||||
// On a fresh install both fire, close enough that both could observe
|
|
||||||
// an alarm missing and create it — and a second create restarts the
|
|
||||||
// period the first one just set.
|
|
||||||
const loaded = loadBackground();
|
|
||||||
alarmsStub = loaded.alarmsStub;
|
|
||||||
loaded.listeners.onInstalled[0]();
|
|
||||||
await settle();
|
|
||||||
|
|
||||||
expect(alarmsStub.created).toHaveLength(2);
|
|
||||||
expect(alarmsStub.created.map((c) => c.name).sort()).toEqual(
|
|
||||||
[
|
|
||||||
"autistmask-balance-refresh",
|
|
||||||
"autistmask-phishing-refresh",
|
|
||||||
].sort(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// The alarm period alone must set the cadence. A freshness guard timed to the
|
|
||||||
// period vetoes the very tick it gates, because the guard is measured from
|
|
||||||
// when the last run finished and the alarm fires one run-duration before that.
|
|
||||||
// These tests measure the interval between refreshes that actually ran.
|
|
||||||
describe("balance refresh steady-state cadence", () => {
|
|
||||||
const {
|
|
||||||
BALANCE_REFRESH_PERIOD_MINUTES,
|
|
||||||
BALANCE_REFRESH_ALARM,
|
|
||||||
} = require("../src/shared/alarms");
|
|
||||||
const PERIOD_MS = BALANCE_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
|
||||||
|
|
||||||
let clockSpy;
|
|
||||||
let timerSpy;
|
|
||||||
|
|
||||||
function seededStore() {
|
|
||||||
return {
|
|
||||||
autistmask: {
|
|
||||||
hasWallet: true,
|
|
||||||
wallets: [
|
|
||||||
{ address: "0x0000000000000000000000000000000000000001" },
|
|
||||||
],
|
|
||||||
lastBalanceRefresh: 0,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockNow = Date.UTC(2026, 0, 1, 0, 0, 0);
|
|
||||||
mockBalanceRefreshAt.length = 0;
|
|
||||||
mockSetIntervalCalls = 0;
|
|
||||||
mockStorageOpCount = 0;
|
|
||||||
mockStorageJitter = false;
|
|
||||||
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => mockNow);
|
|
||||||
timerSpy = jest.spyOn(global, "setInterval").mockImplementation(() => {
|
|
||||||
mockSetIntervalCalls++;
|
|
||||||
return 0;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
mockStorageJitter = false;
|
|
||||||
clockSpy.mockRestore();
|
|
||||||
timerSpy.mockRestore();
|
|
||||||
delete global.chrome;
|
|
||||||
delete global.fetch;
|
|
||||||
jest.resetModules();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ten alarm ticks produce ten refreshes, one per period", async () => {
|
|
||||||
const { alarmsStub } = loadBackground(seededStore());
|
|
||||||
await settle();
|
|
||||||
mockStorageJitter = true;
|
|
||||||
|
|
||||||
const TICKS = 10;
|
|
||||||
let tickAt = mockNow + PERIOD_MS;
|
|
||||||
for (let i = 0; i < TICKS; i++) {
|
|
||||||
mockNow = tickAt;
|
|
||||||
tickAt += PERIOD_MS;
|
|
||||||
alarmsStub.fire(BALANCE_REFRESH_ALARM);
|
|
||||||
await settle();
|
|
||||||
}
|
|
||||||
|
|
||||||
// No tick was a no-op. This is the assertion that fails when the guard
|
|
||||||
// is timed to the alarm period.
|
|
||||||
expect(mockBalanceRefreshAt).toHaveLength(TICKS);
|
|
||||||
|
|
||||||
// And the observed cadence is one period, not two.
|
|
||||||
const intervals = mockBalanceRefreshAt
|
|
||||||
.slice(1)
|
|
||||||
.map((t, i) => t - mockBalanceRefreshAt[i]);
|
|
||||||
for (const interval of intervals) {
|
|
||||||
expect(interval).toBeGreaterThanOrEqual(
|
|
||||||
PERIOD_MS - MOCK_MAX_STORAGE_LATENCY_MS,
|
|
||||||
);
|
|
||||||
expect(interval).toBeLessThanOrEqual(
|
|
||||||
PERIOD_MS + MOCK_MAX_STORAGE_LATENCY_MS,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a refresh an open popup just did still suppresses the tick", async () => {
|
|
||||||
// The guard's actual job, and the reason it is shortened rather than
|
|
||||||
// removed: while the popup is open it refreshes every 10 seconds and
|
|
||||||
// stamps the same field, and the background job has nothing to add.
|
|
||||||
const store = seededStore();
|
|
||||||
const { alarmsStub } = loadBackground(store);
|
|
||||||
await settle();
|
|
||||||
|
|
||||||
mockNow += PERIOD_MS;
|
|
||||||
store.autistmask.lastBalanceRefresh = mockNow - 10 * 1000;
|
|
||||||
alarmsStub.fire(BALANCE_REFRESH_ALARM);
|
|
||||||
await settle();
|
|
||||||
|
|
||||||
expect(mockBalanceRefreshAt).toHaveLength(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -255,11 +255,6 @@ async function openPopup(ctx, popupUrl) {
|
|||||||
|
|
||||||
// Full wallet creation through the real UI: BIP-39 generation, libsodium
|
// Full wallet creation through the real UI: BIP-39 generation, libsodium
|
||||||
// vault encryption and extension storage persistence, for real.
|
// vault encryption and extension storage persistence, for real.
|
||||||
//
|
|
||||||
// Returns the recovery phrase it generated. Tests that assert on a secret
|
|
||||||
// need the real value — checking for "some 12 words" would pass against the
|
|
||||||
// wrong wallet's phrase, and checking for nothing at all would pass against
|
|
||||||
// a screen that shows the phrase it was supposed to hide.
|
|
||||||
async function createWallet(page) {
|
async function createWallet(page) {
|
||||||
await page.click("#btn-welcome-add");
|
await page.click("#btn-welcome-add");
|
||||||
await visible(page, "#view-add-wallet");
|
await visible(page, "#view-add-wallet");
|
||||||
@@ -268,12 +263,10 @@ async function createWallet(page) {
|
|||||||
const el = document.getElementById("wallet-mnemonic");
|
const el = document.getElementById("wallet-mnemonic");
|
||||||
return el && el.value.trim().split(/\s+/).length >= 12;
|
return el && el.value.trim().split(/\s+/).length >= 12;
|
||||||
});
|
});
|
||||||
const phrase = (await page.inputValue("#wallet-mnemonic")).trim();
|
|
||||||
await page.fill("#add-wallet-password", PASSWORD);
|
await page.fill("#add-wallet-password", PASSWORD);
|
||||||
await page.fill("#add-wallet-password-confirm", PASSWORD);
|
await page.fill("#add-wallet-password-confirm", PASSWORD);
|
||||||
await page.click("#btn-add-wallet-confirm");
|
await page.click("#btn-add-wallet-confirm");
|
||||||
await visible(page, "#view-main", 60000);
|
await visible(page, "#view-main", 60000);
|
||||||
return phrase;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reach the address detail screen from wherever the popup restored to.
|
// Reach the address detail screen from wherever the popup restored to.
|
||||||
@@ -288,7 +281,6 @@ async function openAddressDetail(page) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
PASSWORD,
|
|
||||||
createWallet,
|
createWallet,
|
||||||
launch,
|
launch,
|
||||||
openAddressDetail,
|
openAddressDetail,
|
||||||
|
|||||||
264
tests/e2e/run.js
264
tests/e2e/run.js
@@ -10,7 +10,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const {
|
const {
|
||||||
PASSWORD,
|
|
||||||
createWallet,
|
createWallet,
|
||||||
launch,
|
launch,
|
||||||
openAddressDetail,
|
openAddressDetail,
|
||||||
@@ -35,10 +34,6 @@ function assert(cond, message) {
|
|||||||
if (!cond) throw new Error(message);
|
if (!cond) throw new Error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
function sleep(ms) {
|
|
||||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
|
|
||||||
function withTimeout(promise, name) {
|
function withTimeout(promise, name) {
|
||||||
let timer;
|
let timer;
|
||||||
const timeout = new Promise((_, reject) => {
|
const timeout = new Promise((_, reject) => {
|
||||||
@@ -61,11 +56,7 @@ test("popup loads and reaches the welcome view", async (env) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("wallet creation through the UI reaches the main view", async (env) => {
|
test("wallet creation through the UI reaches the main view", async (env) => {
|
||||||
env.phrase = await createWallet(env.page);
|
await createWallet(env.page);
|
||||||
assert(
|
|
||||||
env.phrase.split(/\s+/).length >= 12,
|
|
||||||
"wallet creation did not yield a recovery phrase",
|
|
||||||
);
|
|
||||||
const addrCount = await env.page
|
const addrCount = await env.page
|
||||||
.locator("#wallet-list .btn-addr-info")
|
.locator("#wallet-list .btn-addr-info")
|
||||||
.count();
|
.count();
|
||||||
@@ -126,256 +117,6 @@ test("transaction detail renders an ERC-20 transfer (#151)", async (env) => {
|
|||||||
assert(dots > 0, "token contract row rendered without its colour dot");
|
assert(dots > 0, "token contract row rendered without its colour dot");
|
||||||
});
|
});
|
||||||
|
|
||||||
// -------------------------------------------- recovery phrase (#161)
|
|
||||||
|
|
||||||
// The gear toggles, so pressing it while Settings is already up leaves it.
|
|
||||||
async function openSettings(page) {
|
|
||||||
if (!(await page.isVisible("#view-settings"))) {
|
|
||||||
await page.click("#btn-settings");
|
|
||||||
}
|
|
||||||
await visible(page, "#view-settings");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Everything the recovery phrase screen is holding, read straight out of
|
|
||||||
// the DOM whether or not that screen is the one on top. Reading it while it
|
|
||||||
// is hidden is the point: "cleared on leave" means the node is empty, not
|
|
||||||
// merely off-screen.
|
|
||||||
async function phraseScreenState(page) {
|
|
||||||
return page.evaluate(() => ({
|
|
||||||
value: document.getElementById("show-phrase-value").textContent,
|
|
||||||
error: document.getElementById("show-phrase-flash").textContent,
|
|
||||||
html: document.getElementById("view-show-phrase").innerHTML,
|
|
||||||
resultHidden: document
|
|
||||||
.getElementById("show-phrase-result")
|
|
||||||
.classList.contains("hidden"),
|
|
||||||
viewHidden: document
|
|
||||||
.getElementById("view-show-phrase")
|
|
||||||
.classList.contains("hidden"),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openPhraseScreen(page) {
|
|
||||||
await openSettings(page);
|
|
||||||
await page.click("#settings-wallet-list .btn-show-phrase");
|
|
||||||
await visible(page, "#view-show-phrase");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function revealPhrase(page) {
|
|
||||||
await page.fill("#show-phrase-password", PASSWORD);
|
|
||||||
await page.click("#btn-show-phrase-reveal");
|
|
||||||
await visible(page, "#show-phrase-result", 60000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertWiped(st, phrase, where) {
|
|
||||||
assert(st.value === "", "phrase still in the DOM " + where);
|
|
||||||
assert(st.resultHidden, "result section still shown " + where);
|
|
||||||
assert(
|
|
||||||
!st.html.includes(phrase),
|
|
||||||
"the recovery phrase is still somewhere in the screen markup " + where,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
test("only an HD wallet is offered the recovery phrase action (#161)", async (env) => {
|
|
||||||
await openSettings(env.page);
|
|
||||||
const offered = await env.page
|
|
||||||
.locator("#settings-wallet-list .btn-show-phrase")
|
|
||||||
.count();
|
|
||||||
const wallets = await env.page
|
|
||||||
.locator("#settings-wallet-list .btn-delete-wallet")
|
|
||||||
.count();
|
|
||||||
assert(wallets === 1, "expected exactly one wallet row, got " + wallets);
|
|
||||||
assert(
|
|
||||||
offered === 1,
|
|
||||||
"the HD wallet was not offered the recovery phrase action",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// The other half of the gate, against the real UI: a wallet holding a bare
|
|
||||||
// private key has no phrase to show, so no row of it may offer the action.
|
|
||||||
// The key is generated here rather than committed — the repo holds no
|
|
||||||
// private keys, test ones included.
|
|
||||||
test("a key wallet is not offered the recovery phrase action (#161)", async (env) => {
|
|
||||||
const { Wallet } = require("ethers");
|
|
||||||
|
|
||||||
await openSettings(env.page);
|
|
||||||
await env.page.click("#btn-main-add-wallet");
|
|
||||||
await visible(env.page, "#view-add-wallet");
|
|
||||||
await env.page.click("#tab-privkey");
|
|
||||||
await env.page.fill(
|
|
||||||
"#import-private-key",
|
|
||||||
Wallet.createRandom().privateKey,
|
|
||||||
);
|
|
||||||
await env.page.fill("#add-wallet-password", PASSWORD);
|
|
||||||
await env.page.fill("#add-wallet-password-confirm", PASSWORD);
|
|
||||||
await env.page.click("#btn-add-wallet-confirm");
|
|
||||||
await visible(env.page, "#view-main", 60000);
|
|
||||||
|
|
||||||
await openSettings(env.page);
|
|
||||||
const wallets = await env.page
|
|
||||||
.locator("#settings-wallet-list .btn-delete-wallet")
|
|
||||||
.count();
|
|
||||||
const offered = await env.page
|
|
||||||
.locator("#settings-wallet-list .btn-show-phrase")
|
|
||||||
.count();
|
|
||||||
assert(wallets === 2, "expected two wallet rows, got " + wallets);
|
|
||||||
assert(
|
|
||||||
offered === 1,
|
|
||||||
"the key wallet was offered the recovery phrase action",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the recovery phrase screen holds nothing before the password (#161)", async (env) => {
|
|
||||||
await openPhraseScreen(env.page);
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assertWiped(st, env.phrase, "before any password was entered");
|
|
||||||
const passwordShown = await env.page.isVisible(
|
|
||||||
"#show-phrase-password-section",
|
|
||||||
);
|
|
||||||
assert(passwordShown, "the password prompt is not shown");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a wrong password reveals nothing (#161)", async (env) => {
|
|
||||||
await env.page.fill("#show-phrase-password", "not-the-password");
|
|
||||||
await env.page.click("#btn-show-phrase-reveal");
|
|
||||||
await env.page.waitForFunction(
|
|
||||||
() =>
|
|
||||||
document.getElementById("show-phrase-flash").textContent.length > 0,
|
|
||||||
null,
|
|
||||||
{ timeout: 60000 },
|
|
||||||
);
|
|
||||||
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assertWiped(st, env.phrase, "after a wrong password");
|
|
||||||
assert(
|
|
||||||
/^[A-Z].*\.$/.test(st.error.trim()),
|
|
||||||
"the wrong-password error is not a full sentence: " +
|
|
||||||
JSON.stringify(st.error),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the correct password reveals the full phrase, and nothing logs it (#161)", async (env) => {
|
|
||||||
const console_ = [];
|
|
||||||
const listener = (msg) => console_.push(msg.text());
|
|
||||||
env.page.on("console", listener);
|
|
||||||
try {
|
|
||||||
await revealPhrase(env.page);
|
|
||||||
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assert(
|
|
||||||
st.value === env.phrase,
|
|
||||||
"the displayed phrase is not the wallet's phrase, verbatim",
|
|
||||||
);
|
|
||||||
const promptShown = await env.page.isVisible(
|
|
||||||
"#show-phrase-password-section",
|
|
||||||
);
|
|
||||||
assert(!promptShown, "the password prompt is still shown after unlock");
|
|
||||||
|
|
||||||
// Full Identifiers Policy: shown whole, and copyable.
|
|
||||||
const title = await env.page.getAttribute(
|
|
||||||
"#show-phrase-value",
|
|
||||||
"title",
|
|
||||||
);
|
|
||||||
assert(title === "Click to copy", "the phrase is not click-to-copy");
|
|
||||||
|
|
||||||
const leaked = console_.filter((line) => line.includes(env.phrase));
|
|
||||||
assert(
|
|
||||||
leaked.length === 0,
|
|
||||||
"the recovery phrase reached the console: " +
|
|
||||||
JSON.stringify(leaked),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
env.page.off("console", listener);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('"Back" wipes the revealed phrase (#161)', async (env) => {
|
|
||||||
await env.page.click("#btn-show-phrase-back");
|
|
||||||
await visible(env.page, "#view-settings");
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assert(st.viewHidden, "the recovery phrase screen is still on top");
|
|
||||||
assertWiped(st, env.phrase, "after Back");
|
|
||||||
});
|
|
||||||
|
|
||||||
// The settings gear leaves the screen without touching its Back button. A
|
|
||||||
// clear wired only to Back would pass the test above and leak here.
|
|
||||||
test("leaving by the settings gear wipes it too (#161)", async (env) => {
|
|
||||||
await openPhraseScreen(env.page);
|
|
||||||
await revealPhrase(env.page);
|
|
||||||
await env.page.click("#btn-settings");
|
|
||||||
await visible(env.page, "#view-settings");
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assertWiped(st, env.phrase, "after leaving via the settings gear");
|
|
||||||
});
|
|
||||||
|
|
||||||
// The same leave, but taken while the decrypt is still running. Both
|
|
||||||
// clicks are dispatched inside one page task on purpose: "Reveal" runs its
|
|
||||||
// handler up to the await, the gear then runs the leave — and the wipe with
|
|
||||||
// it — to completion, and the decrypt's continuation resumes afterwards.
|
|
||||||
// Without a liveness check that continuation writes the phrase into the
|
|
||||||
// hidden screen after the wipe, and nothing is left to wipe it again.
|
|
||||||
//
|
|
||||||
// A human cannot produce this interleaving by hand once libsodium's wasm is
|
|
||||||
// warm, because crypto_pwhash is synchronous and the only suspension point
|
|
||||||
// is a microtask; the window a user can actually hit is a still-pending
|
|
||||||
// sodium.ready on the first vault use of a page load. Forcing it here is
|
|
||||||
// the only way to test the guard deterministically.
|
|
||||||
test("leaving while the decrypt is in flight reveals nothing (#161)", async (env) => {
|
|
||||||
await openPhraseScreen(env.page);
|
|
||||||
await env.page.fill("#show-phrase-password", PASSWORD);
|
|
||||||
await env.page.evaluate(() => {
|
|
||||||
document.getElementById("btn-show-phrase-reveal").click();
|
|
||||||
document.getElementById("btn-settings").click();
|
|
||||||
});
|
|
||||||
await visible(env.page, "#view-settings");
|
|
||||||
|
|
||||||
// The Reveal button is disabled for exactly the duration of the
|
|
||||||
// decrypt and re-enabled in the same continuation that would have
|
|
||||||
// written the phrase, so waiting for it to come back is a precise
|
|
||||||
// "the decrypt has settled and its handler has finished" signal
|
|
||||||
// rather than a guess at a duration.
|
|
||||||
await env.page.waitForFunction(
|
|
||||||
() => !document.getElementById("btn-show-phrase-reveal").disabled,
|
|
||||||
null,
|
|
||||||
{ timeout: 60000 },
|
|
||||||
);
|
|
||||||
await sleep(2000);
|
|
||||||
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
// Printed on every run, pass or fail: "the phrase is not there" is
|
|
||||||
// worth more as a measurement than as a silent assertion, and the
|
|
||||||
// same line read from a build without the guard is what this test
|
|
||||||
// exists to prevent.
|
|
||||||
console.log(
|
|
||||||
"# probe: len=" +
|
|
||||||
st.value.length +
|
|
||||||
" equalsPhrase=" +
|
|
||||||
(st.value === env.phrase) +
|
|
||||||
" resultHidden=" +
|
|
||||||
st.resultHidden +
|
|
||||||
" viewHidden=" +
|
|
||||||
st.viewHidden,
|
|
||||||
);
|
|
||||||
assert(st.viewHidden, "the recovery phrase screen is still on top");
|
|
||||||
assertWiped(st, env.phrase, "after leaving mid-decrypt");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Closing and reopening the page rather than reloading it: that is what
|
|
||||||
// the toolbar popup actually does, and the persisted currentView is
|
|
||||||
// "show-phrase" at the moment it happens, which is precisely the state
|
|
||||||
// RESTORABLE_VIEWS has to refuse.
|
|
||||||
test("reopening the popup never lands on the phrase screen (#161)", async (env) => {
|
|
||||||
await openPhraseScreen(env.page);
|
|
||||||
await revealPhrase(env.page);
|
|
||||||
|
|
||||||
await env.page.close();
|
|
||||||
env.page = await openPopup(env.ctx, env.popupUrl);
|
|
||||||
await visible(env.page, "#view-main");
|
|
||||||
|
|
||||||
const st = await phraseScreenState(env.page);
|
|
||||||
assert(st.viewHidden, "the popup reopened onto the recovery phrase screen");
|
|
||||||
assertWiped(st, env.phrase, "after reopening the popup");
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- runner
|
// ---------------------------------------------------------------- runner
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
@@ -413,9 +154,6 @@ async function main() {
|
|||||||
popupUrl: session.popupUrl,
|
popupUrl: session.popupUrl,
|
||||||
routeOpts,
|
routeOpts,
|
||||||
page: null,
|
page: null,
|
||||||
// The recovery phrase of the wallet created in test 2, so later
|
|
||||||
// tests can assert on the real secret rather than its shape.
|
|
||||||
phrase: null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Attribution of collected errors is total. session.errors has no
|
// Attribution of collected errors is total. session.errors has no
|
||||||
|
|||||||
@@ -1,24 +1,17 @@
|
|||||||
// Extension storage stub for the Node test environment. The module resolves
|
// Provide a localStorage mock for Node.js test environment.
|
||||||
// the storage API on use, so this only has to exist before the first call.
|
// Must be set before requiring the module since it calls loadDeltaFromStorage()
|
||||||
// Values round-trip through JSON the way structured cloning would, so a test
|
// at module load time.
|
||||||
// cannot pass by holding a live reference to the module's own array.
|
const localStorageStore = {};
|
||||||
const storageStore = {};
|
global.localStorage = {
|
||||||
global.chrome = {
|
getItem: (key) =>
|
||||||
storage: {
|
Object.prototype.hasOwnProperty.call(localStorageStore, key)
|
||||||
local: {
|
? localStorageStore[key]
|
||||||
get: async (key) =>
|
: null,
|
||||||
Object.prototype.hasOwnProperty.call(storageStore, key)
|
setItem: (key, value) => {
|
||||||
? { [key]: JSON.parse(JSON.stringify(storageStore[key])) }
|
localStorageStore[key] = String(value);
|
||||||
: {},
|
},
|
||||||
set: async (items) => {
|
removeItem: (key) => {
|
||||||
for (const [key, value] of Object.entries(items)) {
|
delete localStorageStore[key];
|
||||||
storageStore[key] = JSON.parse(JSON.stringify(value));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
remove: async (key) => {
|
|
||||||
delete storageStore[key];
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -28,32 +21,19 @@ const {
|
|||||||
getBlocklistSize,
|
getBlocklistSize,
|
||||||
getDeltaSize,
|
getDeltaSize,
|
||||||
hostnameVariants,
|
hostnameVariants,
|
||||||
DELTA_STORAGE_KEY,
|
|
||||||
_reset,
|
_reset,
|
||||||
_getVendoredBlacklistSize,
|
_getVendoredBlacklistSize,
|
||||||
_getDeltaBlacklist,
|
_getDeltaBlacklist,
|
||||||
} = require("../src/shared/phishingDomains");
|
} = require("../src/shared/phishingDomains");
|
||||||
|
|
||||||
function clearStorage() {
|
|
||||||
for (const key of Object.keys(storageStore)) {
|
|
||||||
delete storageStore[key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The MV3 service worker is torn down when idle and re-evaluated on the next
|
|
||||||
// event, which wipes every module-level variable. Re-requiring the module with
|
|
||||||
// the registry reset is exactly that: fresh in-memory state, same extension
|
|
||||||
// storage underneath.
|
|
||||||
function restartWorker() {
|
|
||||||
jest.resetModules();
|
|
||||||
return require("../src/shared/phishingDomains");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset delta state before each test to avoid cross-test contamination.
|
// Reset delta state before each test to avoid cross-test contamination.
|
||||||
// Note: vendored sets are immutable and always present.
|
// Note: vendored sets are immutable and always present.
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
_reset();
|
_reset();
|
||||||
clearStorage();
|
// Clear localStorage mock between tests
|
||||||
|
for (const key of Object.keys(localStorageStore)) {
|
||||||
|
delete localStorageStore[key];
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("phishingDomains", () => {
|
describe("phishingDomains", () => {
|
||||||
@@ -189,34 +169,15 @@ describe("phishingDomains", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("extension storage persistence", () => {
|
describe("localStorage persistence", () => {
|
||||||
test("delta is persisted to extension storage, not localStorage", async () => {
|
test("saveDeltaToStorage persists delta under 256KiB", () => {
|
||||||
await loadConfig({
|
loadConfig({
|
||||||
blacklist: ["persisted-scam-xyz.com"],
|
blacklist: ["persisted-scam-xyz.com"],
|
||||||
});
|
});
|
||||||
const stored = storageStore[DELTA_STORAGE_KEY];
|
const stored = localStorage.getItem("phishing-delta");
|
||||||
expect(stored).toBeDefined();
|
expect(stored).not.toBeNull();
|
||||||
expect(stored.blacklist).toContain("persisted-scam-xyz.com");
|
const data = JSON.parse(stored);
|
||||||
});
|
expect(data.blacklist).toContain("persisted-scam-xyz.com");
|
||||||
|
|
||||||
test("the fetch timestamp is persisted alongside the delta", async () => {
|
|
||||||
const before = Date.now();
|
|
||||||
await loadConfig({ blacklist: ["timestamped-scam-xyz.com"] });
|
|
||||||
const stored = storageStore[DELTA_STORAGE_KEY];
|
|
||||||
expect(typeof stored.lastFetchTime).toBe("number");
|
|
||||||
expect(stored.lastFetchTime).toBeGreaterThanOrEqual(before);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an oversized delta is dropped entirely, timestamp included", async () => {
|
|
||||||
// A record above the 256 KiB cap is not worth keeping; the
|
|
||||||
// timestamp goes with it so the next start re-fetches rather than
|
|
||||||
// claiming freshness for a delta that was never stored.
|
|
||||||
const huge = [];
|
|
||||||
for (let i = 0; i < 20000; i++) {
|
|
||||||
huge.push(`oversize-scam-${i}-xyzxyzxyzxyzxyz.com`);
|
|
||||||
}
|
|
||||||
await loadConfig({ blacklist: huge });
|
|
||||||
expect(storageStore[DELTA_STORAGE_KEY]).toBeUndefined();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("delta is cleared on _reset", () => {
|
test("delta is cleared on _reset", () => {
|
||||||
@@ -242,332 +203,3 @@ describe("phishingDomains", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("phishing list across a service worker restart", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
clearStorage();
|
|
||||||
jest.resetModules();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
delete global.fetch;
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a revived worker restores the persisted delta without re-fetching", async () => {
|
|
||||||
const first = require("../src/shared/phishingDomains");
|
|
||||||
await first.loadConfig({ blacklist: ["restart-scam-xyz.com"] });
|
|
||||||
|
|
||||||
const revived = restartWorker();
|
|
||||||
// Nothing in memory yet — this is a brand new module instance.
|
|
||||||
expect(revived.getDeltaSize()).toBe(0);
|
|
||||||
|
|
||||||
global.fetch = jest.fn();
|
|
||||||
await revived.initPhishingList();
|
|
||||||
|
|
||||||
expect(global.fetch).not.toHaveBeenCalled();
|
|
||||||
expect(revived.getDeltaSize()).toBe(1);
|
|
||||||
expect(revived.isPhishingDomain("restart-scam-xyz.com")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("repeated wakes inside the cache window never re-fetch", async () => {
|
|
||||||
const first = require("../src/shared/phishingDomains");
|
|
||||||
await first.loadConfig({ blacklist: ["no-storm-scam-xyz.com"] });
|
|
||||||
|
|
||||||
global.fetch = jest.fn();
|
|
||||||
for (let i = 0; i < 5; i++) {
|
|
||||||
const revived = restartWorker();
|
|
||||||
await revived.initPhishingList();
|
|
||||||
}
|
|
||||||
expect(global.fetch).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a persisted timestamp older than the TTL causes a fetch on startup", async () => {
|
|
||||||
const first = require("../src/shared/phishingDomains");
|
|
||||||
await first.loadConfig({ blacklist: ["stale-scam-xyz.com"] });
|
|
||||||
|
|
||||||
// Age the persisted record past the 24-hour TTL.
|
|
||||||
storageStore[first.DELTA_STORAGE_KEY].lastFetchTime =
|
|
||||||
Date.now() - first.CACHE_TTL_MS - 1000;
|
|
||||||
|
|
||||||
const revived = restartWorker();
|
|
||||||
global.fetch = jest.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
json: async () => ({ blacklist: ["refreshed-scam-xyz.com"] }),
|
|
||||||
}));
|
|
||||||
await revived.initPhishingList();
|
|
||||||
|
|
||||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
||||||
expect(revived.isPhishingDomain("refreshed-scam-xyz.com")).toBe(true);
|
|
||||||
expect(revived.isPhishingDomain("stale-scam-xyz.com")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a first start with nothing persisted fetches immediately", async () => {
|
|
||||||
const fresh = restartWorker();
|
|
||||||
global.fetch = jest.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
json: async () => ({ blacklist: ["first-run-scam-xyz.com"] }),
|
|
||||||
}));
|
|
||||||
await fresh.initPhishingList();
|
|
||||||
|
|
||||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
||||||
expect(fresh.isPhishingDomain("first-run-scam-xyz.com")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("updatePhishingList honours the persisted timestamp on its own", async () => {
|
|
||||||
// The startup path calls updatePhishingList() directly, so it must
|
|
||||||
// load persisted state itself rather than relying on anything else
|
|
||||||
// having finished first.
|
|
||||||
const first = require("../src/shared/phishingDomains");
|
|
||||||
await first.loadConfig({ blacklist: ["alarm-tick-scam-xyz.com"] });
|
|
||||||
|
|
||||||
const revived = restartWorker();
|
|
||||||
global.fetch = jest.fn();
|
|
||||||
await revived.updatePhishingList();
|
|
||||||
|
|
||||||
expect(global.fetch).not.toHaveBeenCalled();
|
|
||||||
expect(revived.isPhishingDomain("alarm-tick-scam-xyz.com")).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// The alarm period alone must set the cadence. lastFetchTime is stamped when
|
|
||||||
// the fetch completes, so it lands one fetch latency after the alarm that
|
|
||||||
// caused it; a freshness guard timed to the alarm period therefore vetoes
|
|
||||||
// every scheduled tick and halves the real refresh rate. These tests measure
|
|
||||||
// the interval between fetches that actually happened.
|
|
||||||
describe("phishing refresh steady-state cadence", () => {
|
|
||||||
const { PHISHING_REFRESH_PERIOD_MINUTES } = require("../src/shared/alarms");
|
|
||||||
const PERIOD_MS = PHISHING_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
|
||||||
|
|
||||||
let clockSpy;
|
|
||||||
let now;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
clearStorage();
|
|
||||||
jest.resetModules();
|
|
||||||
now = Date.UTC(2026, 0, 1, 0, 0, 0);
|
|
||||||
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => now);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
clockSpy.mockRestore();
|
|
||||||
delete global.fetch;
|
|
||||||
});
|
|
||||||
|
|
||||||
function fetchStub(latencyMs, seen) {
|
|
||||||
return jest.fn(async () => {
|
|
||||||
seen.push(now);
|
|
||||||
// A network fetch takes time, and lastFetchTime is stamped after
|
|
||||||
// it, not when the alarm fired.
|
|
||||||
now += latencyMs;
|
|
||||||
return { ok: true, json: async () => ({ blacklist: [] }) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test("ten alarm ticks produce ten fetches, one per period", async () => {
|
|
||||||
const fetchedAt = [];
|
|
||||||
global.fetch = fetchStub(5000, fetchedAt);
|
|
||||||
|
|
||||||
const startup = require("../src/shared/phishingDomains");
|
|
||||||
const T0 = now;
|
|
||||||
await startup.initPhishingList();
|
|
||||||
expect(fetchedAt).toEqual([T0]);
|
|
||||||
|
|
||||||
const TICKS = 10;
|
|
||||||
let tickAt = T0 + PERIOD_MS;
|
|
||||||
for (let i = 0; i < TICKS; i++) {
|
|
||||||
now = tickAt;
|
|
||||||
tickAt += PERIOD_MS;
|
|
||||||
// The browser wakes a terminated worker to deliver the alarm, so
|
|
||||||
// every tick starts from cold memory and the persisted record.
|
|
||||||
const revived = restartWorker();
|
|
||||||
await revived.refreshPhishingListOnSchedule();
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(fetchedAt).toHaveLength(TICKS + 1);
|
|
||||||
const intervals = fetchedAt.slice(1).map((t, i) => t - fetchedAt[i]);
|
|
||||||
expect(intervals).toEqual(new Array(TICKS).fill(PERIOD_MS));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the scheduled tick fetches whatever the last fetch's latency was", async () => {
|
|
||||||
// The alarm fires one period after the previous alarm, which is
|
|
||||||
// `latency` short of one period since the fetch it caused completed.
|
|
||||||
for (const latency of [200, 1000, 5000]) {
|
|
||||||
clearStorage();
|
|
||||||
jest.resetModules();
|
|
||||||
storageStore[DELTA_STORAGE_KEY] = {
|
|
||||||
blacklist: [],
|
|
||||||
lastFetchTime: now - PERIOD_MS + latency,
|
|
||||||
lastAttemptTime: now - PERIOD_MS,
|
|
||||||
};
|
|
||||||
const mod = require("../src/shared/phishingDomains");
|
|
||||||
const fetchedAt = [];
|
|
||||||
global.fetch = fetchStub(latency, fetchedAt);
|
|
||||||
|
|
||||||
await mod.refreshPhishingListOnSchedule();
|
|
||||||
expect(fetchedAt).toHaveLength(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a worker wake inside the cache window still does not fetch", async () => {
|
|
||||||
// The TTL is not removed, only taken off the scheduled path. Chrome
|
|
||||||
// revives the worker every ~30 seconds and every revival runs the
|
|
||||||
// startup path, so the TTL still has to keep that off the network.
|
|
||||||
storageStore[DELTA_STORAGE_KEY] = {
|
|
||||||
blacklist: [],
|
|
||||||
lastFetchTime: now - PERIOD_MS + 5000,
|
|
||||||
lastAttemptTime: now - PERIOD_MS,
|
|
||||||
};
|
|
||||||
const mod = require("../src/shared/phishingDomains");
|
|
||||||
global.fetch = jest.fn();
|
|
||||||
|
|
||||||
await mod.initPhishingList();
|
|
||||||
expect(global.fetch).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("phishing list timestamps that cannot be trusted", () => {
|
|
||||||
let clockSpy;
|
|
||||||
let now;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
clearStorage();
|
|
||||||
jest.resetModules();
|
|
||||||
now = Date.UTC(2026, 0, 1, 0, 0, 0);
|
|
||||||
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => now);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
clockSpy.mockRestore();
|
|
||||||
delete global.fetch;
|
|
||||||
});
|
|
||||||
|
|
||||||
function okFetch() {
|
|
||||||
return jest.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
json: async () => ({ blacklist: ["recovered-scam-xyz.com"] }),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// jest.resetModules() clears the call record of a jest.fn, and simulating
|
|
||||||
// a worker restart is exactly that call. Anything counted across restarts
|
|
||||||
// has to be counted outside the mock.
|
|
||||||
function countingFetch(counter, response) {
|
|
||||||
return async () => {
|
|
||||||
counter.calls++;
|
|
||||||
return response();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
test("a lastFetchTime in the future is discarded rather than trusted", async () => {
|
|
||||||
// Clock skew or a restored profile backup writes one. Every guard
|
|
||||||
// measures `Date.now() - stamp` and only tests the lower bound, so a
|
|
||||||
// stamp a year ahead would suppress updates for a year, and now that
|
|
||||||
// the value is persisted it would outlive every worker.
|
|
||||||
storageStore[DELTA_STORAGE_KEY] = {
|
|
||||||
blacklist: ["poisoned-scam-xyz.com"],
|
|
||||||
lastFetchTime: now + 365 * 24 * 60 * 60 * 1000,
|
|
||||||
lastAttemptTime: 0,
|
|
||||||
};
|
|
||||||
const mod = require("../src/shared/phishingDomains");
|
|
||||||
global.fetch = okFetch();
|
|
||||||
|
|
||||||
await mod.initPhishingList();
|
|
||||||
|
|
||||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
||||||
expect(mod.isPhishingDomain("recovered-scam-xyz.com")).toBe(true);
|
|
||||||
// And the record it leaves behind is sane, so recovery is permanent.
|
|
||||||
expect(
|
|
||||||
storageStore[DELTA_STORAGE_KEY].lastFetchTime,
|
|
||||||
).toBeLessThanOrEqual(now);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a lastAttemptTime in the future does not suppress the retry", async () => {
|
|
||||||
storageStore[DELTA_STORAGE_KEY] = {
|
|
||||||
lastAttemptTime: now + 365 * 24 * 60 * 60 * 1000,
|
|
||||||
};
|
|
||||||
const mod = require("../src/shared/phishingDomains");
|
|
||||||
global.fetch = okFetch();
|
|
||||||
|
|
||||||
await mod.initPhishingList();
|
|
||||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an oversized delta does not re-download on every worker wake", async () => {
|
|
||||||
// The delta and its freshness claim are both dropped, which is right,
|
|
||||||
// but nothing then says a fetch just happened. Chrome cycles the
|
|
||||||
// worker roughly every 30 seconds idle, so without the attempt stamp
|
|
||||||
// this is a full blocklist download per wake, forever.
|
|
||||||
const huge = [];
|
|
||||||
for (let i = 0; i < 20000; i++) {
|
|
||||||
huge.push(`oversize-scam-${i}-xyzxyzxyzxyzxyz.com`);
|
|
||||||
}
|
|
||||||
const counter = { calls: 0 };
|
|
||||||
global.fetch = countingFetch(counter, () => ({
|
|
||||||
ok: true,
|
|
||||||
json: async () => ({ blacklist: huge }),
|
|
||||||
}));
|
|
||||||
|
|
||||||
for (let wake = 0; wake < 4; wake++) {
|
|
||||||
const revived = restartWorker();
|
|
||||||
await revived.initPhishingList();
|
|
||||||
now += 30 * 1000; // idle timeout, worker torn down and revived
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(counter.calls).toBe(1);
|
|
||||||
expect(storageStore[DELTA_STORAGE_KEY].blacklist).toBeUndefined();
|
|
||||||
expect(typeof storageStore[DELTA_STORAGE_KEY].lastAttemptTime).toBe(
|
|
||||||
"number",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a failing fetch is not retried on every worker wake either", async () => {
|
|
||||||
const counter = { calls: 0 };
|
|
||||||
global.fetch = countingFetch(counter, () => ({
|
|
||||||
ok: false,
|
|
||||||
status: 503,
|
|
||||||
}));
|
|
||||||
|
|
||||||
for (let wake = 0; wake < 4; wake++) {
|
|
||||||
const revived = restartWorker();
|
|
||||||
await revived.initPhishingList();
|
|
||||||
now += 30 * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(counter.calls).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the retry floor expires, so a failure is not permanent", async () => {
|
|
||||||
const {
|
|
||||||
MIN_FETCH_ATTEMPT_INTERVAL_MS,
|
|
||||||
} = require("../src/shared/phishingDomains");
|
|
||||||
const counter = { calls: 0 };
|
|
||||||
global.fetch = countingFetch(counter, () => ({
|
|
||||||
ok: false,
|
|
||||||
status: 503,
|
|
||||||
}));
|
|
||||||
|
|
||||||
await restartWorker().initPhishingList();
|
|
||||||
expect(counter.calls).toBe(1);
|
|
||||||
|
|
||||||
// Still inside the floor: no retry.
|
|
||||||
now += MIN_FETCH_ATTEMPT_INTERVAL_MS - 1000;
|
|
||||||
await restartWorker().initPhishingList();
|
|
||||||
expect(counter.calls).toBe(1);
|
|
||||||
|
|
||||||
// Past it: the extension goes back to the network.
|
|
||||||
now += 2000;
|
|
||||||
await restartWorker().initPhishingList();
|
|
||||||
expect(counter.calls).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the scheduled tick ignores the retry floor", async () => {
|
|
||||||
// The alarm period is far above the floor, but the floor exists to
|
|
||||||
// throttle wakes, not the schedule.
|
|
||||||
storageStore[DELTA_STORAGE_KEY] = { lastAttemptTime: now - 1000 };
|
|
||||||
const mod = require("../src/shared/phishingDomains");
|
|
||||||
global.fetch = okFetch();
|
|
||||||
|
|
||||||
await mod.refreshPhishingListOnSchedule();
|
|
||||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
// Tests for the UTC Timestamps setting.
|
|
||||||
//
|
|
||||||
// The checkbox was moved out of the Token Spam Protection well and into the
|
|
||||||
// Display well next to the theme selector. It is wired by id through the $()
|
|
||||||
// helper, so the move cannot break the handler — but nothing in the suite said
|
|
||||||
// so. These tests pin both halves down: the markup lives in Display and
|
|
||||||
// nowhere else, and the value still round-trips through storage.
|
|
||||||
|
|
||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
|
|
||||||
const POPUP_HTML = fs.readFileSync(
|
|
||||||
path.join(__dirname, "..", "src", "popup", "index.html"),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
|
|
||||||
// The body of one `<div class="bg-well ...">` well, selected by its heading.
|
|
||||||
function wellWithHeading(html, heading) {
|
|
||||||
const headingIndex = html.indexOf(
|
|
||||||
'<h3 class="font-bold mb-1">' + heading + "</h3>",
|
|
||||||
);
|
|
||||||
expect(headingIndex).toBeGreaterThan(-1);
|
|
||||||
const start = html.lastIndexOf('<div class="bg-well', headingIndex);
|
|
||||||
const end = html.indexOf('<div class="bg-well', headingIndex);
|
|
||||||
return html.slice(start, end === -1 ? html.length : end);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("the UTC Timestamps checkbox placement", () => {
|
|
||||||
test("the checkbox appears exactly once in the popup markup", () => {
|
|
||||||
const matches = POPUP_HTML.match(/id="settings-utc-timestamps"/g);
|
|
||||||
expect(matches).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("it renders in the Display well, alongside the theme selector", () => {
|
|
||||||
const display = wellWithHeading(POPUP_HTML, "Display");
|
|
||||||
|
|
||||||
expect(display).toContain('id="settings-utc-timestamps"');
|
|
||||||
expect(display).toContain('id="settings-theme"');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("it does not render in the Token Spam Protection well", () => {
|
|
||||||
const spam = wellWithHeading(POPUP_HTML, "Token Spam Protection");
|
|
||||||
|
|
||||||
expect(spam).not.toContain('id="settings-utc-timestamps"');
|
|
||||||
// The filters that do belong there are untouched.
|
|
||||||
expect(spam).toContain('id="settings-hide-low-holders"');
|
|
||||||
expect(spam).toContain('id="settings-hide-fraud-contracts"');
|
|
||||||
expect(spam).toContain('id="settings-hide-dust"');
|
|
||||||
expect(spam).toContain('id="settings-dust-threshold"');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("the UTC Timestamps setting round-trips through storage", () => {
|
|
||||||
let store;
|
|
||||||
|
|
||||||
function loadStateModule() {
|
|
||||||
store = {};
|
|
||||||
global.chrome = {
|
|
||||||
storage: {
|
|
||||||
local: {
|
|
||||||
get: async (key) =>
|
|
||||||
key in store ? { [key]: store[key] } : {},
|
|
||||||
set: async (obj) => Object.assign(store, obj),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
jest.resetModules();
|
|
||||||
return require("../src/shared/state");
|
|
||||||
}
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
delete global.chrome;
|
|
||||||
});
|
|
||||||
|
|
||||||
test("defaults to off with nothing persisted", async () => {
|
|
||||||
const { state, loadState } = loadStateModule();
|
|
||||||
|
|
||||||
await loadState();
|
|
||||||
|
|
||||||
expect(state.utcTimestamps).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an enabled checkbox is persisted and read back", async () => {
|
|
||||||
const first = loadStateModule();
|
|
||||||
|
|
||||||
// What the change handler in views/settings.js does.
|
|
||||||
first.state.utcTimestamps = true;
|
|
||||||
await first.saveState();
|
|
||||||
expect(store.autistmask.utcTimestamps).toBe(true);
|
|
||||||
|
|
||||||
// A fresh popup load sees it.
|
|
||||||
jest.resetModules();
|
|
||||||
const second = require("../src/shared/state");
|
|
||||||
expect(second.state.utcTimestamps).toBe(false);
|
|
||||||
await second.loadState();
|
|
||||||
expect(second.state.utcTimestamps).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("turning it back off is persisted too", async () => {
|
|
||||||
const { state, saveState, loadState } = loadStateModule();
|
|
||||||
|
|
||||||
state.utcTimestamps = true;
|
|
||||||
await saveState();
|
|
||||||
state.utcTimestamps = false;
|
|
||||||
await saveState();
|
|
||||||
|
|
||||||
state.utcTimestamps = true;
|
|
||||||
await loadState();
|
|
||||||
expect(state.utcTimestamps).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
// Tests for the recovery phrase display (issue #161).
|
|
||||||
//
|
|
||||||
// These cover the parts that do not need a DOM: which wallet types may be
|
|
||||||
// offered the action at all, the exclusion of the screen from the set of
|
|
||||||
// views the popup may reopen onto, and the absence of any path from this
|
|
||||||
// module to the logger. The DOM behaviour it guards — nothing rendered
|
|
||||||
// before the password is accepted, a wrong password revealing nothing, and
|
|
||||||
// the wipe on leaving — is driven against the real popup in a real browser
|
|
||||||
// by tests/e2e/run.js, which is where every other view behaviour is tested.
|
|
||||||
|
|
||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
|
|
||||||
const { walletHasRecoveryPhrase } = require("../src/shared/wallet");
|
|
||||||
const { RESTORABLE_VIEWS } = require("../src/popup/restorableViews");
|
|
||||||
|
|
||||||
const SHOW_PHRASE_VIEW = "show-phrase";
|
|
||||||
|
|
||||||
// helpers.js pulls in state.js, which reads chrome.storage.local at load.
|
|
||||||
function loadHelpers() {
|
|
||||||
globalThis.chrome = {
|
|
||||||
storage: { local: { get: async () => ({}), set: async () => {} } },
|
|
||||||
};
|
|
||||||
return require("../src/popup/views/helpers");
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("which wallets have a recovery phrase", () => {
|
|
||||||
test("an HD wallet does", () => {
|
|
||||||
expect(walletHasRecoveryPhrase({ type: "hd" })).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
// A key wallet holds a bare private key and an xprv wallet an extended
|
|
||||||
// private key. Neither can be turned back into words, so neither may be
|
|
||||||
// offered the action.
|
|
||||||
test("a key wallet does not", () => {
|
|
||||||
expect(walletHasRecoveryPhrase({ type: "key" })).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an xprv wallet does not", () => {
|
|
||||||
expect(walletHasRecoveryPhrase({ type: "xprv" })).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an unknown or missing wallet type does not", () => {
|
|
||||||
expect(walletHasRecoveryPhrase({ type: "something-new" })).toBe(false);
|
|
||||||
expect(walletHasRecoveryPhrase({})).toBe(false);
|
|
||||||
expect(walletHasRecoveryPhrase(undefined)).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("views the popup may reopen onto", () => {
|
|
||||||
// Restoring onto a secret screen would put the phrase on screen with no
|
|
||||||
// password prompt in front of it, on a popup the user may have reopened
|
|
||||||
// by accident.
|
|
||||||
test("the recovery phrase screen is not restorable", () => {
|
|
||||||
expect(RESTORABLE_VIEWS.has(SHOW_PHRASE_VIEW)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the private key export screen is not restorable either", () => {
|
|
||||||
expect(RESTORABLE_VIEWS.has("export-privkey")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the recovery phrase screen is still a registered view", () => {
|
|
||||||
const { VIEWS } = loadHelpers();
|
|
||||||
expect(VIEWS).toContain(SHOW_PHRASE_VIEW);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Guards the other direction: a restorable name that is not a real view
|
|
||||||
// would leave restoreView() showing nothing at all.
|
|
||||||
test("every restorable view is a registered view", () => {
|
|
||||||
const { VIEWS } = loadHelpers();
|
|
||||||
for (const view of RESTORABLE_VIEWS) {
|
|
||||||
expect(VIEWS).toContain(view);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("the phrase cannot reach the logger", () => {
|
|
||||||
const source = fs.readFileSync(
|
|
||||||
path.join(__dirname, "..", "src", "popup", "views", "showPhrase.js"),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
|
|
||||||
// The decrypted phrase only ever lives in a local and in the DOM node
|
|
||||||
// that displays it. The module has no logger to hand it to, and this
|
|
||||||
// pins that: src/shared/log.js writes to the console, and a console
|
|
||||||
// record of a recovery phrase outlives the popup.
|
|
||||||
test("the view does not import src/shared/log.js", () => {
|
|
||||||
expect(source).not.toMatch(/require\(["'][^"']*shared\/log["']\)/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the view calls no logger method", () => {
|
|
||||||
expect(source).not.toMatch(/\blog\.(debugf|infof|warnf|errorf)\b/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -102,60 +102,3 @@ describe("loadState hasWallet reconciliation", () => {
|
|||||||
expect(mod.state.activeAddress).toBe(ADDRESS);
|
expect(mod.state.activeAddress).toBe(ADDRESS);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// The known-symbol spoof filter is a safety filter, so an existing profile
|
|
||||||
// stored before the setting existed must load with it on rather than with
|
|
||||||
// undefined, which would read as off.
|
|
||||||
describe("hideSpoofedSymbols persistence", () => {
|
|
||||||
test("defaults to on with empty storage", async () => {
|
|
||||||
const { mod } = loadModuleWith(null);
|
|
||||||
await mod.loadState();
|
|
||||||
expect(mod.state.hideSpoofedSymbols).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a profile stored without the key loads with it on", async () => {
|
|
||||||
const { mod } = loadModuleWith({ wallets: oneWallet() });
|
|
||||||
await mod.loadState();
|
|
||||||
expect(mod.state.hideSpoofedSymbols).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an explicit false survives the load", async () => {
|
|
||||||
const { mod } = loadModuleWith({
|
|
||||||
wallets: oneWallet(),
|
|
||||||
hideSpoofedSymbols: false,
|
|
||||||
});
|
|
||||||
await mod.loadState();
|
|
||||||
expect(mod.state.hideSpoofedSymbols).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("saveState persists the flag", async () => {
|
|
||||||
const { mod, set } = loadModuleWith(null);
|
|
||||||
mod.state.hideSpoofedSymbols = false;
|
|
||||||
await mod.saveState();
|
|
||||||
expect(set).toHaveBeenCalledWith({
|
|
||||||
autistmask: expect.objectContaining({ hideSpoofedSymbols: false }),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the flag round-trips off through save and load", async () => {
|
|
||||||
const first = loadModuleWith(null);
|
|
||||||
first.mod.state.hideSpoofedSymbols = false;
|
|
||||||
await first.mod.saveState();
|
|
||||||
const persisted = first.set.mock.calls[0][0].autistmask;
|
|
||||||
|
|
||||||
const second = loadModuleWith(persisted);
|
|
||||||
await second.mod.loadState();
|
|
||||||
expect(second.mod.state.hideSpoofedSymbols).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the flag round-trips back on through save and load", async () => {
|
|
||||||
const first = loadModuleWith(null);
|
|
||||||
first.mod.state.hideSpoofedSymbols = true;
|
|
||||||
await first.mod.saveState();
|
|
||||||
const persisted = first.set.mock.calls[0][0].autistmask;
|
|
||||||
|
|
||||||
const second = loadModuleWith(persisted);
|
|
||||||
await second.mod.loadState();
|
|
||||||
expect(second.mod.state.hideSpoofedSymbols).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -78,7 +78,6 @@ const ORDINARY_PEER = "0x5aa0f9f1e0a1d0e0e5c1e7ce3b7dbbe9c19f0a11";
|
|||||||
|
|
||||||
// The documented default settings (README.md:810-814, state.js:24-27).
|
// The documented default settings (README.md:810-814, state.js:24-27).
|
||||||
const DEFAULT_FILTERS = {
|
const DEFAULT_FILTERS = {
|
||||||
hideSpoofedSymbols: true,
|
|
||||||
hideLowHolderTokens: true,
|
hideLowHolderTokens: true,
|
||||||
hideFraudContracts: true,
|
hideFraudContracts: true,
|
||||||
hideDustTransactions: true,
|
hideDustTransactions: true,
|
||||||
@@ -330,150 +329,44 @@ describe("known-symbol spoof verification", () => {
|
|||||||
expect(result.newFraudContracts).toEqual([]);
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Regression guard (#179): EIP-55 mixed case is a checksum over the
|
// Documents current behaviour, not desired behaviour: the spoof check
|
||||||
// address, not part of its identity, so the contract comparison must be
|
// compares tx.contractAddress against a lowercased known address with
|
||||||
// case-insensitive in both directions — a genuine token in any casing is
|
// ===, so a caller passing a checksummed address for a genuine token has
|
||||||
// genuine, and a spoof cannot escape detection by changing its casing.
|
// it treated as a spoof. In the app this cannot happen because
|
||||||
test("a genuine contract in all-lowercase form is not a spoof", () => {
|
// parseTokenTransfer lowercases, but the exported function is not
|
||||||
const tx = tokenTx({ contractAddress: USDC_CONTRACT });
|
// defensive about it the way the blocklist check is.
|
||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
test("current behaviour: a checksummed genuine contract is treated as a spoof", () => {
|
||||||
});
|
const genuineButChecksummed = tokenTx({
|
||||||
|
|
||||||
test("a genuine contract in EIP-55 checksummed form is not a spoof", () => {
|
|
||||||
const tx = tokenTx({
|
|
||||||
contractAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
contractAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
||||||
});
|
});
|
||||||
const result = filterTransactions([tx], filters());
|
const result = filterTransactions([genuineButChecksummed], filters());
|
||||||
expect(result.transactions).toEqual([tx]);
|
|
||||||
expect(result.newFraudContracts).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a genuine contract in all-uppercase form is not a spoof", () => {
|
|
||||||
const tx = tokenTx({
|
|
||||||
contractAddress: "0X" + USDC_CONTRACT.slice(2).toUpperCase(),
|
|
||||||
});
|
|
||||||
const result = filterTransactions([tx], filters());
|
|
||||||
expect(result.transactions).toEqual([tx]);
|
|
||||||
expect(result.newFraudContracts).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a genuinely different contract claiming USDC is still a spoof in any casing", () => {
|
|
||||||
const tx = tokenTx({
|
|
||||||
contractAddress: "0xD05339F9EA5AB9D9F03B9D57F671D2ABD1F55C82",
|
|
||||||
});
|
|
||||||
const result = filterTransactions([tx], filters());
|
|
||||||
expect(result.transactions).toEqual([]);
|
expect(result.transactions).toEqual([]);
|
||||||
// The recorded fraud contract is normalised, so the persisted
|
|
||||||
// blocklist matches later transfers whatever casing they arrive in.
|
|
||||||
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Turning the other three filters off must not turn this one off: each
|
// Documents current behaviour: README.md:810-814 says all four filters
|
||||||
// filter is independent, and this is the one the README calls out as the
|
// "default to on but can be individually disabled". There is no setting
|
||||||
// defense against the fake "ETH" attack.
|
// for known-symbol verification, and filterTransactions applies it
|
||||||
test("the check still runs when the other three filters are off", () => {
|
// unconditionally, so it cannot be turned off.
|
||||||
|
test("current behaviour: spoof filtering cannot be disabled by any setting", () => {
|
||||||
|
const allFiltersOff = {
|
||||||
|
hideLowHolderTokens: false,
|
||||||
|
hideFraudContracts: false,
|
||||||
|
hideDustTransactions: false,
|
||||||
|
dustThresholdGwei: 1,
|
||||||
|
fraudContracts: [],
|
||||||
|
};
|
||||||
const result = filterTransactions(
|
const result = filterTransactions(
|
||||||
[fakeEthTokenTransfer()],
|
[fakeEthTokenTransfer()],
|
||||||
filters({
|
allFiltersOff,
|
||||||
hideLowHolderTokens: false,
|
|
||||||
hideFraudContracts: false,
|
|
||||||
hideDustTransactions: false,
|
|
||||||
dustThresholdGwei: 1,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
expect(result.transactions).toEqual([]);
|
expect(result.transactions).toEqual([]);
|
||||||
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("spoof filtering also applies with no filters argument", () => {
|
test("current behaviour: spoof filtering also applies with no filters argument", () => {
|
||||||
const result = filterTransactions([fakeEthTokenTransfer()]);
|
const result = filterTransactions([fakeEthTokenTransfer()]);
|
||||||
expect(result.transactions).toEqual([]);
|
expect(result.transactions).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fail-safe: unlike the other three flags, an absent hideSpoofedSymbols
|
|
||||||
// leaves the check ON. A caller that forgets the key keeps the wallet's
|
|
||||||
// headline protection; only a user who deliberately switched the setting
|
|
||||||
// off sends an explicit false.
|
|
||||||
test("an absent hideSpoofedSymbols leaves the check on", () => {
|
|
||||||
const result = filterTransactions([fakeEthTokenTransfer()], {
|
|
||||||
fraudContracts: [],
|
|
||||||
});
|
|
||||||
expect(result.transactions).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a truthy-but-not-true hideSpoofedSymbols leaves the check on", () => {
|
|
||||||
const result = filterTransactions(
|
|
||||||
[fakeEthTokenTransfer()],
|
|
||||||
filters({ hideSpoofedSymbols: undefined }),
|
|
||||||
);
|
|
||||||
expect(result.transactions).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("disabling known-symbol spoof verification", () => {
|
|
||||||
test("the spoofed transfer is shown when hideSpoofedSymbols is false", () => {
|
|
||||||
const attack = fakeEthTokenTransfer();
|
|
||||||
const result = filterTransactions(
|
|
||||||
[attack],
|
|
||||||
filters({
|
|
||||||
hideSpoofedSymbols: false,
|
|
||||||
// The blocklist rule would otherwise hide the same row via a
|
|
||||||
// contract this pass had already learned.
|
|
||||||
hideFraudContracts: false,
|
|
||||||
hideLowHolderTokens: false,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(result.transactions).toEqual([attack]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// The blocklist is populated only by this check, so switching the check
|
|
||||||
// off stops the learning too. Leaving learning on would make the setting
|
|
||||||
// a no-op: the contract it recorded would immediately hide the same row
|
|
||||||
// through the fraud-contract rule, which is on by default.
|
|
||||||
test("no fraud contract is learned when hideSpoofedSymbols is false", () => {
|
|
||||||
const result = filterTransactions(
|
|
||||||
[fakeEthTokenTransfer()],
|
|
||||||
filters({ hideSpoofedSymbols: false }),
|
|
||||||
);
|
|
||||||
expect(result.newFraudContracts).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the setting off does not stop the other three rules", () => {
|
|
||||||
const dust = nativeDustTransfer();
|
|
||||||
const lowHolder = tokenTx({
|
|
||||||
symbol: NOVEL_SPAM_SYMBOL,
|
|
||||||
contractAddress: NOVEL_SPAM_CONTRACT,
|
|
||||||
holders: 0,
|
|
||||||
});
|
|
||||||
const result = filterTransactions(
|
|
||||||
[dust, lowHolder],
|
|
||||||
filters({ hideSpoofedSymbols: false }),
|
|
||||||
);
|
|
||||||
expect(result.transactions).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// An already-persisted fraud contract keeps being filtered: the blocklist
|
|
||||||
// rule is a separate setting and is unaffected by this one.
|
|
||||||
test("an already-blocklisted contract is still hidden with the check off", () => {
|
|
||||||
const result = filterTransactions(
|
|
||||||
[fakeEthTokenTransfer()],
|
|
||||||
filters({
|
|
||||||
hideSpoofedSymbols: false,
|
|
||||||
fraudContracts: [FAKE_ETH_CONTRACT],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(result.transactions).toEqual([]);
|
|
||||||
expect(result.newFraudContracts).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a genuine transfer is unaffected by the setting either way", () => {
|
|
||||||
const tx = tokenTx();
|
|
||||||
expect(
|
|
||||||
filterTransactions([tx], filters({ hideSpoofedSymbols: false }))
|
|
||||||
.transactions,
|
|
||||||
).toEqual([tx]);
|
|
||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
||||||
@@ -519,21 +412,6 @@ describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
|||||||
expect(tx.holders).toBeNull();
|
expect(tx.holders).toBeNull();
|
||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Regression guard (#179): an unknown holder count on a real token — the
|
|
||||||
// explorer rate-limited the call, or a self-hosted instance omits the
|
|
||||||
// field — must not be read as zero holders. Reading it that way hides a
|
|
||||||
// legitimate transfer from the user's history, the same over-filtering
|
|
||||||
// harm as the zero-threshold bug. This pins the `tx.holders !== null`
|
|
||||||
// guard, which no fixture previously reached.
|
|
||||||
test("a token whose holder count is unknown is not filtered", () => {
|
|
||||||
const tx = tokenTx({
|
|
||||||
symbol: NOVEL_SPAM_SYMBOL,
|
|
||||||
contractAddress: NOVEL_SPAM_CONTRACT,
|
|
||||||
holders: null,
|
|
||||||
});
|
|
||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("fraud contract blocklist", () => {
|
describe("fraud contract blocklist", () => {
|
||||||
@@ -697,56 +575,21 @@ describe("dust threshold filtering", () => {
|
|||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Regression guard (#179): 0 is a real threshold meaning "hide nothing",
|
// Documents current behaviour: the threshold is read as
|
||||||
// not an absent one. It used to be swallowed by `|| 100000`, so the one
|
// `filters.dustThresholdGwei || 100000`, so a user who sets the threshold
|
||||||
// value a user would pick to see everything was the one that did not
|
// to 0 (the natural way to ask for no dust filtering while leaving the
|
||||||
// work.
|
// toggle on) silently gets the 100,000 gwei default instead.
|
||||||
test("a threshold of 0 hides nothing, leaving the toggle on", () => {
|
test("current behaviour: a threshold of 0 falls back to the 100,000 gwei default", () => {
|
||||||
const dust = dustOf(50);
|
const result = filterTransactions(
|
||||||
const zero = dustOf(0);
|
[dustOf(50)],
|
||||||
const opts = filters({ dustThresholdGwei: 0 });
|
|
||||||
expect(filterTransactions([dust], opts).transactions).toEqual([dust]);
|
|
||||||
expect(filterTransactions([zero], opts).transactions).toEqual([zero]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a threshold of 0 agrees with clearing the hide-dust checkbox", () => {
|
|
||||||
const tx = nativeDustTransfer();
|
|
||||||
const thresholdZero = filterTransactions(
|
|
||||||
[tx],
|
|
||||||
filters({ dustThresholdGwei: 0 }),
|
filters({ dustThresholdGwei: 0 }),
|
||||||
);
|
);
|
||||||
const toggleOff = filterTransactions(
|
expect(result.transactions).toEqual([]);
|
||||||
[tx],
|
|
||||||
filters({ hideDustTransactions: false }),
|
|
||||||
);
|
|
||||||
expect(thresholdZero.transactions).toEqual([tx]);
|
|
||||||
expect(toggleOff.transactions).toEqual([tx]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("0, unset and a set threshold are three distinct behaviours", () => {
|
|
||||||
const tx = dustOf(50);
|
|
||||||
expect(
|
|
||||||
filterTransactions([tx], filters({ dustThresholdGwei: 0 }))
|
|
||||||
.transactions,
|
|
||||||
).toEqual([tx]);
|
|
||||||
expect(
|
|
||||||
filterTransactions([tx], filters({ dustThresholdGwei: undefined }))
|
|
||||||
.transactions,
|
|
||||||
).toEqual([]);
|
|
||||||
expect(
|
|
||||||
filterTransactions([tx], filters({ dustThresholdGwei: 40 }))
|
|
||||||
.transactions,
|
|
||||||
).toEqual([tx]);
|
|
||||||
expect(
|
|
||||||
filterTransactions([tx], filters({ dustThresholdGwei: 60 }))
|
|
||||||
.transactions,
|
|
||||||
).toEqual([]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("filter defaults promised by the README and Settings", () => {
|
describe("filter defaults promised by the README and Settings", () => {
|
||||||
test("all four toggles default to on and the threshold to 100,000 gwei", () => {
|
test("all three toggles default to on and the threshold to 100,000 gwei", () => {
|
||||||
expect(state.hideSpoofedSymbols).toBe(true);
|
|
||||||
expect(state.hideLowHolderTokens).toBe(true);
|
expect(state.hideLowHolderTokens).toBe(true);
|
||||||
expect(state.hideFraudContracts).toBe(true);
|
expect(state.hideFraudContracts).toBe(true);
|
||||||
expect(state.hideDustTransactions).toBe(true);
|
expect(state.hideDustTransactions).toBe(true);
|
||||||
@@ -757,10 +600,10 @@ describe("filter defaults promised by the README and Settings", () => {
|
|||||||
expect(state.fraudContracts).toEqual([]);
|
expect(state.fraudContracts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Documents current behaviour: filterTransactions defaults the other three
|
// Documents current behaviour: filterTransactions itself defaults every
|
||||||
// optional filters to off. Their "default to on" promise is satisfied by
|
// optional filter to off. The "default to on" promise is satisfied by
|
||||||
// the state defaults above, which every caller passes in. Spoof
|
// the state defaults above, which every caller passes in; the pure
|
||||||
// verification is the exception and stays on unless explicitly disabled.
|
// function makes no assumption of its own.
|
||||||
test("current behaviour: with no filters argument only spoof filtering runs", () => {
|
test("current behaviour: with no filters argument only spoof filtering runs", () => {
|
||||||
const dust = nativeDustTransfer();
|
const dust = nativeDustTransfer();
|
||||||
const lowHolder = tokenTx({
|
const lowHolder = tokenTx({
|
||||||
|
|||||||
@@ -111,7 +111,6 @@ global.chrome = {
|
|||||||
|
|
||||||
const txStatus = require("../src/popup/views/txStatus");
|
const txStatus = require("../src/popup/views/txStatus");
|
||||||
const { state } = require("../src/shared/state");
|
const { state } = require("../src/shared/state");
|
||||||
const { RESTORABLE_VIEWS } = require("../src/popup/restorableViews");
|
|
||||||
|
|
||||||
const TX_HASH =
|
const TX_HASH =
|
||||||
"0x85215772ed26ea8b39c2b3b18779030487efbe0b5fd7e882592b2f62b837be84";
|
"0x85215772ed26ea8b39c2b3b18779030487efbe0b5fd7e882592b2f62b837be84";
|
||||||
@@ -332,18 +331,6 @@ describe("WaitTx persistence across popup close", () => {
|
|||||||
{ hash: TX_HASH, txInfo: TX_INFO, broadcastTime: "soon" },
|
{ hash: TX_HASH, txInfo: TX_INFO, broadcastTime: "soon" },
|
||||||
{ hash: TX_HASH, txInfo: TX_INFO, broadcastTime: NaN },
|
{ hash: TX_HASH, txInfo: TX_INFO, broadcastTime: NaN },
|
||||||
{ hash: TX_HASH, txInfo: "nope", broadcastTime: Date.now() },
|
{ hash: TX_HASH, txInfo: "nope", broadcastTime: Date.now() },
|
||||||
// An object that merely lacks a field startWait() dereferences
|
|
||||||
// is the shape that actually escaped: txInfo.to reaches
|
|
||||||
// addressTitle(), which calls address.toLowerCase(). typeof []
|
|
||||||
// is "object", so an array passes an object check.
|
|
||||||
{ hash: TX_HASH, txInfo: {}, broadcastTime: Date.now() },
|
|
||||||
{ hash: TX_HASH, txInfo: [], broadcastTime: Date.now() },
|
|
||||||
{ hash: TX_HASH, txInfo: { to: 42 }, broadcastTime: Date.now() },
|
|
||||||
{
|
|
||||||
hash: TX_HASH,
|
|
||||||
txInfo: { to: RECIPIENT },
|
|
||||||
broadcastTime: Date.now(),
|
|
||||||
},
|
|
||||||
]) {
|
]) {
|
||||||
state.viewData = { pendingWait: bad };
|
state.viewData = { pendingWait: bad };
|
||||||
expect(txStatus.restoreWait()).toBe(false);
|
expect(txStatus.restoreWait()).toBe(false);
|
||||||
@@ -351,90 +338,3 @@ describe("WaitTx persistence across popup close", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("WaitTx against an RPC that never answers", () => {
|
|
||||||
test("a permanently failing lookup ends the wait instead of polling forever", async () => {
|
|
||||||
mockReceiptLookup.mockRejectedValue(new Error("rpc unavailable"));
|
|
||||||
|
|
||||||
txStatus.showWait(TX_INFO, TX_HASH);
|
|
||||||
|
|
||||||
// Six consecutive failures is 60 seconds at the 10s cadence — the
|
|
||||||
// same patience as the confirmation deadline.
|
|
||||||
await jest.advanceTimersByTimeAsync(60000);
|
|
||||||
|
|
||||||
expect(state.currentView).toBe("error-tx");
|
|
||||||
expect(visible("wait-tx")).toBe(false);
|
|
||||||
// The user is told what actually happened: the lookup failed. It is
|
|
||||||
// not the same fact as "the transaction did not confirm".
|
|
||||||
expect(state.viewData.message).toMatch(/could not be reached/i);
|
|
||||||
expect(state.viewData.message).not.toMatch(/not confirmed within/);
|
|
||||||
expect(state.viewData.hash).toBe(TX_HASH);
|
|
||||||
|
|
||||||
// Nothing is left running, and nothing is left to resume onto.
|
|
||||||
expect(jest.getTimerCount()).toBe(0);
|
|
||||||
expect(state.viewData.pendingWait).toBeUndefined();
|
|
||||||
|
|
||||||
const calls = mockReceiptLookup.mock.calls.length;
|
|
||||||
await jest.advanceTimersByTimeAsync(3600000);
|
|
||||||
expect(mockReceiptLookup).toHaveBeenCalledTimes(calls);
|
|
||||||
expect(state.currentView).toBe("error-tx");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an answered lookup clears the failure count, so the bound is on consecutive failures", async () => {
|
|
||||||
// Failures interleaved with answers must never accumulate into the
|
|
||||||
// bound: an RPC that is merely flaky keeps waiting for the receipt.
|
|
||||||
mockReceiptLookup.mockImplementation(() => {
|
|
||||||
const n = mockReceiptLookup.mock.calls.length;
|
|
||||||
if (n % 2 === 1) return Promise.reject(new Error("flaky"));
|
|
||||||
return Promise.resolve(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
txStatus.showWait(TX_INFO, TX_HASH);
|
|
||||||
await jest.advanceTimersByTimeAsync(50000);
|
|
||||||
|
|
||||||
// Five polls in: three threw, two answered null, and the answered
|
|
||||||
// ones are all before the deadline. Still waiting.
|
|
||||||
expect(state.currentView).toBe("wait-tx");
|
|
||||||
expect(visible("wait-tx")).toBe(true);
|
|
||||||
expect(jest.getTimerCount()).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
// Past the deadline the first lookup that answers "no receipt"
|
|
||||||
// still times out, with the timeout copy rather than the RPC copy.
|
|
||||||
await jest.advanceTimersByTimeAsync(70000);
|
|
||||||
expect(state.currentView).toBe("error-tx");
|
|
||||||
expect(state.viewData.message).toMatch(/not confirmed within/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a resumed wait against a dead RPC also terminates", async () => {
|
|
||||||
// The reopen path is the one that made this unbounded: the wait is
|
|
||||||
// persisted, so without a bound every popup open resumes it forever.
|
|
||||||
mockReceiptLookup.mockResolvedValue(null);
|
|
||||||
txStatus.showWait(TX_INFO, TX_HASH);
|
|
||||||
const persisted = JSON.parse(JSON.stringify(state.viewData));
|
|
||||||
txStatus.endWait();
|
|
||||||
|
|
||||||
jest.advanceTimersByTime(3600000);
|
|
||||||
mockReceiptLookup.mockReset();
|
|
||||||
mockReceiptLookup.mockRejectedValue(new Error("rpc unavailable"));
|
|
||||||
|
|
||||||
state.viewData = persisted;
|
|
||||||
expect(txStatus.restoreWait()).toBe(true);
|
|
||||||
await jest.advanceTimersByTimeAsync(60000);
|
|
||||||
|
|
||||||
expect(state.currentView).toBe("error-tx");
|
|
||||||
expect(state.viewData.message).toMatch(/could not be reached/i);
|
|
||||||
expect(jest.getTimerCount()).toBe(0);
|
|
||||||
expect(state.viewData.pendingWait).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("wait-tx is a view the popup may reopen onto", () => {
|
|
||||||
// The resume feature is wired through RESTORABLE_VIEWS: restoreView()
|
|
||||||
// refuses any view not in the set, so dropping "wait-tx" from it kills
|
|
||||||
// the resume silently — the tests above call restoreWait() directly and
|
|
||||||
// would all still pass. This pins the membership. Mirrors the exclusion
|
|
||||||
// assertions in tests/showPhrase.test.js.
|
|
||||||
test("wait-tx is restorable", () => {
|
|
||||||
expect(RESTORABLE_VIEWS.has("wait-tx")).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,357 +0,0 @@
|
|||||||
const { parseEther } = require("ethers");
|
|
||||||
const {
|
|
||||||
CODES,
|
|
||||||
FEE_PENDING,
|
|
||||||
FEE_KNOWN,
|
|
||||||
FEE_UNAVAILABLE,
|
|
||||||
feeReserveWei,
|
|
||||||
feeEstimateWei,
|
|
||||||
toFixedPoint,
|
|
||||||
validateTransfer,
|
|
||||||
} = require("../src/shared/txValidation");
|
|
||||||
|
|
||||||
// A plausible mainnet fee: 21000 gas at 20 gwei.
|
|
||||||
const FEE = 21000n * 20000000000n; // 0.00042 ETH
|
|
||||||
|
|
||||||
const GWEI = 1000000000n;
|
|
||||||
const GAS_LIMIT = 21000n;
|
|
||||||
|
|
||||||
describe("toFixedPoint", () => {
|
|
||||||
test("scales human decimals to 18 places", () => {
|
|
||||||
expect(toFixedPoint("1.5")).toBe(parseEther("1.5"));
|
|
||||||
expect(toFixedPoint("0")).toBe(0n);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("rejects values it cannot represent exactly", () => {
|
|
||||||
expect(toFixedPoint("not a number")).toBe(null);
|
|
||||||
expect(toFixedPoint("")).toBe(null);
|
|
||||||
expect(toFixedPoint(null)).toBe(null);
|
|
||||||
// More precision than 18 decimals can hold.
|
|
||||||
expect(toFixedPoint("0.0000000000000000001")).toBe(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("validateTransfer, native ETH", () => {
|
|
||||||
const eth = (over) => ({
|
|
||||||
isErc20: false,
|
|
||||||
amount: "0.5",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_KNOWN,
|
|
||||||
feeWei: FEE,
|
|
||||||
...over,
|
|
||||||
});
|
|
||||||
|
|
||||||
test("allows a send comfortably within balance", () => {
|
|
||||||
const r = validateTransfer(eth());
|
|
||||||
expect(r).toEqual({ canSend: true, codes: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks a send whose amount plus fee exceeds the balance", () => {
|
|
||||||
// The whole balance: passes an amount-only check, fails once the fee
|
|
||||||
// is counted. This is the bug this module exists to prevent.
|
|
||||||
const r = validateTransfer(eth({ amount: "1.0", ethBalance: "1.0" }));
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks a send left short by less than one fee", () => {
|
|
||||||
const balance = "1.0";
|
|
||||||
// One wei less headroom than the fee needs.
|
|
||||||
const amount = "0.99958000000000001"; // 1.0 - 0.00042 + 1e-17
|
|
||||||
const r = validateTransfer(eth({ amount, ethBalance: balance }));
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("allows a send that leaves exactly the fee behind", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
eth({ amount: "0.99958", ethBalance: "1.0" }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: true, codes: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("reports plain insufficient balance when the amount alone is too big", () => {
|
|
||||||
const r = validateTransfer(eth({ amount: "2.0", ethBalance: "1.0" }));
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks while the fee estimate is still pending", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
eth({ feeStatus: FEE_PENDING, feeWei: null }),
|
|
||||||
);
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.FEE_PENDING]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks when the fee estimate failed, without assuming zero", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
eth({
|
|
||||||
amount: "1.0",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_UNAVAILABLE,
|
|
||||||
feeWei: null,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.FEE_UNAVAILABLE]);
|
|
||||||
// A zero fee would have let this exact transfer through.
|
|
||||||
expect(
|
|
||||||
validateTransfer(
|
|
||||||
eth({ amount: "1.0", ethBalance: "1.0", feeWei: 0n }),
|
|
||||||
).canSend,
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("still reports an over-balance amount before the estimate lands", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
eth({
|
|
||||||
amount: "2.0",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_PENDING,
|
|
||||||
feeWei: null,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH, CODES.FEE_PENDING]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("rejects an amount it cannot do exact arithmetic on", () => {
|
|
||||||
const r = validateTransfer(eth({ amount: "abc" }));
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.AMOUNT_INVALID]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("rejects a negative amount", () => {
|
|
||||||
// A negative amount parses to a perfectly good bigint, so neither
|
|
||||||
// balance comparison can fire: both are trivially false against it.
|
|
||||||
// Left unblocked it clears the screen and then dies at encode time.
|
|
||||||
const r = validateTransfer(
|
|
||||||
eth({ amount: "-1", ethBalance: "1.0", feeWei: 861000000000000n }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
|
||||||
expect(
|
|
||||||
validateTransfer(eth({ amount: "-0.000000000000000001" })),
|
|
||||||
).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("treats a missing balance as zero, not as unlimited", () => {
|
|
||||||
const r = validateTransfer(eth({ ethBalance: undefined }));
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("validateTransfer, ERC-20", () => {
|
|
||||||
const erc20 = (over) => ({
|
|
||||||
isErc20: true,
|
|
||||||
amount: "100.0",
|
|
||||||
tokenBalance: "250.0",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_KNOWN,
|
|
||||||
feeWei: FEE,
|
|
||||||
...over,
|
|
||||||
});
|
|
||||||
|
|
||||||
test("allows a transfer with tokens to spend and ETH for the fee", () => {
|
|
||||||
expect(validateTransfer(erc20())).toEqual({ canSend: true, codes: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("checks the token amount against the token balance", () => {
|
|
||||||
const r = validateTransfer(erc20({ amount: "250.000001" }));
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_TOKEN]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("does not charge the fee against the token balance", () => {
|
|
||||||
// The full token balance is sendable: the fee is paid in ETH.
|
|
||||||
expect(validateTransfer(erc20({ amount: "250.0" })).canSend).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks when the ETH balance does not cover the fee", () => {
|
|
||||||
const r = validateTransfer(erc20({ ethBalance: "0.0001" }));
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_FOR_FEE]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("allows a fee exactly equal to the ETH balance", () => {
|
|
||||||
const r = validateTransfer(erc20({ ethBalance: "0.00042" }));
|
|
||||||
expect(r).toEqual({ canSend: true, codes: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("reports both shortfalls when tokens and ETH are both short", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
erc20({ amount: "300.0", ethBalance: "0.0" }),
|
|
||||||
);
|
|
||||||
expect(r.codes).toEqual([
|
|
||||||
CODES.INSUFFICIENT_TOKEN,
|
|
||||||
CODES.INSUFFICIENT_ETH_FOR_FEE,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks while the fee estimate is pending or failed", () => {
|
|
||||||
expect(
|
|
||||||
validateTransfer(erc20({ feeStatus: FEE_PENDING, feeWei: null }))
|
|
||||||
.codes,
|
|
||||||
).toEqual([CODES.FEE_PENDING]);
|
|
||||||
expect(
|
|
||||||
validateTransfer(
|
|
||||||
erc20({ feeStatus: FEE_UNAVAILABLE, feeWei: null }),
|
|
||||||
).codes,
|
|
||||||
).toEqual([CODES.FEE_UNAVAILABLE]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("rejects a negative token amount", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
erc20({ amount: "-0.5", feeWei: 861000000000000n }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("treats a missing token balance as zero", () => {
|
|
||||||
const r = validateTransfer(erc20({ tokenBalance: undefined }));
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_TOKEN]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// The reserve a node requires, not the fee the transaction is expected to
|
|
||||||
// actually cost. An unpinned send goes out as type-2, and the node checks it
|
|
||||||
// against maxFeePerGas; reserving gasPrice lets a transaction the node will
|
|
||||||
// reject pass the gate.
|
|
||||||
describe("feeReserveWei", () => {
|
|
||||||
// baseFee 20 gwei, tip 1 gwei: eth_gasPrice reports ~21 gwei, while
|
|
||||||
// ethers populates maxFeePerGas as baseFee * 2 + tip = 41 gwei.
|
|
||||||
const type2 = {
|
|
||||||
gasPrice: 21n * GWEI,
|
|
||||||
maxFeePerGas: 41n * GWEI,
|
|
||||||
maxPriorityFeePerGas: 1n * GWEI,
|
|
||||||
};
|
|
||||||
|
|
||||||
test("reserves gasLimit * maxFeePerGas, not gasLimit * gasPrice", () => {
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(GAS_LIMIT * 41n * GWEI);
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(861000000000000n);
|
|
||||||
// The number the node would not have accepted.
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, type2)).not.toBe(441000000000000n);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("gates out a send the type-2 reserve cannot fund", () => {
|
|
||||||
// Exactly fundable against a gasPrice reserve (0.999559 + 0.000441 is
|
|
||||||
// the whole balance to the wei), and short against the reserve the
|
|
||||||
// node will actually require.
|
|
||||||
const send = {
|
|
||||||
isErc20: false,
|
|
||||||
amount: "0.999559",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_KNOWN,
|
|
||||||
};
|
|
||||||
expect(
|
|
||||||
validateTransfer({
|
|
||||||
...send,
|
|
||||||
feeWei: GAS_LIMIT * type2.gasPrice,
|
|
||||||
}).canSend,
|
|
||||||
).toBe(true);
|
|
||||||
const r = validateTransfer({
|
|
||||||
...send,
|
|
||||||
feeWei: feeReserveWei(GAS_LIMIT, type2),
|
|
||||||
});
|
|
||||||
expect(r.canSend).toBe(false);
|
|
||||||
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("falls back to gasPrice on a network with no type-2 pricing", () => {
|
|
||||||
const legacy = { gasPrice: 21n * GWEI, maxFeePerGas: null };
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, legacy)).toBe(GAS_LIMIT * 21n * GWEI);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns null when no usable price or gas limit is available", () => {
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, { gasPrice: null })).toBe(null);
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, {})).toBe(null);
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, null)).toBe(null);
|
|
||||||
expect(feeReserveWei(21000, type2)).toBe(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// The display counterpart of the reserve: what the transaction is expected to
|
|
||||||
// cost. Shown alongside the reserve so the screen neither contradicts the gate
|
|
||||||
// nor quotes the user roughly double what they will pay.
|
|
||||||
describe("feeEstimateWei", () => {
|
|
||||||
const type2 = {
|
|
||||||
gasPrice: 21n * GWEI,
|
|
||||||
maxFeePerGas: 41n * GWEI,
|
|
||||||
maxPriorityFeePerGas: 1n * GWEI,
|
|
||||||
};
|
|
||||||
|
|
||||||
test("estimates gasLimit * gasPrice, below the reserve", () => {
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, type2)).toBe(441000000000000n);
|
|
||||||
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(861000000000000n);
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, type2)).toBeLessThan(
|
|
||||||
feeReserveWei(GAS_LIMIT, type2),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("equals the reserve when the network has no type-2 pricing", () => {
|
|
||||||
const legacy = { gasPrice: 21n * GWEI, maxFeePerGas: null };
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, legacy)).toBe(
|
|
||||||
feeReserveWei(GAS_LIMIT, legacy),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("falls back to maxFeePerGas when there is no gasPrice", () => {
|
|
||||||
const noLegacy = { gasPrice: null, maxFeePerGas: 41n * GWEI };
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, noLegacy)).toBe(
|
|
||||||
feeReserveWei(GAS_LIMIT, noLegacy),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns null on the same unusable inputs as the reserve", () => {
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, {})).toBe(null);
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, null)).toBe(null);
|
|
||||||
expect(feeEstimateWei(GAS_LIMIT, { gasPrice: -1n })).toBe(null);
|
|
||||||
expect(feeEstimateWei(21000, type2)).toBe(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Everything that is not a usable fee blocks exactly as FEE_UNAVAILABLE does.
|
|
||||||
// Each of these previously returned { canSend: true, codes: [] } — counting no
|
|
||||||
// fee at all, on a full-balance send, in the direction that lets money out.
|
|
||||||
describe("validateTransfer, unusable fee input fails closed", () => {
|
|
||||||
const fullBalanceSend = (over) => ({
|
|
||||||
isErc20: false,
|
|
||||||
amount: "1.0",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
...over,
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks a null fee claiming to be known", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: null }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks a known fee that is a number rather than a bigint", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: 420000000000000 }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks an unrecognised fee status", () => {
|
|
||||||
const r = validateTransfer(fullBalanceSend({ feeStatus: "bogus" }));
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks a negative fee", () => {
|
|
||||||
const r = validateTransfer(
|
|
||||||
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: -1n }),
|
|
||||||
);
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("blocks an ERC-20 transfer on an unusable fee too", () => {
|
|
||||||
const r = validateTransfer({
|
|
||||||
isErc20: true,
|
|
||||||
amount: "100.0",
|
|
||||||
tokenBalance: "250.0",
|
|
||||||
ethBalance: "1.0",
|
|
||||||
feeStatus: FEE_KNOWN,
|
|
||||||
feeWei: null,
|
|
||||||
});
|
|
||||||
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -160,31 +160,6 @@ function masterXprv(phrase, passphrase = "") {
|
|||||||
).extendedKey;
|
).extendedKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The account-level (depth-3) extended private key m/44'/60'/0' for a phrase.
|
|
||||||
// A normal thing for a user to hold, and not something the import flow can
|
|
||||||
// derive the BIP-44 account path from.
|
|
||||||
function accountXprv(phrase) {
|
|
||||||
return HDNodeWallet.fromSeed(
|
|
||||||
Mnemonic.fromPhrase(phrase, "").computeSeed(),
|
|
||||||
).derivePath("m/44'/60'/0'").extendedKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Every single-character substitution of `key`, using base58 characters that
|
|
||||||
// are not the original. Base58 has no visually ambiguous characters, so each
|
|
||||||
// of these is a plausible typo rather than a contrived string.
|
|
||||||
const TYPO_CHARS = ["a", "b", "2", "Z"];
|
|
||||||
|
|
||||||
function singleCharacterTypos(key) {
|
|
||||||
const out = [];
|
|
||||||
for (let i = 0; i < key.length; i++) {
|
|
||||||
for (const c of TYPO_CHARS) {
|
|
||||||
if (c === key[i]) continue;
|
|
||||||
out.push(key.slice(0, i) + c + key.slice(i + 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("hdWalletFromMnemonic", () => {
|
describe("hdWalletFromMnemonic", () => {
|
||||||
test("first address matches the published vector for m/44'/60'/0'/0/0", () => {
|
test("first address matches the published vector for m/44'/60'/0'/0/0", () => {
|
||||||
expect(wallet.hdWalletFromMnemonic(VECTOR_PHRASE).firstAddress).toBe(
|
expect(wallet.hdWalletFromMnemonic(VECTOR_PHRASE).firstAddress).toBe(
|
||||||
@@ -324,7 +299,19 @@ describe("isValidXprv", () => {
|
|||||||
expect(wallet.isValidXprv(xpub)).toBe(false);
|
expect(wallet.isValidXprv(xpub)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("rejects an extended key with a one-character typo", () => {
|
// Skipped: this asserts the correct behaviour, which the code does not
|
||||||
|
// currently have. isValidXprv gates the paste-your-extended-private-key
|
||||||
|
// import in src/popup/views/addWallet.js:215, and it accepts a key with a
|
||||||
|
// one-character typo: ethers' HDNodeWallet.fromExtendedKey skips base58
|
||||||
|
// checksum verification whenever the decoded payload is the usual 82
|
||||||
|
// bytes, which is the whole point of that checksum. Measured on this
|
||||||
|
// vector: changing any one of the last 14 characters passes validation,
|
||||||
|
// and for 9 of those 14 positions the import silently yields a *different*
|
||||||
|
// wallet (e.g. 0x3F334f0a356d6B46B1d70B590E7437D77100d28D instead of
|
||||||
|
// 0x022b971dFF0C43305e691DEd7a14367AF19D6407) with no error shown.
|
||||||
|
// Tracked as https://git.eeqj.de/sneak/AutistMask/issues/210; out of scope
|
||||||
|
// here, which is tests only. Unskip when it is fixed.
|
||||||
|
test.skip("rejects an extended key with a one-character typo", () => {
|
||||||
const index = BIP32_VECTOR_1_XPRV.length - 8;
|
const index = BIP32_VECTOR_1_XPRV.length - 8;
|
||||||
const typo =
|
const typo =
|
||||||
BIP32_VECTOR_1_XPRV.slice(0, index) +
|
BIP32_VECTOR_1_XPRV.slice(0, index) +
|
||||||
@@ -333,125 +320,6 @@ describe("isValidXprv", () => {
|
|||||||
|
|
||||||
expect(wallet.isValidXprv(typo)).toBe(false);
|
expect(wallet.isValidXprv(typo)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
// The base58 checksum exists to make a mistyped key impossible to use, and
|
|
||||||
// ethers does not enforce it: HDNodeWallet.fromExtendedKey skips checksum
|
|
||||||
// verification whenever the decoded payload is the usual 82 bytes, which
|
|
||||||
// is precisely the case it is there to catch. A typo anywhere in the key
|
|
||||||
// must be refused, not silently turned into someone else's wallet.
|
|
||||||
test("no single-character typo anywhere in the key is accepted", () => {
|
|
||||||
const accepted = singleCharacterTypos(BIP32_VECTOR_1_XPRV).filter(
|
|
||||||
(typo) => wallet.isValidXprv(typo),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(accepted).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a typo never yields a wallet, let alone a different one", () => {
|
|
||||||
const correct = wallet.hdWalletFromXprv(BIP32_VECTOR_1_XPRV);
|
|
||||||
const derived = [];
|
|
||||||
for (const typo of singleCharacterTypos(BIP32_VECTOR_1_XPRV)) {
|
|
||||||
try {
|
|
||||||
derived.push(wallet.hdWalletFromXprv(typo).firstAddress);
|
|
||||||
} catch {
|
|
||||||
// Rejected, which is the required behaviour.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(derived).toEqual([]);
|
|
||||||
expect(correct.firstAddress).toBe(
|
|
||||||
"0x022b971dFF0C43305e691DEd7a14367AF19D6407",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("extended key depth", () => {
|
|
||||||
// hdWalletFromXprv derives the BIP-44 Ethereum account path from the key
|
|
||||||
// it is given. That is only the path it names when the key is the master
|
|
||||||
// key. Under an account-level key the same derivation lands at
|
|
||||||
// m/44'/60'/0'/44'/60'/0'/0, whose addresses correspond to nothing the
|
|
||||||
// user holds, so a non-master key is refused rather than derived from.
|
|
||||||
test("a master key is a master key", () => {
|
|
||||||
expect(wallet.isMasterExtendedKey(masterXprv(VECTOR_PHRASE))).toBe(
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
expect(wallet.isMasterExtendedKey(BIP32_VECTOR_1_XPRV)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("an account-level key is not a master key", () => {
|
|
||||||
expect(wallet.isMasterExtendedKey(accountXprv(VECTOR_PHRASE))).toBe(
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a derived xpub is not a master key", () => {
|
|
||||||
expect(
|
|
||||||
wallet.isMasterExtendedKey(
|
|
||||||
wallet.hdWalletFromMnemonic(VECTOR_PHRASE).xpub,
|
|
||||||
),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a mistyped key is not a master key either", () => {
|
|
||||||
expect(wallet.isMasterExtendedKey(BIP32_VECTOR_1_XPRV + "a")).toBe(
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("hdWalletFromXprv rejects an account-level key", () => {
|
|
||||||
expect(() =>
|
|
||||||
wallet.hdWalletFromXprv(accountXprv(VECTOR_PHRASE)),
|
|
||||||
).toThrow(/master/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getSignerForAddress rejects an account-level key", () => {
|
|
||||||
expect(() =>
|
|
||||||
wallet.getSignerForAddress(
|
|
||||||
{ type: "xprv" },
|
|
||||||
0,
|
|
||||||
accountXprv(VECTOR_PHRASE),
|
|
||||||
),
|
|
||||||
).toThrow(/master/i);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the account-level key is well-formed, so only depth rejects it", () => {
|
|
||||||
expect(wallet.isValidXprv(accountXprv(VECTOR_PHRASE))).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a master key still imports and derives the published addresses", () => {
|
|
||||||
const { xpub, firstAddress } = wallet.hdWalletFromXprv(
|
|
||||||
masterXprv(VECTOR_PHRASE),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(firstAddress).toBe(VECTOR_ADDRESSES[0]);
|
|
||||||
expect(
|
|
||||||
[0, 1, 2].map((i) => wallet.deriveAddressFromXpub(xpub, i)),
|
|
||||||
).toEqual(VECTOR_ADDRESSES);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("deriveAddressFromXpub checksum enforcement", () => {
|
|
||||||
// The xpub path shares the hole: fromExtendedKey accepts a mistyped xpub
|
|
||||||
// just as readily, and deriveAddressFromXpub would hand back addresses
|
|
||||||
// from a different tree.
|
|
||||||
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
|
||||||
|
|
||||||
test("the correct xpub still derives the published addresses", () => {
|
|
||||||
expect(wallet.deriveAddressFromXpub(xpub, 0)).toBe(VECTOR_ADDRESSES[0]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("no single-character typo anywhere in an xpub is accepted", () => {
|
|
||||||
const derived = [];
|
|
||||||
for (const typo of singleCharacterTypos(xpub)) {
|
|
||||||
try {
|
|
||||||
derived.push(wallet.deriveAddressFromXpub(typo, 0));
|
|
||||||
} catch {
|
|
||||||
// Rejected, which is the required behaviour.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(derived).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("isValidMnemonic", () => {
|
describe("isValidMnemonic", () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user