8000 feat(solana): derive PDAs by oritwoen · Pull Request #433 · 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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ Holding something else? Here's what to reach for. Every module below lives under
| A hint with a PGP signature under it | `verify` in `openpgp` | `keys_openpgp_verify` | [Keys](https://keys.agntn.dev/guide/keys#openpgp-signatures) |
| The same `r` on two signatures | `extractSignatures` in `transaction`, `recoverReusedNonce` | `keys_transaction_signatures_extract`, `keys_secp256k1_nonce_recover` | [Bitcoin](https://keys.agntn.dev/blockchains/bitcoin#recovering-a-key-from-a-reused-nonce) |
| One signature and its leaked nonce | `recoverKnownNonce` in `secp256k1` | `keys_secp256k1_known_nonce_recover` | [Bitcoin](https://keys.agntn.dev/blockchains/bitcoin#recovering-a-key-from-a-known-nonce) |
| A Solana program's seeds, or a token mint | `findProgramAddress`, `getAssociatedTokenAddress` | `keys_solana_program_address_get`, `keys_solana_token_address_get` | [Solana](https://keys.agntn.dev/blockchains/solana#program-addresses) |
| A multisig, a `redeemScript`, a descriptor | `script` and `descriptor` | `keys_script_address_get`, `keys_descriptor_derive` | [Bitcoin](https://keys.agntn.dev/blockchains/bitcoin#multisig-and-other-scripts) |

The tools that open a secret answer agents with an address, a public key or a fingerprint. BIP38 and the parent recovery hand over the key itself only with `revealKey: true`. And one trap no table shows: any well formed signature recovers some key for any message. Check the address match, not just that a key came out.
Expand Down
28 changes: 28 additions & 0 deletions docs/content/2.blockchains/solana.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,34 @@ The seed in this public test vector just counts from 1 to 32. The other half is

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.

## Program addresses

Remember how `validateAddress` waves through a program address no key controls? Here's where those come from. A program derived address (PDA) starts with SHA-256. It hashes seeds, a bump byte, the program ID and `"ProgramDerivedAddress"`. The result must land off the ed25519 curve, so no private key exists for it. All offline, no RPC.

```js
const seeds = [new TextEncoder().encode("helloWorld")];
solanaChain.findProgramAddress(seeds, "BPFLoaderUpgradeab1e11111111111111111111111");
// { address: "BkJopytB5Ah8hxg8A9joeGLjQxPVNigk1D8JDj5JkPqq", bump: 255 }
```

`findProgramAddress` searches down from 255 for the first off-curve bump. That's the canonical bump, matching Rust's `find_program_address` and `@solana/web3.js`. Whether 255 works on the first try is a coin flip.

Already know the bump? Put it last in the seeds for `createProgramAddress`. That method throws if the result lands on the curve. Seeds are `Uint8Array` values, at most 32 bytes each. You can use 15 seeds, plus the bump. Encode a `u64` as eight little-endian bytes.

### Token accounts

```js
import { TOKEN_2022_PROGRAM } from "@agntn/keys/blockchains/solana";

const usdc = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
solanaChain.getAssociatedTokenAddress("9C6hybhQ6Aycep9jaUnP6uL9ZYvDjUp1aSkFWPUFJtpj", { mint: usdc }).address;
// FjCjyojZLVYVQ2dEdDKQx76msks96TdH9xqvc8BQ9UUx
```

`getAssociatedTokenAddress` gives you a wallet's associated token account (ATA) for a mint. It uses SPL Token by default. For a Token-2022 mint, pass `tokenProgram: TOKEN_2022_PROGRAM`. A PDA can own the account too. Check the program carefully: the wrong one gives you a valid address that never holds a token, with no warning.

Agents get `keys_solana_program_address_get` and `keys_solana_token_address_get`. Each program address seed is an object with one of `text`, `hex`, `address` or `u64`. Every address here comes from `@solana/web3.js` 1.99.0 and `@solana/spl-token` 0.4.15, and the tests hold the library to them.

## 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.
2 changes: 2 additions & 0 deletions extensions/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ Pi coding agent extension exposing the [`@agntn/keys`](../../README.md) library
| `keys_address_validate` | Check if an address is valid for a chain |
| `keys_script_address_get` | P2SH, P2WSH and P2SH-P2WSH addresses of a script or a multisig |
| `keys_descriptor_derive` | Addresses and checksum of a Bitcoin output descriptor |
| `keys_solana_program_address_get` | Get a Solana program address from seeds and a program ID |
| `keys_solana_token_address_get` | Get a Solana associated token address for an owner and mint |
| `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 signmessage, personal_sign or EIP-712 |
Expand Down
49 changes: 49 additions & 0 deletions src/blockchains/solana.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ 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 ProgramAddress,
type TokenAddressOptions,
createProgramAddress,
findProgramAddress,
getAssociatedTokenAddress,
} from "../utils/solana-pda.ts";
import type { AddressType, DerivationPathOptions, Wallet, WalletOptions } from "../types.ts";

/**
Expand Down Expand Up @@ -99,6 +106,48 @@ export class Solana extends AbstractEd25519Blockchain {
return false;
}
}

/**
* The canonical program derived address, as `find_program_address` gives it.
* @param seeds - Up to 15 seeds of up to 32 bytes, without the bump
* @param programId - The program, base58
* @returns {ProgramAddress} The address and its bump, the first from 255 down off the curve
* @throws {RangeError} On bad seeds or a bad program id
*/
findProgramAddress(seeds: readonly Uint8Array[], programId: string): ProgramAddress {
return findProgramAddress(seeds, programId);
}

/**
* The program address of seeds that already end in their bump.
* @param seeds - Up to 16 seeds of up to 32 bytes, the bump last
* @param programId - The program, base58
* @returns {string} The address
* @throws {RangeError} On bad seeds, a bad program id or seeds that land on the curve
*/
createProgramAddress(seeds: readonly Uint8Array[], programId: string): string {
return createProgramAddress(seeds, programId);
}

/**
* The associated token account of a wallet for a mint, SPL Token unless told otherwise.
* @param owner - The wallet, base58
* @param options - The mint and its token program
* @returns {ProgramAddress} The account and its bump
* @throws {TypeError} When options carries no mint
* @throws {RangeError} When an address isn't 32 bytes of base58
*/
getAssociatedTokenAddress(owner: string, options: TokenAddressOptions): ProgramAddress {
return getAssociatedTokenAddress(owner, options);
}
}

export {
ASSOCIATED_TOKEN_PROGRAM,
TOKEN_2022_PROGRAM,
TOKEN_PROGRAM,
type ProgramAddress,
type TokenAddressOptions,
} from "../utils/solana-pda.ts";

export default Solana;
2 changes: 2 additions & 0 deletions src/tool-operations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ export { decryptStore } from "./store.ts";
export type { DecryptedStoreDetails } from "./store.ts";
export { getArweaveAddress } from "./arweave.ts";
export type { ArweaveAddressDetails } from "./arweave.ts";
export { getSolanaProgramAddress, getSolanaTokenAddress } from "./solana.ts";
export type { SolanaProgramAddressDetails, SolanaTokenAddressDetails } from "./solana.ts";
export {
MAX_BIP39_LOOKUP_ITEMS,
BIP39_ENTROPY_BYTE_LENGTHS,
Expand Down
163 changes: 163 additions & 0 deletions src/tool-operations/solana.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import {
type ProgramAddress,
MAX_PROGRAM_SEED_LENGTH,
MAX_PROGRAM_SEEDS,
TOKEN_PROGRAM,
createProgramAddress,
decodeSolanaAddress,
findProgramAddress,
getAssociatedTokenAddress,
} from "../utils/solana-pda.ts";
import { BUMP_SCHEMA_PATTERN } from "../tool-parameters.ts";
import {
HEX_BYTES,
boundedArray,
closedObject,
optionalName,
requiredString,
} from "./arguments.ts";
import { type ToolResult, content } from "./results.ts";

/** A program address, the bump that made it and whether the bump was searched for. */
export interface SolanaProgramAddressDetails {
chain: "solana";
programId: string;
address: string;
bump: number;
canonical: boolean;
}

/** A wallet's token account for one mint. */
export interface SolanaTokenAddressDetails {
chain: "solana";
owner: string;
mint: string;
tokenProgram: string;
address: string;
bump: number;
}

const SEED_KINDS = ["text", "hex", "address", "u64"] as const;

const U64_MAX = 2n ** 64n - 1n;

const BUMP = new RegExp(BUMP_SCHEMA_PATTERN, "u");

/**
* Writes a decimal u64 as Rust's `to_le_bytes` does.
* @param value - Decimal digits
* @returns {Uint8Array} 8 bytes
*/
function u64Bytes(value: string): Uint8Array {
const number = /^(?:0|[1-9]\d{0,19})$/u.test(value) ? BigInt(value) : U64_MAX + 1n;
if (number > U64_MAX) throw new RangeError("u64 seed must be a decimal integer below 2^64");
const bytes = new Uint8Array(8);
new DataView(bytes.buffer).setBigUint64(0, number, true);
return bytes;
}

/**
* Turns one seed object into its bytes.
* @param value - Raw seed
* @param index - Its position, for the error
* @returns {Uint8Array} The bytes
*/
function seedBytes(value: unknown, index: number): Uint8Array {
const seed = closedObject(value, { name: `Seed ${index}`, keys: SEED_KINDS });
const given = SEED_KINDS.filter((kind) => seed[kind] !== undefined);
const [kind] = given;
if (kind === undefined || given.length > 1) {
throw new TypeError(`Seed ${index} takes exactly one of ${SEED_KINDS.join(", ")}`);
}
const text = requiredString(seed[kind], `Seed ${index} ${kind}`);
if (kind === "address") return decodeSolanaAddress(text, `Seed ${index} address`);
if (kind === "u64") return u64Bytes(text);
if (kind === "hex" && !HEX_BYTES.test(text)) {
throw new TypeError(`Seed ${index} hex must be whole bytes of hex without 0x`);
}
const bytes = kind === "hex" ? Uint8Array.fromHex(text) : new TextEncoder().encode(text);
if (bytes.length > MAX_PROGRAM_SEED_LENGTH) {
throw new RangeError(
`Seed ${index} is ${bytes.length} bytes, past the ${MAX_PROGRAM_SEED_LENGTH} a seed takes`,
);
}
return bytes;
}

/**
* Reads an optional bump given as decimal text, blank meaning left out.
* @param value - Raw bump
* @returns {number | undefined} The bump
*/
function optionalBump(value: unknown): number | undefined {
const text = optionalName(value, "bump");
if (text === undefined) return undefined;
if (!BUMP.test(text)) throw new RangeError("bump must be decimal text from 0 to 255");
return Number(text);
}

/** Program address arguments besides the program, raw until the executor checks them. */
export interface SolanaProgramAddressArguments {
readonly seeds?: unknown;
readonly bump?: unknown;
}

/**
* Derives a program address, the canonical one or the one a known bump gives.
* @param programValue - The program, base58
* @param options - Seeds and an optional bump
* @returns {ToolResult<SolanaProgramAddressDetails>} The address and its bump
*/
export function getSolanaProgramAddress(
programValue: unknown,
options: SolanaProgramAddressArguments,
): ToolResult<SolanaProgramAddressDetails> {
const programId = requiredString(programValue, "programId");
decodeSolanaAddress(programId, "programId");
const raw = boundedArray(options.seeds, {
name: "seeds",
minimum: 0,
maximum: MAX_PROGRAM_SEEDS - 1,
});
const seeds = raw.map((seed, index) => seedBytes(seed, index));
const bump = optionalBump(options.bump);
const found: ProgramAddress =
bump === undefined
? findProgramAddress(seeds, programId)
: { address: createProgramAddress([...seeds, Uint8Array.of(bump)], programId), bump };
const canonical = bump === undefined;
return {
content: content(
[`Address: ${found.address}`, `Bump: ${found.bump}${canonical ? " (canonical)" : ""}`].join(
"\n",
),
),
details: { chain: "solana", programId, ...found, canonical },
};
}

/** Token account arguments besides the owner, raw until the executor checks them. */
export interface SolanaTokenAddressArguments {
readonly mint?: unknown;
readonly tokenProgram?: unknown;
}

/**
* Derives the associated token account of a wallet for a mint.
* @param ownerValue - The wallet, base58
* @param options - The mint and an optional token program
* @returns {ToolResult<SolanaTokenAddressDetails>} The account
*/
export function getSolanaTokenAddress(
ownerValue: unknown,
options: SolanaTokenAddressArguments,
): ToolResult<SolanaTokenAddressDetails> {
const owner = requiredString(ownerValue, "owner");
const mint = requiredString(options.mint, "mint");
const tokenProgram = optionalName(options.tokenProgram, "tokenProgram") ?? TOKEN_PROGRAM;
const { address, bump } = getAssociatedTokenAddress(owner, { mint, tokenProgram });
return {
content: content(`Address: ${address}`),
details: { chain: "solana", owner, mint, tokenProgram, address, bump },
};
}
11 changes: 11 additions & 0 deletions src/tool-parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export const TOOL_NAMES = [
"keys_address_validate",
"keys_script_address_get",
"keys_descriptor_derive",
"keys_solana_program_address_get",
"keys_solana_token_address_get",
"keys_message_sign",
"keys_message_verify",
"keys_message_recover",
Expand Down Expand Up @@ -421,3 +423,12 @@ export const MAX_DESCRIPTOR_LENGTH = 16_384;

/** Most addresses one `keys_descriptor_derive` call lists. */
export const MAX_DESCRIPTOR_ADDRESSES = 100;

/** JSON Schema pattern for a Solana address: base58, the length 32 bytes can take. */
export const SOLANA_ADDRESS_SCHEMA_PATTERN = "^[1-9A-HJ-NP-Za-km-z]{32,44}$";

/** JSON Schema pattern for a PDA bump, 0 to 255 in decimal: OMP sends 0 for a number left out. */
export const BUMP_SCHEMA_PATTERN = "^(?:0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

/** JSON Schema pattern for a u64 in decimal; the executor checks the upper bound. */
export const U64_SCHEMA_PATTERN = "^(?:0|[1-9][0-9]{0,19})$";
68 changes: 68 additions & 0 deletions src/tool-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,12 @@ import {
MAX_DESCRIPTOR_LENGTH,
MAX_SCRIPT_HEX_LENGTH,
SEC1_PUBLIC_KEY_SCHEMA_PATTERN,
SOLANA_ADDRESS_SCHEMA_PATTERN,
BUMP_SCHEMA_PATTERN,
U64_SCHEMA_PATTERN,
} from "./tool-parameters.ts";
import { MAX_MULTISIG_KEYS } from "./utils/script/limits.ts";
import { MAX_PROGRAM_SEED_LENGTH, MAX_PROGRAM_SEEDS } from "./utils/solana-limits.ts";
import { COSMOS_PREFIX_PATTERN } from "./utils/cosmos-prefix.ts";
import { BIP39_LANGUAGES } from "./utils/bip39/languages.ts";

Expand Down Expand Up @@ -1303,6 +1307,70 @@ export const DERIVE_DESCRIPTOR_PARAMETERS = Type.Object(
{ additionalProperties: false },
);

/**
* A Solana address, 32 bytes of base58.
* @param description - What the address is
* @returns {TString} The schema
*/
function solanaAddress(description: string): TString {
return Type.String({ pattern: SOLANA_ADDRESS_SCHEMA_PATTERN, description });
}

export const GET_SOLANA_PROGRAM_ADDRESS_PARAMETERS = Type.Object(
{
programId: solanaAddress("The program that owns the address, base58"),
seeds: Type.Array(
Type.Object(
{
text: Type.Optional(
Type.String({ maxLength: MAX_PROGRAM_SEED_LENGTH, description: "UTF-8 text" }),
),
hex: Type.Optional(
Type.String({
maxLength: MAX_PROGRAM_SEED_LENGTH * 2,
pattern: HEX_BYTES_SCHEMA_PATTERN,
description: "Raw bytes as hex without 0x",
}),
),
address: Type.Optional(solanaAddress("A wallet, mint or program, base58")),
u64: Type.Optional(
Type.String({
pattern: U64_SCHEMA_PATTERN,
description: "A decimal integer as 8 little-endian bytes, like to_le_bytes()",
}),
),
},
{ additionalProperties: false },
),
{
maxItems: MAX_PROGRAM_SEEDS - 1,
description: `Seeds in program order, one of text, hex, address or u64 each, up to ${MAX_PROGRAM_SEED_LENGTH} bytes`,
},
),
bump: Type.Optional(
Type.String({
pattern: BUMP_SCHEMA_PATTERN,
description:
"A known bump from 0 to 255 as decimal text, appended as the last seed. Default: the canonical one",
}),
),
},
{ additionalProperties: false },
);

export const GET_SOLANA_TOKEN_ADDRESS_PARAMETERS = Type.Object(
{
owner: solanaAddress("The wallet that holds the tokens, base58"),
mint: solanaAddress("The token's mint, base58"),
tokenProgram: Type.Optional(
solanaAddress(
"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb for a Token-2022 mint. Default: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
),
),
},
{ additionalProperties: false },
);

export const BIP44_PARSE_PARAMETERS = Type.Object(
{
path: Type.String({
Expand Down
Loading
Loading
0