Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,28 @@ Converts chain addresses to and from the bytes ENS stores in `addr(node, coinTyp
## Layout

- `src/<Chain>Coder.sol`: one library per chain (see the README table). Each one exposes
`encode(bytes) → string`, `decode(string) → bytes` and `COIN_TYPE`.
`encode(bytes) → (bool ok, string addr)`, `decode(string) → (bool ok, bytes data)` and `COIN_TYPE`
(`EvmCoder` has `COIN_TYPE_ETH` / `COIN_TYPE_DEFAULT`, per ENSIP-19).
- `src/AddressCoder.sol`: opt-in dispatcher by coinType over every coder.
- `src/utils/`: shared building blocks (`Base58`, `Base32`, `Bech32`, `BitcoinLike`, `CashAddr`, `Blake2b`, `SS58`).
- `test/Coders.t.sol`: vector, decode-only, invalid-input and round-trip fuzz tests, run through a `Harness`
that dispatches by coinType. `test/Blake2b.t.sol` has RFC 7693 and hashlib vectors.
that calls `AddressCoder`. `test/Blake2b.t.sol` has RFC 7693 and hashlib vectors.
- `test/vectors/`: `vectors.json` is generated by `generate.mjs` from the JS reference. Don't hand-edit it.

## Conventions

- **Everything is an `internal` library function.** That's what keeps the libraries tree-shakeable: a
consumer only compiles in the coders and functions it calls. Don't add `public`/`external`
library functions, storage, or a central registry that imports every coder.
library functions or storage. `AddressCoder` is the only file that imports every coder, and no
coder or util may import it.
- One file per chain. Adding a chain shouldn't change the bytecode of contracts that use other coders.
- Byte layout must match `@ensdomains/address-encoder` (the output of `decode`, the input of `encode`).
Being stricter about validity is fine; document any difference in the README.
- Invalid input reverts with a custom error. There are no `try*`/bool-returning variants unless asked for.
- **Nothing reverts, and there are no custom errors.** `encode` and `decode` return `(false, "")` on
invalid input, and so does every util that can fail. Internal library calls can't be wrapped in
`try`/`catch`, so a revert would leave callers no way to handle bad input. Don't index past a
length you haven't checked (a panic is a revert too). `testFuzz_encodeNeverReverts*` and
`testFuzz_decodeNeverReverts*` enforce this for every coinType.
- Coders are `pure` unless they need a precompile (Polkadot/Kusama use the BLAKE2b precompile, so they're `view`).
- If the reference has a bug, don't copy it. Write a vector that pins the correct behaviour, and record
the difference in the README.
Expand All @@ -36,9 +43,12 @@ Converts chain addresses to and from the bytes ENS stores in `addr(node, coinTyp

## Adding a coder

1. Add `src/<Chain>Coder.sol` (and any shared util under `src/utils/`).
1. Add `src/<Chain>Coder.sol` (and any shared util under `src/utils/`). Give the library NatSpec with a
`References:` list: the format specs, where the chain's constants come from, and the
address-encoder source file. Wire it into `AddressCoder` (`encode`, `decode`, `isSupported`).
2. Add a `define('<coin>', …)` block to `test/vectors/generate.mjs` with `valid`, `decodeOnly`
(non-canonical forms), `invalidAddress` and `invalidBytes` cases, then regenerate:
`cd test/vectors && npm i --no-save @ensdomains/address-encoder && node generate.mjs`
3. Add the coin to `Harness` in `test/Coders.t.sol`, then add a `test_<coin>_vectors` test and fuzz round-trips.
3. In `test/Coders.t.sol`, add a `test_<coin>_vectors` test, the coinType to `_coinType` and
`test_isSupported`, and fuzz round-trips.
Update the README table.
48 changes: 42 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ human-readable chain addresses to and from the binary form ENS stores in `addr(n

| Library | coinType | Address | Bytes |
| ------------------ | -------- | ---------------------------------------- | ----------------------------------------- |
| `EvmCoder` | 60, `0x80000000 \| chainId`³ | `0x…` (EIP-55 checksum) | 20-byte address |
| `BitcoinCoder` | 0 | `1…` / `3…` / `bc1…` | scriptPubKey |
| `LitecoinCoder` | 2 | `L…` / `M…` / `3…`¹ / `ltc1…` | scriptPubKey |
| `DogecoinCoder` | 3 | `D…` / `9…` / `A…` | scriptPubKey |
Expand All @@ -21,23 +22,55 @@ human-readable chain addresses to and from the binary form ENS stores in `addr(n
| `CardanoCoder` | 1815 | `addr1…` (Shelley), `Ae2…` / `Ddz…` (Byron) | CIP-19 address bytes / Byron CBOR address |
| `ChiaCoder` | 8444 | `xch1…` (bech32m) | 32-byte puzzle hash |

Each library has `encode(bytes) → string`, `decode(string) → bytes` and a `COIN_TYPE` constant.
Every library has the same shape, plus a `COIN_TYPE` constant (`EvmCoder` has `COIN_TYPE_ETH` and
`COIN_TYPE_DEFAULT` instead):

```solidity
function encode(bytes memory data) internal pure returns (bool ok, string memory addr);
function decode(string memory addr) internal pure returns (bool ok, bytes memory data);
```

Neither function reverts (short of running out of gas). Invalid input returns `(false, "")`, so a
contract can handle bad stored bytes or a bad user-supplied address without `try`/`catch`, which
can't wrap `internal` library calls anyway. If you want a revert, add your own:
`if (!ok) revert InvalidAddress();`. Coders whose input has a fixed size (Solana, Chia, Stellar, EVM)
also offer an infallible `encode(bytes32)` / `encode(address, checksum)` that returns a plain `string`. Each
coder's NatSpec lists the specs it implements.

¹ Decode only: `encode` emits the canonical form (`M…` for LTC P2SH, `bitcoincash:…` for BCH). BCH
also accepts CashAddr without the `bitcoincash:` prefix.<br>
² `view`, not `pure`: the SS58 checksum uses the EIP-152 BLAKE2b precompile (`0x09`), which some
L2s / zkEVMs don't implement.
L2s / zkEVMs don't implement. Where it's missing, `encode` and `decode` both return `false`.<br>
³ ENSIP-19 EVM chains, including the default coin type `0x80000000`. All of them use the same EIP-55
format as ETH. `EvmCoder` also has `encode(data, checksum)` / `encode(address, checksum)` (EIP-55 or
lowercase) and `decode(addr, checksum)`. With `checksum`, mixed-case input must be a valid EIP-55
checksum; without it, any case is accepted. The one-argument forms use `checksum = true`.

### `AddressCoder`

One entry point that dispatches by coinType:

```solidity
import {AddressCoder} from "address-coder-sol/AddressCoder.sol";

(bool ok, string memory addr) = AddressCoder.encode(coinType, data); // false for unsupported / invalid
(bool ok, bytes memory data) = AddressCoder.decode(coinType, addr); // false for unsupported / invalid
bool supported = AddressCoder.isSupported(coinType);
```

`AddressCoder` compiles in every coder you reach through it (about 8–9 KB each for `encode` and `decode`). If you
only need a few chains, import their coders directly.

```solidity
import {BitcoinCoder} from "address-coder-sol/BitcoinCoder.sol";

bytes memory script = BitcoinCoder.decode("bc1q..."); // 0x0014...
string memory addr = BitcoinCoder.encode(script);
(bool ok, bytes memory script) = BitcoinCoder.decode("bc1q..."); // 0x0014...
(bool ok, string memory addr) = BitcoinCoder.encode(script);
```

Each coder is its own library of `internal` functions, so only what you call is compiled into your
contract. Each coder adds about 1–3.5 KB per direction; for example, `SolanaCoder.decode` alone is
~1.3 KB and pulls in none of the Bitcoin, bech32 or encode code.
~1.4 KB and pulls in none of the Bitcoin, bech32 or encode code.

Reusable building blocks live in `src/utils`:

Expand All @@ -51,7 +84,9 @@ Reusable building blocks live in `src/utils`:
- `Blake2b`: BLAKE2b-512 using the EIP-152 precompile
- `SS58`: Substrate addresses (single-byte network prefixes)

Invalid input reverts with a custom error.
The utils follow the same rule: decoders return `ok = false` instead of reverting, and so do
encoders that can fail (`Bech32` over its length limit, `CashAddr` with an unsupported hash size,
`Blake2b` without the precompile).

## Differences from the JS reference

Expand All @@ -63,6 +98,7 @@ addresses:
- **BTC / DOGE / TRX / XRP Base58Check:** payloads of the wrong length or with the wrong version byte.
- **Chia:** addresses that don't decode to exactly 32 bytes.
- **Cosmos:** empty account bytes.
- **EVM:** only 20-byte inputs encode. The reference hex-encodes any length.
- **Stellar:** keys that aren't 32 bytes.
- **Cardano:** Shelley addresses that aren't mainnet or that break CIP-19 lengths, reward addresses
under the `addr` prefix, and Byron addresses whose inner bytes aren't a CBOR address (`0x83…`).
Expand Down
81 changes: 81 additions & 0 deletions src/AddressCoder.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {EvmCoder} from "./EvmCoder.sol";
import {BitcoinCoder} from "./BitcoinCoder.sol";
import {SolanaCoder} from "./SolanaCoder.sol";
import {BitcoinCashCoder} from "./BitcoinCashCoder.sol";
import {LitecoinCoder} from "./LitecoinCoder.sol";
import {DogecoinCoder} from "./DogecoinCoder.sol";
import {CosmosCoder} from "./CosmosCoder.sol";
import {XrpCoder} from "./XrpCoder.sol";
import {StellarCoder} from "./StellarCoder.sol";
import {TronCoder} from "./TronCoder.sol";
import {PolkadotCoder} from "./PolkadotCoder.sol";
import {KusamaCoder} from "./KusamaCoder.sol";
import {CardanoCoder} from "./CardanoCoder.sol";
import {ChiaCoder} from "./ChiaCoder.sol";

/// @title AddressCoder
/// @notice Dispatches by ENS coinType to every coder in this package.
/// @dev Opt-in convenience: importing this compiles in every coder you call through it. If you only
/// need one chain, import that `<Chain>Coder` directly instead.
/// `view` because Polkadot/Kusama use the BLAKE2b precompile.
///
/// References:
/// - ENSIP-9 (multichain addresses): https://docs.ens.domains/ensip/9
/// - ENSIP-19 (EVM chain coin types): https://docs.ens.domains/ensip/19
/// - SLIP-44 (coin types): https://github.com/satoshilabs/slips/blob/master/slip-0044.md
/// - Reference: https://github.com/ensdomains/address-encoder/blob/main/src/index.ts
library AddressCoder {
/// @notice Whether `coinType` has a coder.
function isSupported(uint256 coinType) internal pure returns (bool) {
return EvmCoder.isEvmCoinType(coinType) || coinType == BitcoinCoder.COIN_TYPE
|| coinType == SolanaCoder.COIN_TYPE || coinType == BitcoinCashCoder.COIN_TYPE
|| coinType == LitecoinCoder.COIN_TYPE || coinType == DogecoinCoder.COIN_TYPE
|| coinType == CosmosCoder.COIN_TYPE || coinType == XrpCoder.COIN_TYPE || coinType == StellarCoder.COIN_TYPE
|| coinType == TronCoder.COIN_TYPE || coinType == PolkadotCoder.COIN_TYPE
|| coinType == KusamaCoder.COIN_TYPE || coinType == CardanoCoder.COIN_TYPE
|| coinType == ChiaCoder.COIN_TYPE;
}

/// @notice Address bytes -> address string for `coinType`.
/// @return ok False if `coinType` is unsupported or `data` is not valid for it. Never reverts.
function encode(uint256 coinType, bytes memory data) internal view returns (bool ok, string memory addr) {
if (EvmCoder.isEvmCoinType(coinType)) return EvmCoder.encode(data);
if (coinType == BitcoinCoder.COIN_TYPE) return BitcoinCoder.encode(data);
if (coinType == SolanaCoder.COIN_TYPE) return SolanaCoder.encode(data);
if (coinType == BitcoinCashCoder.COIN_TYPE) return BitcoinCashCoder.encode(data);
if (coinType == LitecoinCoder.COIN_TYPE) return LitecoinCoder.encode(data);
if (coinType == DogecoinCoder.COIN_TYPE) return DogecoinCoder.encode(data);
if (coinType == CosmosCoder.COIN_TYPE) return CosmosCoder.encode(data);
if (coinType == XrpCoder.COIN_TYPE) return XrpCoder.encode(data);
if (coinType == StellarCoder.COIN_TYPE) return StellarCoder.encode(data);
if (coinType == TronCoder.COIN_TYPE) return TronCoder.encode(data);
if (coinType == PolkadotCoder.COIN_TYPE) return PolkadotCoder.encode(data);
if (coinType == KusamaCoder.COIN_TYPE) return KusamaCoder.encode(data);
if (coinType == CardanoCoder.COIN_TYPE) return CardanoCoder.encode(data);
if (coinType == ChiaCoder.COIN_TYPE) return ChiaCoder.encode(data);
return (false, "");
}

/// @notice Address string -> address bytes for `coinType`.
/// @return ok False if `coinType` is unsupported or `addr` is not valid for it. Never reverts.
function decode(uint256 coinType, string memory addr) internal view returns (bool ok, bytes memory data) {
if (EvmCoder.isEvmCoinType(coinType)) return EvmCoder.decode(addr);
if (coinType == BitcoinCoder.COIN_TYPE) return BitcoinCoder.decode(addr);
if (coinType == SolanaCoder.COIN_TYPE) return SolanaCoder.decode(addr);
if (coinType == BitcoinCashCoder.COIN_TYPE) return BitcoinCashCoder.decode(addr);
if (coinType == LitecoinCoder.COIN_TYPE) return LitecoinCoder.decode(addr);
if (coinType == DogecoinCoder.COIN_TYPE) return DogecoinCoder.decode(addr);
if (coinType == CosmosCoder.COIN_TYPE) return CosmosCoder.decode(addr);
if (coinType == XrpCoder.COIN_TYPE) return XrpCoder.decode(addr);
if (coinType == StellarCoder.COIN_TYPE) return StellarCoder.decode(addr);
if (coinType == TronCoder.COIN_TYPE) return TronCoder.decode(addr);
if (coinType == PolkadotCoder.COIN_TYPE) return PolkadotCoder.decode(addr);
if (coinType == KusamaCoder.COIN_TYPE) return KusamaCoder.decode(addr);
if (coinType == CardanoCoder.COIN_TYPE) return CardanoCoder.decode(addr);
if (coinType == ChiaCoder.COIN_TYPE) return ChiaCoder.decode(addr);
return (false, "");
}
}
25 changes: 15 additions & 10 deletions src/BitcoinCashCoder.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,21 @@ import {CashAddr} from "./utils/CashAddr.sol";
/// @dev `decode` accepts CashAddr ("bitcoincash:q...", "bitcoincash:p...", prefix optional, either case)
/// and legacy Base58Check ("1...", "3..."). `encode` always emits CashAddr with the prefix.
/// Only 20-byte P2PKH / P2SH are supported (not P2SH32).
///
/// References:
/// - CashAddr: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md
/// - P2SH32 (unsupported): https://gitlab.com/0353F40E/p2sh32
/// - Reference: https://github.com/ensdomains/address-encoder/blob/main/src/coin/bch.ts
library BitcoinCashCoder {
error UnrecognisedAddressFormat();

uint256 internal constant COIN_TYPE = 145;

bytes internal constant PREFIX = "bitcoincash";
uint8 internal constant P2PKH_VERSION = 0x00;
uint8 internal constant P2SH_VERSION = 0x05;

/// @notice scriptPubKey -> "bitcoincash:..." address string.
function encode(bytes memory script) internal pure returns (string memory) {
/// @return ok False if `script` is not P2PKH or P2SH.
function encode(bytes memory script) internal pure returns (bool ok, string memory addr) {
uint256 n = script.length;
if (
n == 25 && script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 && script[23] == 0x88
Expand All @@ -30,22 +34,23 @@ library BitcoinCashCoder {
if (n == 23 && script[0] == 0xa9 && script[1] == 0x14 && script[22] == 0x87) {
return CashAddr.encode(PREFIX, 1, _slice20(script, 2));
}
revert UnrecognisedAddressFormat();
return (false, "");
}

/// @notice Address string -> scriptPubKey.
function decode(string memory addr) internal pure returns (bytes memory) {
/// @return ok False if `addr` is not a valid address.
function decode(string memory addr) internal pure returns (bool ok, bytes memory script) {
bytes memory b = bytes(addr);
if (b.length != 0 && (b[0] == "1" || b[0] == "3")) {
return BitcoinLike.decodeLegacy(addr, P2PKH_VERSION, P2SH_VERSION);
}
(uint256 kind, bytes memory hash) = CashAddr.decode(PREFIX, addr);
if (hash.length != 20) revert UnrecognisedAddressFormat();
(bool valid, uint256 kind, bytes memory hash) = CashAddr.decode(PREFIX, addr);
if (!valid || hash.length != 20) return (false, "");
// OP_DUP OP_HASH160 <20> OP_EQUALVERIFY OP_CHECKSIG
if (kind == 0) return abi.encodePacked(hex"76a914", hash, hex"88ac");
if (kind == 0) return (true, abi.encodePacked(hex"76a914", hash, hex"88ac"));
// OP_HASH160 <20> OP_EQUAL
if (kind == 1) return abi.encodePacked(hex"a914", hash, hex"87");
revert UnrecognisedAddressFormat();
if (kind == 1) return (true, abi.encodePacked(hex"a914", hash, hex"87"));
return (false, "");
}

function _slice20(bytes memory b, uint256 offset) private pure returns (bytes memory out) {
Expand Down
16 changes: 14 additions & 2 deletions src/BitcoinCoder.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ import {BitcoinLike} from "./utils/BitcoinLike.sol";
/// @notice Bitcoin (coinType 0) address <-> scriptPubKey bytes, as used by ENS `addr(node, 0)`.
/// @dev `decode`: "1...", "3..." or "bc1..." -> scriptPubKey. `encode`: scriptPubKey -> address.
/// Supported scripts: P2PKH, P2SH and SegWit v0-v16 (P2WPKH, P2WSH, P2TR, ...).
///
/// References:
/// - Base58Check: https://en.bitcoin.it/wiki/Base58Check_encoding
/// - BIP-13 (P2SH addresses): https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki
/// - BIP-141 (witness programs): https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
/// - BIP-173 (bech32): https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
/// - BIP-350 (bech32m): https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
/// - Address prefixes: https://github.com/bitcoin/bitcoin/blob/master/src/kernel/chainparams.cpp
/// - ENSIP-9 (multichain addresses): https://docs.ens.domains/ensip/9
/// - Reference: https://github.com/ensdomains/address-encoder/blob/main/src/coin/btc.ts
library BitcoinCoder {
uint256 internal constant COIN_TYPE = 0;

Expand All @@ -15,12 +25,14 @@ library BitcoinCoder {
uint8 internal constant P2SH_VERSION = 0x05;

/// @notice scriptPubKey -> address string.
function encode(bytes memory script) internal pure returns (string memory) {
/// @return ok False if `script` is not P2PKH, P2SH or a valid SegWit output.
function encode(bytes memory script) internal pure returns (bool ok, string memory addr) {
return BitcoinLike.encode(script, HRP, P2PKH_VERSION, P2SH_VERSION);
}

/// @notice Address string -> scriptPubKey.
function decode(string memory addr) internal pure returns (bytes memory) {
/// @return ok False if `addr` is not a valid address.
function decode(string memory addr) internal pure returns (bool ok, bytes memory data) {
return BitcoinLike.decode(addr, HRP, P2PKH_VERSION, P2SH_VERSION);
}
}
Loading