8000 feat(solana): read keypair files by oritwoen · Pull Request #432 · agntn/keys · GitHub
[go: up one dir, main page]

Skip to content
Merged
8000
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ Most of them need nothing past the loader. A few have opinions:

- Cosmos takes a `prefix`, so `blockchains.cosmos({ prefix: "osmo" })()` writes Osmosis addresses.
- Polkadot takes `ss58Prefix`, 2 for Kusama. It writes sr25519 like the wallets, until `addressType: "ed25519"` says otherwise.
- Monero, TON and the XRP Ledger restore from their own seeds through `deriveSeedWallet`.
- Monero, TON and the XRP Ledger restore from their own seeds through `deriveSeedWallet`. Solana uses the same method for the `id.json` that `solana-keygen` writes or Phantom's base58 secret.
- TON writes one address per wallet contract, so `addressType` picks `v4r2`, `v5r1` or `v3r2`.
- Decred and Cardano refuse `deriveHDWallet` on purpose.

Expand Down
13 changes: 13 additions & 0 deletions docs/content/2.blockchains/solana.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ solanaChain.deriveHDWallet(mnemonic, { path: "m/44'/501'/0'/0'" }).address;

A path with an unhardened segment throws before derivation, there isn't a soft child to give you. Phantom and Solflare use exactly this shape, so the first account matches what those wallets show. `solanaChain.getDerivationPath({ account: 1 })` gives the next one, `m/44'/501'/1'/0'`.

## Keypair files

Got the `id.json` the Solana CLI writes, or a secret exported from Phantom or Solflare? Pass it straight to `deriveSeedWallet`. No slicing bytes by hand first.

```js
solanaChain.deriveSeedWallet("2Ana1pUpv2ZbMVkwF5FXapYeBEjdxDatLn7nvJkhgTSdZd8hbDHTd21as7EAsg7ypityqfsw2pMQKJcVDVcAEsd").address;
// 9C6hybhQ6Aycep9jaUnP6uL9ZYvDjUp1aSkFWPUFJtpj, and the id.json array of the same 64 bytes gives the same
```

The seed in this public test vector just counts from 1 to 32. The other half is the public key, so the file carries its own answer key. Halves that don't match throw instead of handing you some other address.

You get `keys.private` as the 32-byte seed in hex, the key every other Solana method here takes. `keys_wallet_derive` reads both forms as `privateKey` too.

## Signing

`signMessage` is a plain ed25519 signature over the message bytes, hex encoded, and `verifyMessage` checks it against the public key. That is the format `nacl.sign.detached` produces, minus the base58 wrapper some wallets add on top.
4 changes: 2 additions & 2 deletions src/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,8 @@ export abstract class AbstractBlockchain implements Blockchain {
}

/**
* Derives a wallet from the chain's own seed string, which only the XRP Ledger and Monero have:
* a family seed (`s...`) and 25 seed words. Every other chain takes a private key or BIP39 words.
* Derives a wallet from the chain's own seed string: an XRPL family seed (`s...`), Monero's 25
* words, TON's 24 or a full Solana secret. Every other chain takes a private key or BIP39 words.
* @param _seed - The seed string
* @param _options - Key options of the wallet and the address type to write
* @returns {Wallet} The wallet behind the seed
Expand Down
60 changes: 59 additions & 1 deletion src/blockchains/solana.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import { base58 } from "@agntn/encodings/base58";
import { equalBytes } from "../utils/bytes.ts";
import { decodeKeyPublic } from "../utils/ed25519.ts";
import { AbstractEd25519Blockchain } from "../utils/ed25519-chains.ts";
import { BIP44 } from "../utils/bip44/index.ts";
import { BIP44Change, getHardenedPath } from "../utils/bip44/paths.ts";
import { readPathOptions } from "../utils/options.ts";
import type { AddressType, DerivationPathOptions } from "../types.ts";
import type { AddressType, DerivationPathOptions, Wallet, WalletOptions } from "../types.ts";

/**
* Reads the 64 bytes of a Solana CLI keypair file.
* @param text - The file's contents
* @returns {Uint8Array} The bytes, undefined for anything else
*/
function readKeypairArray(text: string): Uint8Array | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return undefined;
}
if (!Array.isArray(parsed) || parsed.length !== 64) return undefined;
const bytes = parsed.filter(
(value): value is number => Number.isInteger(value) && value >= 0 && value <= 255,
);
return bytes.length === 64 ? Uint8Array.from(bytes) : undefined;
}

/**
* Reads a 64-byte Solana secret as base58, as Phantom exports it.
* @param text - The secret
* @returns {Uint8Array} The bytes, undefined for anything else
*/
function readKeypairBase58(text: string): Uint8Array | undefined {
try {
const bytes = base58.decode(text);
return bytes.length === 64 ? bytes : undefined;
} catch {
return undefined;
}
}

/** Solana blockchain implementation. */
export class Solana extends AbstractEd25519Blockchain {
Expand Down Expand Up @@ -34,6 +68,30 @@ export class Solana extends AbstractEd25519Blockchain {
return base58.encode(decodeKeyPublic(keyPublic, "Solana"));
}

/**
* Restores a wallet from `id.json` or Phantom's base58 export: the seed, then its public key.
* @param seed - The 64-byte secret as a JSON array or base58
* @param options - Key options of the wallet
* @returns {Wallet} The wallet, keyed by the 32-byte seed
* @throws {RangeError} On another shape, or a public half from another key
*/
override deriveSeedWallet(seed: string, options?: WalletOptions): Wallet {
const text = seed.trim();
const bytes = text.startsWith("[") ? readKeypairArray(text) : readKeypairBase58(text);
if (bytes === undefined) {
throw new RangeError(
"A Solana secret is 64 bytes: a JSON array of numbers as in id.json, or base58",
);
}
const wallet = this.deriveWallet(bytes.subarray(0, 32).toHex(), options);
if (!equalBytes(Uint8Array.fromHex(wallet.keys.public), bytes.subarray(32))) {
throw new RangeError(
"The last 32 bytes of this Solana secret are not the public key its seed derives",
);
}
return wallet;
}

override validateAddress(address: string): boolean {
try {
return base58.decode(address).length === 32;
Expand Down
20 changes: 15 additions & 5 deletions src/tool-operations/wallet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { blockchains } from "../_blockchains.ts";
import type { AbstractBlockchain } from "../blockchain.ts";
import { FAMILY_SEED_SCHEMA_PATTERN, MAX_WALLET_SECRET_LENGTH } from "../tool-parameters.ts";
import {
FAMILY_SEED_SCHEMA_PATTERN,
MAX_WALLET_SECRET_LENGTH,
SOLANA_SECRET_SCHEMA_PATTERN,
} from "../tool-parameters.ts";
import type { KeyOptions, Wallet } from "../types.ts";
import {
SEED_WORDS,
Expand Down Expand Up @@ -45,6 +49,8 @@ export interface DerivedWalletDetails {

const FAMILY_SEED = new RegExp(FAMILY_SEED_SCHEMA_PATTERN, "u");

const SOLANA_SECRET = new RegExp(SOLANA_SECRET_SCHEMA_PATTERN, "u");

/** Chains whose wallets restore from seed words of their own rather than BIP39. */
const SEED_WORD_CHAINS: ReadonlySet<string> = new Set(["monero", "ton"]);

Expand Down Expand Up @@ -113,7 +119,8 @@ interface SecretWalletRequest {
}

/**
* Derives a wallet from an XRPL family seed, Monero or TON seed words, or a private key in hex.
* Derives a wallet from an XRPL family seed, Monero or TON seed words, a full Solana secret, or a
* private key in hex.
* @param blockchain - The chain to derive on
* @param request - The secret, key options and the address type the caller asked for
* @returns {Wallet} The wallet
Expand All @@ -123,7 +130,9 @@ function secretWallet(
request: SecretWalletRequest,
): Wallet {
const { secret, options, addressType } = request;
if (FAMILY_SEED.test(secret) || SEED_WORDS.test(secret)) {
const solanaSecret =
blockchain.name === "solana" && !PRIVATE_KEY_HEX.test(secret) && SOLANA_SECRET.test(secret);
if (FAMILY_SEED.test(secret) || SEED_WORDS.test(secret) || solanaSecret) {
return blockchain.deriveSeedWallet(secret, { ...options, addressType });
}
if (blockchain.name === "polkadot") {
Expand All @@ -135,7 +144,8 @@ function secretWallet(
const keyPrivate = hexArgument(secret, {
name: "Private key",
pattern: PRIVATE_KEY_HEX,
shape: "64 hex characters, a family seed (s...) on xrpl or the seed words on monero and ton,",
shape:
"64 hex characters, a family seed (s...) on xrpl, the seed words on monero and ton, a 64-byte secret on solana,",
});
return blockchain.deriveWallet(keyPrivate, { ...options, addressType });
}
Expand Down Expand Up @@ -167,7 +177,7 @@ async function moneroSubaddressWallet(

/** Wallet tool arguments besides the chain, raw until the executor checks them. */
export interface WalletArguments extends Omit<ChainArguments, "coinType">, SubaddressArguments {
/** Private key as hex, a family seed on xrpl or the seed words on monero and ton. */
/** Private key as hex, or the chain's own seed or secret. */
readonly privateKey?: unknown;
/** secp256k1 public key form, compressed by default. */
readonly compressed?: unknown;
Expand Down
12 changes: 9 additions & 3 deletions src/tool-parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,12 @@ export const SIGNING_KEY_SCHEMA_PATTERN = "^(?:[0-9A-Fa-f]{64}){1,2}$";
/** JSON Schema pattern for an XRPL family seed: `s...` for secp256k1, `sEd...` for ed25519. */
export const FAMILY_SEED_SCHEMA_PATTERN = "^s[1-9A-HJ-NP-Za-km-z]{28,30}$";

/** A 64-byte Solana secret, as id.json or base58, pasted with or without whitespace around it. */
const SOLANA_SECRET = "\\s*(?:\\[[0-9,\\s]+\\]|[1-9A-HJ-NP-Za-km-z]{64,88})\\s*";

/** JSON Schema pattern for a 64-byte Solana secret, as id.json or base58. */
export const SOLANA_SECRET_SCHEMA_PATTERN = `^${SOLANA_SECRET}$`;

/** Longest secret `keys_wallet_derive` reads, room for 25 seed words with loose spacing. */
export const MAX_WALLET_SECRET_LENGTH = 1024;

Expand All @@ -318,10 +324,10 @@ export const MONERO_PAYMENT_ID_SCHEMA_PATTERN = "^[0-9A-Fa-f]{16}$";

/**
* JSON Schema pattern for the secret a wallet is derived from: a private key, a Polkadot sr25519
* secret, an XRPL family seed, or Monero or TON seed words.
* secret, an XRPL family seed, Monero or TON seed words, or a 64-byte Solana secret as the
* id.json array or base58.
*/
export const WALLET_SECRET_SCHEMA_PATTERN =
"^(?:(?:[0-9A-Fa-f]{64}){1,2}|s[1-9A-HJ-NP-Za-km-z]{28,30}|\\s*[A-Za-z]+(?:\\s+[A-Za-z]+){23,24}\\s*)$";
export const WALLET_SECRET_SCHEMA_PATTERN = `^(?:(?:[0-9A-Fa-f]{64}){1,2}|s[1-9A-HJ-NP-Za-km-z]{28,30}|\\s*[A-Za-z]+(?:\\s+[A-Za-z]+){23,24}\\s*|${SOLANA_SECRET})$`;

/**
* JSON Schema pattern for a 32-byte ed25519 key, XRPL's 33-byte `ED` form of one, or a compressed
Expand Down
2 changes: 1 addition & 1 deletion src/tool-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ export const DERIVE_WALLET_PARAMETERS = Type.Object(
pattern: WALLET_SECRET_SCHEMA_PATTERN,
maxLength: MAX_WALLET_SECRET_LENGTH,
description:
"Private key as 64 hex characters without 0x. On polkadot also the 128-character sr25519 secret of an account past a /soft junction. On xrpl also a family seed: s... for secp256k1, sEd... for ed25519. On monero also the 25 seed words, on ton the 24 words TON wallets write",
"Private key as 64 hex characters without 0x. On polkadot also the 128-character sr25519 secret of an account past a /soft junction. On xrpl also a family seed: s... for secp256k1, sEd... for ed25519. On monero also the 25 seed words, on ton the 24 words TON wallets write. On solana also the 64-byte secret, as the id.json array or the base58 that Phantom exports",
}),
addressType: addressTypeArgument,
network: networkArgument,
Expand Down
2 changes: 1 addition & 1 deletion src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export const walletDeriveTool = defineTool({
"Derive a public key and address from an existing private key. Use only public or disposable keys because tool arguments enter the transcript.",
snippet: "Use to derive the public key and address for an existing burner private key.",
guidelines: [
"Provide a chain name and private key as hex, or on xrpl a family seed (s... or sEd...), whose version picks the scheme",
"Provide a chain name and private key as hex, or on xrpl a family seed (s... or sEd...), whose version picks the scheme, or on solana the whole 64-byte secret as id.json or base58",
"On monero pass the 25 English seed words as privateKey, or the private spend key as hex; the 24 key words work without the checksum word, but then each word has to be whole",
"On ton pass the 24 words Tonkeeper and the TON wallets write as privateKey; BIP39 words go to keys_hd_wallet_derive instead",
"On monero account and addressIndex pick the subaddress monero-wallet-cli lists there; the public key is then the subaddress pair",
Expand Down
32 changes: 32 additions & 0 deletions test/blockchains/solana.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,38 @@ describe("Solana Blockchain", () => {
});
});

describe("Secrets from wallets", () => {
const blockchain = useBlockchain(new Solana());
const { keypair } = solanaTestVectors;

it.each([
["the id.json array", keypair.json],
["the base58 export", keypair.base58],
["a pretty printed id.json", `\n${keypair.json.replaceAll(",", ", ")}\n`],
])("restores %s like Keypair.fromSecretKey", (_form, secret) => {
const wallet = blockchain.deriveSeedWallet(secret);
expect(wallet.keys.private).toBe(keypair.seed);
expect(wallet.keys.public).toBe(keypair.publicKey);
expect(wallet.address).toBe(keypair.address);
});

it("refuses a secret whose public half belongs to another key", () => {
expect(() => blockchain.deriveSeedWallet(keypair.mismatched)).toThrow(
"not the public key its seed derives",
);
});

it.each([
["32 bytes of base58", keypair.address],
["a short array", "[1,2,3]"],
["a byte over 255", keypair.json.replace("[1,", "[256,")],
["a fraction", keypair.json.replace("[1,", "[1.5,")],
["broken JSON", keypair.json.slice(0, -1)],
])("refuses %s", (_form, secret) => {
expect(() => blockchain.deriveSeedWallet(secret)).toThrow("A Solana secret is 64 bytes");
});
});

describe("Message signing", () => {
const blockchain = useBlockchain(new Solana());
const vector = solanaTestVectors;
Expand Down
2 changes: 1 addition & 1 deletion test/blockchains/xrpl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ describe("XRPL", () => {

it("leaves seed strings to the XRP Ledger", () => {
expect(() => new Solana().deriveSeedWallet(vector.seeds.master.seed)).toThrow(
"solana has no seed string of its own",
"A Solana secret is 64 bytes",
);
});
});
Expand Down
12 changes: 12 additions & 0 deletions test/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,18 @@ export const ethereumTestVectors = {
* public key and address, `nacl.sign.detached` signatures the way wallet adapters sign messages.
*/
export const solanaTestVectors = {
/** `Keypair.fromSeed` over bytes 1 to 32, @solana/web3.js 1.99.0. */
keypair: {
seed: "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
json: "[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,121,181,86,46,143,230,84,249,64,120,177,18,232,169,139,167,144,31,133,58,230,149,190,215,224,227,145,11,173,4,150,100]",
base58:
"2Ana1pUpv2ZbMVkwF5FXapYeBEjdxDatLn7nvJkhgTSdZd8hbDHTd21as7EAsg7ypityqfsw2pMQKJcVDVcAEsd",
publicKey: "79b5562e8fe654f94078b112e8a98ba7901f853ae695bed7e0e3910bad049664",
address: "9C6hybhQ6Aycep9jaUnP6uL9ZYvDjUp1aSkFWPUFJtpj",
/** Seed 1 to 32 beside another key's public half, which `fromSecretKey` refuses. */
mismatched:
"2Ana1pUpv2ZbMVkwF5FXapYeBEjdxDatLn7nvJkhgTSnQV3LRQndW62nHPq9Pg2aG6AAdDHsCpx9RA5NyDE9qdZ",
},
privateKey: "0000000000000000000000000000000000000000000000000000000000000001",
publicKey: "4cb5abf6ad79fbf5abbccafcc269d85cd2651ed4b885b5869f241aedf0a5ba29",
address: "6ASf5EcmmEHTgDJ4X4ZT5vT6iHVJBXPg5AN5YoTCpGWt",
Expand Down
26 changes: 25 additions & 1 deletion test/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import {
evmTransactionVectors,
descriptorVectors,
multisigVector,
solanaTestVectors,
} from "./fixtures.ts";
import Bitcoin from "../src/blockchains/bitcoin.ts";
import { callTool, createMcpServer, toolListings } from "../src/mcp.ts";
Expand Down Expand Up @@ -1999,6 +2000,29 @@ describe("keys MCP server", () => {
expect(text(path.content)).toContain("m/44'/899'/0'/0/0");
});

it("restores Solana from id.json and base58 secrets through MCP", async () => {
const client = await connectTestClient();
const { keypair } = solanaTestVectors;
for (const secret of [keypair.json, keypair.base58, ` ${keypair.base58}\n`]) {
const response = await client.callTool({
name: "keys_wallet_derive",
arguments: { chain: "solana", privateKey: secret },
});
expect(response.isError).not.toBe(true);
expect(text(response.content)).toContain(`Address: ${keypair.address}`);
expect(text(response.content)).not.toContain(keypair.seed);
expect(JSON.stringify(response.structuredContent ?? {})).not.toContain(keypair.seed);
}

const mismatched = await client.callTool({
name: "keys_wallet_derive",
arguments: { chain: "solana", privateKey: keypair.mismatched },
});
expect(mismatched.isError).toBe(true);
expect(text(mismatched.content)).toContain("not the public key its seed derives");
expect(text(mismatched.content)).not.toContain(keypair.mismatched);
});

it("derives XRPL from family seeds and checks its DER signatures through MCP", async () => {
const client = await connectTestClient();
const { master, ed25519 } = xrplTestVectors.seeds;
Expand All @@ -2017,7 +2041,7 @@ describe("keys MCP server", () => {
arguments: { chain: "solana", privateKey: master.seed },
});
expect(elsewhere.isError).toBe(true);
expect(text(elsewhere.content)).toContain("solana has no seed string of its own");
expect(text(elsewhere.content)).toContain("A Solana secret is 64 bytes");

const { publicKey, address } = xrplTestVectors.ed25519;
const typed = await client.callTool({
Expand Down
Loading
0