8000 feat(tools): derive uncompressed wallets by aeitwoen · Pull Request #207 · agntn/keys · GitHub
[go: up one dir, main page]

Skip to content
8000
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
2 changes: 2 additions & 0 deletions packages/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ Pi coding agent extension exposing the [`@agntn/keys`](../../README.md) library

`keys_wallet_generate`, `keys_wallet_derive`, `keys_hd_wallet_derive`, `keys_xpub_wallet_derive` and `keys_address_get` print an `Address type:` line on chains with more than one format: Bitcoin, Bitcoin Gold, Litecoin, Sui and Cardano. It's the type you passed, the one the path purpose or key prefix picked, or the chain's default, so nobody has to guess it from the first characters of the address.

`keys_wallet_derive` takes an optional `compressed`, `true` by default. Old wallets and brainwallets wrote the uncompressed key, and on the Bitcoin family that's another legacy address from the same private key, so pass `compressed: false` for them. Ethereum, Base and TRON hash the uncompressed key anyway and refuse `true`. Sui on secp256k1 refuses `false`, and the ed25519 chains take no flag at all.

## Puzzle checksum override

`keys_hd_wallet_derive` rejects invalid checksums by default. For public puzzle candidates, set `allowInvalidChecksum: true` explicitly. The tool derives from the supplied words without repairing them and includes a warning in both text and details when the checksum is invalid. Words from the selected list and BIP39 word counts are still required. The list comes from optional `language`, English by default, as in the other BIP39 tools. Whitespace collapsing, NFKD normalization and chain/path restrictions are unchanged.
Expand Down
46 changes: 45 additions & 1 deletion src/tool-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ export interface DerivedWalletDetails {
network: string;
publicKey: string;
addressType?: string;
/** The public key form the caller asked for; absent when it was left to the default. */
compressed?: boolean;
address: string;
path?: string;
warnings?: readonly string[];
Expand Down Expand Up @@ -456,36 +458,78 @@ export async function generateWallet(
};
}

/** Chains whose address hashes the uncompressed secp256k1 key whatever form it is given in. */
const UNCOMPRESSED_ADDRESS_CHAINS: ReadonlySet<string> = new Set(["ethereum", "base", "tron"]);

/**
* Reads the public key form, refusing one the chain's address would ignore.
* @param blockchain - Chain the wallet is for
* @param addressType - Parsed address type, which picks the curve on Sui
* @param value - Raw argument
* @returns {boolean | undefined} The form to derive, undefined when omitted
*/
function walletCompressed(
blockchain: Readonly<AbstractBlockchain>,
addressType: string | undefined,
value: unknown,
): boolean | undefined {
if (value === undefined) return undefined;
if (typeof value !== "boolean") throw new TypeError("compressed must be a boolean");
const { name, curve } = blockchain;
if (curve !== "secp256k1" && addressType !== "secp256k1") {
throw new RangeError(`${name} ed25519 keys take no compressed`);
}
if (value && UNCOMPRESSED_ADDRESS_CHAINS.has(name)) {
throw new RangeError(
`${name} addresses hash the uncompressed key, so compressed: true does not apply`,
);
}
if (!value && name === "sui") {
throw new RangeError(
"sui secp256k1 addresses hash the compressed key, so compressed: false does not apply",
);
}
return value;
}

/**
* Derive public wallet material from a private key without echoing the secret.
* @param chainValue - Blockchain name.
* @param privateKeyValue - Private key as hexadecimal text.
* @param addressTypeValue - Optional chain-specific address type.
* @param networkValue - Optional network name.
* @param compressedValue - Optional secp256k1 public key form, compressed by default.
* @returns {Promise<ToolResult<DerivedWalletDetails>>} Derived public wallet material.
*/
export async function deriveWallet(
chainValue: unknown,
privateKeyValue: unknown,
addressTypeValue?: unknown,
networkValue?: unknown,
compressedValue?: unknown,
): Promise<ToolResult<DerivedWalletDetails>> {
const { blockchain, addressType } = await getBlockchain(
chainValue,
networkValue,
addressTypeValue,
);
const compressed = walletCompressed(blockchain, addressType, compressedValue);
const privateKey = hexArgument(
privateKeyValue,
"Private key",
PRIVATE_KEY_HEX,
"64 hex characters",
);
const wallet = blockchain.deriveWallet(privateKey, {}, addressType);
const wallet = blockchain.deriveWallet(
privateKey,
compressed === undefined ? {} : { compressed },
addressType,
);
const details = {
chain: blockchain.name,
network: blockchain.network,
...(wallet.addressType === undefined ? {} : { addressType: wallet.addressType }),
...(compressed === undefined ? {} : { compressed }),
publicKey: wallet.keys.public,
address: wallet.address,
};
Expand Down
6 changes: 6 additions & 0 deletions src/tool-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,12 @@ export const DERIVE_WALLET_PARAMETERS = Type.Object(
}),
addressType: addressTypeArgument,
network: networkArgument,
compressed: Type.Optional(
Type.Boolean({
description:
"secp256k1 only: SEC1 form of the public key, which a legacy address hashes. Old wallets and brainwallets wrote uncompressed. ethereum, base and tron hash the uncompressed key and refuse true, sui refuses false. Default: true",
}),
),
},
{ additionalProperties: false },
);
Expand Down
2 changes: 2 additions & 0 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export const walletDeriveTool = defineTool({
"Bitcoin and Litecoin address types: legacy, p2sh, segwit, p2wsh, taproot",
"Bitcoin Gold address types: legacy, p2sh, segwit, p2wsh",
"For Sui, use ed25519 or secp256k1 as the address type",
"Pass compressed: false for an old key on the Bitcoin family, whose legacy address hashes the uncompressed public key",
],
effect: "read",
input: DERIVE_WALLET_PARAMETERS,
Expand All @@ -186,6 +187,7 @@ export const walletDeriveTool = defineTool({
params.privateKey,
params.addressType,
params.network,
params.compressed,
),
});

Expand Down
49 changes: 49 additions & 0 deletions test/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,55 @@ describe("keys MCP server", () => {
expect(text(response.content)).not.toContain(litecoinTestVectors.privateKey);
});

it("derives the uncompressed Bitcoin and Ethereum wallets through MCP", async () => {
const client = await connectTestClient();
const [rushwallet] = plainBrainwalletVectors;
const bitcoin = await client.callTool({ B8DA
name: "keys_wallet_derive",
arguments: { chain: "bitcoin", privateKey: rushwallet.privateKey, compressed: false },
});
expect(bitcoin.isError).not.toBe(true);
expect(text(bitcoin.content).split("\n")).toEqual([
"Address type: legacy",
`Public key: ${rushwallet.publicKey}`,
`Address: ${rushwallet.address}`,
]);

const ethereum = await client.callTool({
name: "keys_wallet_derive",
arguments: {
chain: "ethereum",
privateKey: ethereumTestVectors.privateKey,
compressed: false,
},
});
expect(text(ethereum.content).split("\n")).toEqual([
`Public key: ${ethereumTestVectors.publicKeyUncompressed}`,
`Address: ${ethereumTestVectors.address}`,
]);
});

it("refuses a compressed flag the chain's address would ignore", async () => {
const client = await connectTestClient();
const privateKey = secp256k1TestVectors.privateKey;
for (const [args, message] of [
[{ chain: "ethereum", compressed: true }, "ethereum addresses hash the uncompressed key"],
[{ chain: "tron", compressed: true }, "tron addresses hash the uncompressed key"],
[{ chain: "sui", addressType: "secp256k1", compressed: false }, "sui secp256k1 addresses"],
[{ chain: "sui", compressed: true }, "sui ed25519 keys take no compressed"],
[{ chain: "solana", compressed: false }, "solana ed25519 keys take no compressed"],
[{ chain: "bitcoin", addressType: "segwit", compressed: false }, "take a compressed"],
] as const) {
const failed = await client.callTool({
name: "keys_wallet_derive",
arguments: { ...args, privateKey },
});
expect(failed.isError, message).toBe(true);
expect(text(failed.content)).toContain(message);
expect(text(failed.content)).not.toContain(privateKey);
}
});

it("derives and validates Bitcoin Cash through the MCP schema and executor", async () => {
const client = await connectTestClient();
const { privateKey, address } = bitcoinCashTestVectors.prize;
Expand Down
Loading
0