8000 feat(signing): recover signmessage signers by aeitwoen · Pull Request #180 · agntn/keys · GitHub
[go: up one dir, main page]

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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ keys/
| CashAddr P2PKH | `src/utils/bitcoin.ts` → `AbstractCashAddrBlockchain` | A prefix per network and the hash lengths each type pays to, as BCH and eCash use |
| Add EVM chain | `src/utils/evm.ts` → `AbstractEVMBlockchain` | Minimal subclass with `name` and `bip44` |
| Fix signing | `src/utils/signing.ts` (generic) or `evm.ts`/`ed25519-chains.ts` (chain-specific) | EVM uses preamble hash, ed25519 signs raw |
| Core signature | `src/utils/secp256k1/compact-signature.ts` | Base64 `header | | r | | s`for the Bitcoin family and Decred;`recoverMessageSigner` reads it |
| Change public API | `src/index.ts` | Re-exports only, never add logic here |
| Change agent tools | `src/tools.ts`, `src/tool-schemas.ts`, `src/tool-operations.ts` | One definition per tool; a new tool also gets its file in `docs/server/mcp/tools/` |
| Add BIP/derivation | `src/utils/bip32/`, `bip39/`, `bip44/`, `slip10/` | Subdirs with index.ts |
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ The docs live at [keys.agntn.dev](https://keys.agntn.dev), keyspace explorer inc
- 👀 **An xpub is enough to watch.** Hand over an account's xpub, ypub or zpub and get the address at `m/0/5`, no secret anywhere in the call.
- 🧩 **Puzzle mnemonics are welcome.** Wrong checksum? Derive anyway and get a warning with the wallet, or ask which words would make it valid.
- 🌍 **All ten BIP39 word lists.** Look a word up in Italian, generate in Japanese with the ideographic spaces, map indices from base 0 or base 1.
- ✍️ **Signing on both curves.** Bitcoin, Bitcoin Cash, Bitcoin Gold, Bitcoin SV, Litecoin, Dash, Decred, Dogecoin, Zcash and eCash hash the message the way Core does, EVM chains the way ethers does, TRON the way TronWeb's `signMessageV2` does, Sui the way the Sui SDK's `signPersonalMessage` does on either curve, Stellar the way the Stellar SDK's `signMessage` does under SEP-53, and Solana, Aptos and Cardano sign the raw bytes. What comes back is 64 bytes of compact `r||s` hex, so it's not Core's base64.
- 🔁 **`v` when you need it.** `{ recovered: true }` on Ethereum, Base or TRON gives 65 bytes of `r||s||v`, byte for byte what ethers and TronWeb produce. Skip it and ethers reads your 64 bytes as an EIP-2098 compact signature and answers with the wrong address instead of an error.
- ✍️ **Signing on both curves.** Bitcoin, Bitcoin Cash, Bitcoin Gold, Bitcoin SV, Litecoin, Dash, Decred, Dogecoin, Zcash and eCash hash the message the way Core does, EVM chains the way ethers does, TRON the way TronWeb's `signMessageV2` does, Sui the way the Sui SDK's `signPersonalMessage` does on either curve, Stellar the way the Stellar SDK's `signMessage` does under SEP-53, and Solana, Aptos and Cardano sign the raw bytes. By default you get 64 bytes of compact `r||s` hex.
- 🔁 **The signer rides along.** `{ recovered: true }` gives 65 bytes of `r||s||v` on Ethereum, Base and TRON, and the base64 `bitcoin-cli signmessage` prints on the Bitcoin family and Decred. Skip it on Ethereum and ethers reads your 64 bytes as EIP-2098 compact, then answers with the wrong address instead of an error.
- 🔌 **Loads one chain at a time.** `blockchains.solana()()` imports Solana and nothing else, so a Bitcoin tool never pays for Cardano.
- 🤖 **Tools for your agent.** MCP over stdio, MCP over HTTP from [keys.agntn.dev/mcp](https://keys.agntn.dev/guide#remote-mcp) and a Pi extension run the same code, and a generated mnemonic comes back with a note that it's in the transcript now.

Expand Down Expand Up @@ -168,6 +168,8 @@ Without the flag `deriveHDWallet` throws. With it you get the wallet and a warni

Brainwallets are a puzzle favorite too, and the salted kind hides a trap. brainwallet.io runs scrypt, then SHA-256 over the hex of the result, not its bytes. Miss that and you get a valid key to the wrong address. `derive` from `@agntn/keys/brainwallet` takes the whole recipe: KDF, costs, salt and what SHA-256 reads. Agents get `keys_brainwallet_derive`. It answers with the public key, the address and a match against your target. Never the private key. Recipes: [Wallets](https://keys.agntn.dev/guide/wallets).

And a signed message is a clue. Somebody proves they hold an address with `signmessage`? That base64 gives away the public key behind it. `btc.recoverMessageSigner(message, signature)` reads it back, `keys_message_recover` does the same for agents. Any well formed signature recovers some key for any message, though. So check the address match, not just that a key came out.

## ⛓️ Chains

| Chain | Curve | Address Formats | Testnet |
Expand Down
16 changes: 15 additions & 1 deletion docs/content/2.blockchains/bitcoin.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,21 @@ Version `0x80` on mainnet, `0xef` on testnet, a trailing `0x01` when the public

## Signing

`signMessage` hashes with the `"\x18Bitcoin Signed Message:\n"` preamble, the same one Bitcoin Core uses, and signs with secp256k1. What comes back is 64 bytes of `r||s` in hex, no recovery byte, and `verifyMessage` checks it against the public key. It isn't the base64 recoverable format `bitcoin-cli signmessage` prints, so don't paste one into the other. `{ recovered: true }` throws here for the same reason: Core writes its header first and encodes the whole thing as base64, so Ethereum's `r||s||v` would be a format no Bitcoin tool reads.
`signMessage` hashes with the `"\x18Bitcoin Signed Message:\n"` preamble, the one Bitcoin Core uses, and signs with secp256k1. By default you get 64 bytes of `r||s` hex. `verifyMessage` checks it against the public key.

`bitcoin-cli signmessage` prints something else. Base64, with a header byte in front of `r||s` that says how to get the key back. Ask for that one with `recovered`:

```js
const signature = bitcoinChain.signMessage("hello", privateKey, { recovered: true });
// base64, byte for byte what signmessagewithprivkey prints for the same key
bitcoinChain.verifyMessage("hello", signature, publicKey); // true

const signer = bitcoinChain.recoverMessageSigner("hello", signature);
// { publicKey: "02...", addressType: "legacy" }
bitcoinChain.getAddress(signer.publicKey, signer.addressType); // 1...
```

Got a signature and an address, but no key? That's what `recoverMessageSigner` is for. The header sets the key's encoding and, under BIP137, its address type. 27 to 34 is P2PKH, 35 to 38 P2SH-P2WPKH, 39 to 42 P2WPKH. Electrum ignores that and signs SegWit under a P2PKH header, so `keys_message_recover` matches a compressed key from such a header against all three. One catch. Any well formed signature recovers some key for any message. Wrong message, different key, no error. The address match is the real check.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/bitcoincash.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ WIF is Bitcoin's too, prefix `0x80`. `encode(privateKey, { chain: "bitcoin" })`

## Signing

Bitcoin Cash Node kept Bitcoin's `"\x18Bitcoin Signed Message:\n"`, so the digest is identical: compact size lengths, double SHA-256, secp256k1. A Bitcoin Cash signature and a Bitcoin signature over the same key and message are the same 64 bytes of `r||s` hex. Like Bitcoin, `{ recovered: true }` throws, because the node's recoverable form is base64 with a header byte.
Bitcoin Cash Node kept Bitcoin's `"\x18Bitcoin Signed Message:\n"`, so the digest is identical: compact size lengths, double SHA-256, secp256k1. A Bitcoin Cash signature and a Bitcoin signature over the same key and message are the same 64 bytes of `r||s` hex. Same story with `{ recovered: true }`: you get the base64 with a header byte, the string Bitcoin gives. `recoverMessageSigner` reads the key back, and `getAddress` turns it into the CashAddr.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/bitcoingold.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ WIF is Bitcoin's, prefix `0x80` on mainnet and `0xef` on testnet. `encode(privat

## Signing

The node signs with `"\x1dBitcoin Gold Signed Message:\n"`, so a Bitcoin signature doesn't verify here and the other way round. The rest is Core's recipe: compact size lengths, double SHA-256, secp256k1. What comes back is 64 bytes of `r||s` hex. The node's own `rpc_signmessage.py` vector matches byte for byte once you drop the header byte from its base64. `{ recovered: true }` throws, like on Bitcoin.
The node signs with `"\x1dBitcoin Gold Signed Message:\n"`, so a Bitcoin signature doesn't verify here and the other way round. The rest is Core's recipe: compact size lengths, double SHA-256, secp256k1. What comes back is 64 bytes of `r||s` hex. The node's own `rpc_signmessage.py` vector matches byte for byte once you drop the header byte from its base64. Or keep it. `{ recovered: true }` gives the whole base64, header and all, exactly what the node prints.

The replay protection Bitcoin Gold added at the fork, `SIGHASH_FORKID`, is about transactions. Signed messages never had it, and this library doesn't sign transactions anyway.

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/bitcoinsv.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ WIF is Bitcoin's too, prefix `0x80`. `encode(privateKey, { chain: "bitcoin" })`

## Signing

The node kept `"\x18Bitcoin Signed Message:\n"`, so the digest is Bitcoin's: compact size lengths, double SHA-256, secp256k1. A Bitcoin SV signature is the same 64 bytes of `r||s` hex that Bitcoin gives for that key and message. The `BSM` vectors in the BSV Blockchain ts-sdk match byte for byte once you drop their header byte. Like Bitcoin, `{ recovered: true }` throws, because the recoverable form is base64 with that header byte in front.
The node kept `"\x18Bitcoin Signed Message:\n"`, so the digest is Bitcoin's: compact size lengths, double SHA-256, secp256k1. A Bitcoin SV signature is the same 64 bytes of `r||s` hex that Bitcoin gives for that key and message. The `BSM` vectors in the BSV Blockchain ts-sdk match byte for byte once you drop their header byte. With `{ recovered: true }` you don't drop anything, it gives the ts-sdk's base64 string as is.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/dash.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Version `0xcc` on mainnet, so compressed keys start with `X` and uncompressed on

## Signing

Dash was DarkCoin until 2015, and the message preamble never got the rename. Dash Core signs under `"\x19DarkCoin Signed Message:\n"` to this day, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. So a Bitcoin signature doesn't verify here, and the other way round. The `message_sign` case in Dash Core's `util_tests.cpp` matches byte for byte once you drop its header byte. `{ recovered: true }` throws, same as on Bitcoin.
Dash was DarkCoin until 2015, and the message preamble never got the rename. Dash Core signs under `"\x19DarkCoin Signed Message:\n"` to this day, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. So a Bitcoin signature doesn't verify here, and the other way round. The `message_sign` case in Dash Core's `util_tests.cpp` matches byte for byte once you drop its header byte. Ask for `{ recovered: true }` and the header stays, so you get Dash Core's base64 exactly.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/decred.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Decred WIF has its own layout: two prefix bytes, a scheme byte that's `0x00` for

## Signing

`"Decred Signed Message:\n"` with compact size lengths in front of the preamble and the message, one round of BLAKE-256, then secp256k1. 64 bytes of `r||s` in hex, verified with `verifyMessage` on the same driver.
`"Decred Signed Message:\n"` with compact size lengths in front of the preamble and the message, one round of BLAKE-256, then secp256k1. 64 bytes of `r||s` in hex, verified with `verifyMessage` on the same driver. `{ recovered: true }` gives dcrd's base64 with a header byte, and both of dcrd's `verifymessage` vectors come out byte for byte. dcrd stops at header 34, so `recoverMessageSigner` throws on the BIP137 headers above it.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/dogecoin.md
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Version `0x9e` on mainnet, so compressed keys start with `Q` and uncompressed on

## Signing

Dogecoin Core signs under `"\x19Dogecoin Signed Message:\n"`, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. So a Bitcoin signature doesn't verify here, and the other way round. The Dogecoin vectors in bitcoinjs-message match byte for byte once you drop their header byte. `{ recovered: true }` throws, same as on Bitcoin.
Dogecoin Core signs under `"\x19Dogecoin Signed Message:\n"`, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. So a Bitcoin signature doesn't verify here, and the other way round. The Dogecoin vectors in bitcoinjs-message match byte for byte once you drop their header byte. `{ recovered: true }` keeps it and gives their base64 whole, the uncompressed one too with `compressed: false`.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/ecash.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ WIF is Bitcoin's, prefix `0x80`. `encode(privateKey, { chain: "bitcoin" })` from

This is where eCash and Bitcoin Cash part ways. Bitcoin ABC signs under `"\x16eCash Signed Message:\n"`, not Bitcoin's preamble. The digest is built the usual way, compact size lengths and double SHA-256, but with a different preamble the hash is different. A Bitcoin Cash signature doesn't verify here and the other way around.

The signature is 64 bytes of `r||s` hex. A signature from ecash-lib verifies, but don't expect the same bytes from the same key, because ecash-lib picks a different nonce. `{ recovered: true }` throws, like on Bitcoin, since the node's recoverable form is base64 with a header byte.
The signature is 64 bytes of `r||s` hex. A signature from ecash-lib verifies, but don't expect the same bytes from the same key, because ecash-lib picks a different nonce. `{ recovered: true }` gives the node's base64 with a header byte, and `recoverMessageSigner` gets ecash-lib's key back out of its signature.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/litecoin.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Version `0xb0` on mainnet, so compressed keys start with `T` and uncompressed on

## Signing

Same construction as Bitcoin with `"\x19Litecoin Signed Message:\n"` in front: double SHA-256, secp256k1, 64 bytes of `r||s` in hex. A Bitcoin signature over the same key and message is a different string because the preamble differs, so verify with the chain that signed.
Same construction as Bitcoin with `"\x19Litecoin Signed Message:\n"` in front: double SHA-256, secp256k1, 64 bytes of `r||s` in hex. A Bitcoin signature over the same key and message is a different string because the preamble differs, so verify with the chain that signed. `{ recovered: true }` gives Litecoin Core's base64, byte for byte its `signmessagewithprivkey` vector.

## Where it lives

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/zcash.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ WIF works without a Zcash entry. Zcash kept Bitcoin's `0x80` and `0xef`, so `dec

## Signing

zcashd signs under `"\x16Zcash Signed Message:\n"`, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. Only the preamble differs, and that's enough for a Bitcoin signature to fail here. The tests take the signature from Zallet's `verifymessage` test, recover its key, get Zallet's `t1` address back and verify it. `{ recovered: true }` throws, same as on Bitcoin.
zcashd signs under `"\x16Zcash Signed Message:\n"`, then does what Bitcoin does: compact size lengths, double SHA-256, secp256k1. Only the preamble differs, and that's enough for a Bitcoin signature to fail here. The tests take the signature from Zallet's `verifymessage` test, recover its key, check that `recoverMessageSigner` finds the same one, get Zallet's `t1` address back and verify it. `{ recovered: true }` writes that same base64 form.

## Where it lives

Expand Down
1 change: 1 addition & 0 deletions docs/server/mcp/tools/keys-message-recover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default keysMcpTool("keys_message_recover");
1 change: 1 addition & 0 deletions packages/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Pi coding agent extension exposing the [`@agntn/keys`](../../README.md) library
| `keys_address_validate` | Check if an address is valid for a chain |
| `keys_message_sign` | Sign a message with a private key (secp256k1/ed25519) |
| `keys_message_verify` | Verify a signature against message + public key |
| `keys_message_recover` | Recover key + address from a `signmessage` base64 signature |
| `keys_bip44_parse` | Parse a BIP44 path into its levels |
| `keys_bip44_generate` | Generate the derivation path a chain's wallets use |

Expand Down
13 changes: 13 additions & 0 deletions src/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
HDWalletOptions,
KeyOptions,
Keys,
MessageSigner,
Options,
SigningOptions,
Wallet,
Expand Down Expand Up @@ -210,6 +211,18 @@ export abstract class AbstractBlockchain implements Blockchain {
...(type === undefined ? {} : { addressType: type }),
};
}

/**
* Recover the signer of a base64 signature, which only the Bitcoin family and Decred write.
* @param _message - The signed message
* @param _signature - Base64 of the header byte, then `r` and `s`
* @returns {MessageSigner} The recovered public key and the address type the header names
*/
recoverMessageSigner(_message: string | Uint8Array, _signature: string): MessageSigner {
throw new Error(
`${this.name} does not write Core style base64 signatures, so it has no signer to recover`,
);
}
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/blockchains/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Decred uses `AbstractBlockchain` directly: ECDSA P2PKH with BLAKE-256, not Bitco
## PATTERNS

- **Bitcoin base class** - `AbstractBitcoinBlockchain` in `utils/bitcoin.ts` shares address generation and HD purpose inference on top of the keys and Core message signing in `AbstractBitcoinMessageBlockchain`. Litecoin keeps only its network table, its preamble and a validation that accepts both P2SH prefix generations.
- **Core signatures** - `{ recovered: true }` on the Bitcoin family and Decred writes base64 of a header byte, then `r` and `s`, through `utils/secp256k1/compact-signature.ts`; `verifyMessage` takes it and `recoverMessageSigner` reads its key and BIP137 address type. Decred refuses the BIP137 headers dcrd never reads, and every other chain throws from the base class
- **CashAddr P2PKH** - `AbstractCashAddrBlockchain` in `utils/bitcoin.ts` sits on the keys and signing half of the Bitcoin base and writes P2PKH as CashAddr through `utils/cashaddr.ts`. It owns the mainnet and testnet check, `legacy` only `getAddress` and a validation that refuses base58. A subclass passes its label and a `CASHADDR_PARAMS` table: the prefix of each network and the hash lengths its node pays to, by type
- **Bitcoin Cash** - `BitcoinCash` extends the CashAddr base under `bitcoincash` and `bchtest`. Validation follows Bitcoin Cash Node, CashTokens types and 32 byte script hashes included
- **eCash** - `ECash` extends the CashAddr base under `ecash` and `ectest` with Bitcoin ABC's `eCash` preamble. Validation follows Bitcoin ABC, which pays to 20 byte hashes under types 0 and 1 only, so the CashTokens types are refused. `bip44` is SLIP-0044's 899; Cashtab's 1899 and the older 145 paths go through `deriveHDWallet` as given
Expand Down
Loading
Loading
0