8000 feat(bip39): split glued words by oritwoen · Pull Request #443 · 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 @@ -167,6 +167,7 @@ Holding something else? Here's what to reach for. Every module below lives under
| You've got | Library | Agent tool | More |
| ------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| A clue with seed words buried in it | `scanText` in `bip39` | `keys_bip39_text_scan` | [Wallets](https://keys.agntn.dev/guide/wallets#words-buried-in-a-sentence) |
| A mnemonic with no spaces | `splitWords` in `bip39` | `keys_bip39_words_segment` | [Wallets](https://keys.agntn.dev/guide/wallets#no-spaces-at-all) |
| Four letters off a steel plate | `lookupPrefixes` in `bip39` | `keys_bip39_words_lookup` | [Wallets](https://keys.agntn.dev/guide/wallets#only-four-letters-on-the-plate) |
| `yelow`, copied off a photo | `repairWords` in `bip39` | `keys_bip39_words_repair` | [Wallets](https://keys.agntn.dev/guide/wallets#copied-from-a-photo) |
| The right words, one per clue, no order | `orderWords` in `bip39` | `keys_bip39_words_order` | [Wallets](https://keys.agntn.dev/guide/wallets#one-word-per-clue) |
Expand Down
23 changes: 23 additions & 0 deletions docs/content/1.guide/4.wallets.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,29 @@ For another language, pass `wordlist` from `loadWordlist`. The Chinese lists go

For agents, `keys_bip39_text_scan` takes `text` and `language`. It returns both index forms and spans, one page at a time. More matches? Use the next page offset.

### No spaces at all?

Got a mnemonic glued into one run of letters? Outside the Chinese lists, `scanText` won't find words without boundaries. `splitWords` tries every complete cut instead. It checks sequences of 12, 15, 18, 21 or 24 words.

```js
import { countWordSplits, splitWords } from "@agntn/keys/bip39";

const letters = "carpetzoozoozoozoozoozoozoozooartworkable";

countWordSplits(letters); // 2n

for (const { words, checksumValid } of splitWords(letters))
console.log(checksumValid, words.join(" "));
// false car pet zoo zoo zoo zoo zoo zoo zoo zoo artwork able
// true carpet zoo zoo zoo zoo zoo zoo zoo zoo art work able
```

Both cuts have twelve words, but only the second passes. Stopping at the first cut is a bad bet. Your car pet would miss the carpet. Count first with `countWordSplits` to see the cost before looping.

Spaces and line breaks disappear. Case and Unicode form are folded. Digits and punctuation raise an error. A letter no word covers gives no split at all, not a partial one. Pass a `wordlist` from `loadWordlist` for another language.

Agents can use `keys_bip39_words_segment` with `letters` and `language`. It counts all splits and passing splits, then lists those that pass. Use `all: true` to include failures, marked pass or fail. Page with `limit` and `offset`. The tool refuses more than a million splits per call. It returns phrases, not wallets. Deriving each one is still your job.

### Only four letters on the plate?

Steel plates often keep four letters per word. That's safe by design: no two English words share their first four. `lookupPrefixes` turns them back into words:
Expand Down
1 change: 1 addition & 0 deletions extensions/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Pi coding agent extension exposing the [`@agntn/keys`](../../README.md) library
| `keys_bip39_words_order` | List orders of scattered words whose checksum passes |
| `keys_bip39_words_repair` | Fix mistyped words and list the phrases whose checksum passes |
| `keys_bip39_text_scan` | Find the words of a BIP39 list in a text, each with its span |
| `keys_bip39_words_segment` | Split glued BIP39 words every way and check each split's checksum |
| `keys_address_get` | Derive an address from a public key |
| `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 |
Expand Down
156 changes: 156 additions & 0 deletions src/tool-operations/bip39-words.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
repairWords,
getMnemonicWordCandidates,
scanText,
countWordSplits,
splitWords,
} from "../utils/bip39/index.ts";
import {
integerArray,
Expand All @@ -31,6 +33,7 @@ import {
optionalIndex,
requiredString,
isUnsetCost,
booleanFlag,
} from "./arguments.ts";
import { parseBIP39Language, normalizedMnemonic } from "./bip39.ts";
import { type ToolResult, content, escapeToolText } from "./results.ts";
Expand Down Expand Up @@ -98,6 +101,26 @@ export interface BIP39TextScanDetails {
nextOffset: number | null;
}

/** One way to cut the glued letters into list words. */
export interface BIP39WordSplit {
mnemonic: string;
checksumValid: boolean;
}

/** Result of splitting glued BIP39 words. */
export interface BIP39WordSegmentDetails {
language: string;
/** Splits into 12, 15, 18, 21 or 24 list words. */
total: number;
valid: number;
/** Whether failing splits are listed too. */
all: boolean;
offset: number;
splits: BIP39WordSplit[];
/** Offset of the next page, null on the last one. */
nextOffset: number | null;
}

/** Candidate words for one missing mnemonic position. */
export interface MnemonicRecoveryDetails {
language: string;
Expand Down Expand Up @@ -554,3 +577,136 @@ export async function scanBip39Text(
details: { language, total: found.length, offset, matches, nextOffset },
};
}

/** Segment arguments besides the letters, raw until the executor checks them. */
export interface Bip39WordSegmentArguments {
readonly language?: unknown;
/** List failing splits too. */
readonly all?: unknown;
readonly limit?: unknown;
readonly offset?: unknown;
}

/** One segment page: the splits it lists and how many the filter keeps in all. */
interface SegmentPage {
readonly splits: BIP39WordSplit[];
readonly valid: number;
readonly listable: number;
}

/**
* Reads the glued letters, refusing a blank or an overlong run before the search.
* @param value - Raw letters argument.
* @returns {string} The letters unchanged.
*/
function segmentLetters(value: unknown): string {
const letters = requiredString(value, "Letters");
if (letters.trim() === "") throw new TypeError("Letters must not be empty");
if (letters.length > MAX_BIP39_PHRASE_LENGTH) {
throw new RangeError(`Letters must be at most ${MAX_BIP39_PHRASE_LENGTH} characters`);
}
return letters;
}

/**
* Walks every split once, counting the passes and keeping one page of what the filter lists.
* @param letters - The glued words.
* @param p 8BD0 age - Word list, whether failing splits are listed, limit and offset.
* @returns {SegmentPage} The listed splits, the passes and the splits the filter keeps.
*/
function segmentPage(
letters: string,
page: {
readonly wordlist: readonly string[];
readonly all: boolean;
readonly limit: number;
readonly offset: number;
},
): SegmentPage {
const splits: BIP39WordSplit[] = [];
let valid = 0;
let listable = 0;
for (const { words, checksumValid } of splitWords(letters, page)) {
if (checksumValid) valid++;
if (!page.all && !checksumValid) continue;
if (listable >= page.offset && splits.length < page.limit) {
splits.push({ mnemonic: words.join(" "), checksumValid });
}
listable++;
}
return { splits, valid, listable };
}

/**
* Writes the segment answer: counts, then the page of splits and where the next one starts.
* @param details - The segment result.
* @param page - The listed splits and how many the filter keeps in all.
* @returns {string} The answer text.
*/
function segmentText(
details: Readonly<Omit<BIP39WordSegmentDetails, "splits">>,
page: Readonly<Pick<SegmentPage, "listable">> & {
readonly splits: readonly Readonly<BIP39WordSplit>[];
},
): string {
const { language, total, valid, all, offset, nextOffset } = details;
const { splits, listable } = page;
const kind = all ? "splits" : "passing splits";
const heading =
splits.length < listable
? `Listing ${splits.length} of ${listable} ${kind} from ${offset}`
: `All ${kind}`;
return [
`Language: ${language}`,
`Splits: ${total}`,
`Valid checksum: ${valid}`,
...(total === 0 ? ["No split into 12, 15, 18, 21 or 24 list words covers every letter"] : []),
...(splits.length === 0 ? [] : [`${heading}, shortest phrases first:`]),
...splits.map(({ mnemonic, checksumValid }) =>
all ? `${checksumValid ? "pass" : "fail"}: ${mnemonic}` : mnemonic,
),
...(nextOffset === null ? [] : [`Next offset: ${nextOffset}`]),
].join("\n");
}

/**
* Split glued BIP39 words every way the list allows and check each split's checksum.
* @param lettersValue - The glued words.
* @param options - Official BIP39 language key, all, limit and offset, each optional.
* @returns {Promise<ToolResult<BIP39WordSegmentDetails>>} Counts and one page of splits.
*/
export async function segmentBip39Words(
lettersValue: unknown,
options: Bip39WordSegmentArguments = {},
): Promise<ToolResult<BIP39WordSegmentDetails>> {
const letters = segmentLetters(lettersValue);
const language = parseBIP39Language(optionalName(options.language, "BIP39 language"));
const all = booleanFlag(options.all, "all");
const limit = isUnsetCost(options.limit) ? undefined : phraseLimit(options.limit);
const offset =
optionalIndex(options.offset, { name: "Offset", maximum: MAX_BIP39_CHECKSUM_SEARCH }) ?? 0;
const wordlist = await loadBIP39Wordlist(language);
const counted = countWordSplits(letters, { wordlist });
if (counted > BigInt(MAX_BIP39_CHECKSUM_SEARCH)) {
throw new RangeError(
`These letters split ${counted} ways, over the ${MAX_BIP39_CHECKSUM_SEARCH} one call checks. Iterate splitWords from @agntn/keys/bip39, which has no cap`,
);
}
const page = segmentPage(letters, {
wordlist,
all,
limit: limit ?? DEFAULT_BIP39_PHRASES_SHOWN,
offset,
});
const listed = offset + page.splits.length;
const details = {
language,
total: Number(counted),
valid: page.valid,
all,
offset,
splits: page.splits,
nextOffset: listed < page.listable ? listed : null,
};
return { content: content(segmentText(details, page)), details };
}
3 changes: 3 additions & 0 deletions src/tool-operations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export {
repairBip39Words,
recoverMnemonicWord,
scanBip39Text,
segmentBip39Words,
} from "./bip39-words.ts";
export type {
BIP39IndexLookupDetails,
Expand All @@ -47,6 +48,8 @@ export type {
BIP39WordRepairDetails,
BIP39TextMatch,
BIP39TextScanDetails,
BIP39WordSegmentDetails,
BIP39WordSplit,
MnemonicRecoveryDetails,
} from "./bip39-words.ts";
export { getAddress, validateAddress } from "./address.ts";
Expand Down
9 changes: 5 additions & 4 deletions src/tool-parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const TOOL_NAMES = [
"keys_bip39_words_order",
"keys_bip39_words_repair",
"keys_bip39_text_scan",
"keys_bip39_words_segment",
"keys_address_get",
"keys_address_validate",
"keys_script_address_get",
Expand Down Expand Up @@ -237,16 +238,16 @@ export const TOOL_WIF_CHAINS = [
/** Maximum number of words or indices accepted by one BIP39 lookup. */
export const MAX_BIP39_LOOKUP_ITEMS = 100;

/** Most phrases one order or repair call checks against the checksum, about a second of hashing. */
/** Most phrases one order, repair or segment call checks against the checksum, about a second. */
export const MAX_BIP39_CHECKSUM_SEARCH = 1_000_000;

/** Longest template or phrase the order and repair tools take, in characters. */
/** Longest template, phrase or glued run the order, repair and segment tools take. */
export const MAX_BIP39_PHRASE_LENGTH = 1024;

/** Most phrases one order or repair call lists. */
/** Most phrases one order, repair or segment call lists. */
export const MAX_BIP39_PHRASES_SHOWN = 100;

/** Phrases the order and repair tools list when the caller sets no limit. */
/** Phrases the order, repair and segment tools list when the caller sets no limit. */
export const DEFAULT_BIP39_PHRASES_SHOWN = 20;

/** Most words outside the list one `keys_bip39_words_repair` call fixes. */
Expand Down
35 changes: 35 additions & 0 deletions src/tool-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
MAX_BIP39_LOOKUP_ITEMS,
MAX_BIP39_PHRASES_SHOWN,
MAX_BIP39_PHRASE_LENGTH,
MAX_BIP39_CHECKSUM_SEARCH,
DEFAULT_BIP39_PHRASES_SHOWN,
MAX_BIP39_REPAIR_DISTANCE,
MAX_BIP39_SCAN_LENGTH,
Expand Down Expand Up @@ -1042,6 +1043,40 @@ export const SCAN_BIP39_TEXT_PARAMETERS = Type.Object(
{ additionalProperties: false },
);

export const SEGMENT_BIP39_WORDS_PARAMETERS = Type.Object(
{
letters: Type.String({
description:
"The words glued together, spaces and line breaks ignored, letters only. Example: carpetzoo for carpet zoo",
minLength: 1,
maxLength: MAX_BIP39_PHRASE_LENGTH,
pattern: "\\S",
}),
language: BIP39_LANGUAGE_PARAMETER,
all: Type.Optional(
Type.Boolean({
description:
"List every split, each marked pass or fail, instead of only the ones whose checksum passes. Default: false",
}),
),
limit: Type.Optional(
Type.Integer({
description: `Most splits to list, from 1 to ${MAX_BIP39_PHRASES_SHOWN}. Default: ${DEFAULT_BIP39_PHRASES_SHOWN}`,
minimum: 1,
maximum: MAX_BIP39_PHRASES_SHOWN,
}),
),
offset: Type.Optional(
Type.Integer({
description: "Listed splits to skip, the next offset a call reported. Default: 0",
minimum: 0,
maximum: MAX_BIP39_CHECKSUM_SEARCH,
}),
),
},
{ additionalProperties: false },
);

export const GET_ADDRESS_PARAMETERS = Type.Object(
{
chain: chainArgument,
Expand Down
23 changes: 23 additions & 0 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
ORDER_BIP39_WORDS_PARAMETERS,
REPAIR_BIP39_WORDS_PARAMETERS,
SCAN_BIP39_TEXT_PARAMETERS,
SEGMENT_BIP39_WORDS_PARAMETERS,
RECOVER_MESSAGE_PARAMETERS,
RECOVER_MNEMONIC_WORD_PARAMETERS,
RECOVER_SECP256K1_KNOWN_NONCE_PARAMETERS,
Expand Down Expand Up @@ -480,6 +481,25 @@ export const bip39TextScanTool = defineTool({
(await loadOperations(signal)).scanBip39Text(text, options),
});

export const bip39WordsSegmentTool = defineTool({
name: "keys_bip39_words_segment",
title: "Split Glued Mnemonic Words",
description: `Cut BIP39 words glued together with no spaces into list words every way the list allows, for 12, 15, 18, 21 and 24 words, and check each split's checksum. One run can split several ways, as carpet and car pet are both on the English list, so the answer counts every split and the ones that pass, then lists the passing ones. More than ${MAX_BIP39_CHECKSUM_SEARCH} splits are refused. Inputs enter the transcript, so use only public or disposable words.`,
snippet: "Use when a puzzle hands over the mnemonic as one run of letters with no spaces.",
guidelines: [
"Pass the letters as copied: spaces and line breaks are dropped, digits and punctuation refused",
"A letter no list word covers gives no split at all, never a partial one",
"all: true lists the failing splits too, each marked pass or fail",
"More splits than limit? The answer ends with the offset of the next page",
"Returns phrases, not wallets: derive each one to find the one that opens the target address",
],
effect: "read",
cli: { positional: ["letters"], stdin: ["letters"] },
input: SEGMENT_BIP39_WORDS_PARAMETERS,
execute: async ({ letters, ...options }, { signal }) =>
(await loadOperations(signal)).segmentBip39Words(letters, options),
});

export const addressGetTool = defineTool({
name: "keys_address_get",
title: "Get Address",
Expand Down Expand Up @@ -779,6 +799,7 @@ export const keysTools = [
bip39WordsOrderTool,
bip39WordsRepairTool,
bip39TextScanTool,
bip39WordsSegmentTool,
addressGetTool,
addressValidateTool,
scriptAddressGetTool,
Expand Down Expand Up @@ -824,6 +845,8 @@ export const callSummaries: Readonly<
`${Array.isArray(args.indices) ? args.indices.length : 0} indices`,
keys_bip39_words_lookup: (args) => `${Array.isArray(args.words) ? args.words.length : 0} words`,
keys_bip39_words_order: (args) => `${Array.isArray(args.words) ? args.words.length : 0} words`,
keys_bip39_words_segment: (args) =>
`${typeof args.letters === "string" ? args.letters.length : 0} letters`,
keys_address_get: (args) => String(args.chain),
keys_address_validate: (args) => String(args.address),
keys_script_address_get: (args) =>
Expand Down
2 changes: 2 additions & 0 deletions src/utils/bip39/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export { repairWords, suggestWords } from "./repair.ts";
export type { WordRepair, WordRepairOptions, WordSuggestion, WordSuggestions } from "./repair.ts";
export { scanText } from "./scan.ts";
export type { TextMatch, TextScanOptions } from "./scan.ts";
export { countWordSplits, splitWords } from "./split.ts";
export type { WordSplit, WordSplitOptions } from "./split.ts";

// Get English wordlist
const wordlist = english.wordlist;
Expand Down
Loading
Loading
0