-
Notifications
You must be signed in to change notification settings - Fork 44
feat(settings): add vanity wallet generation #536
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
juansebsol
wants to merge
2
commits into
samui-build:main
Choose a base branch
from
juansebsol:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+712
−1
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| import type { Address, KeyPairSigner } from '@solana/kit' | ||
| import { createKeyPairSignerFromPrivateKeyBytes } from '@solana/kit' | ||
| import type { MockInstance } from 'vitest' | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| vi.mock('@solana/kit', async () => { | ||
| const actual = await vi.importActual<typeof import('@solana/kit')>('@solana/kit') | ||
| return { | ||
| ...actual, | ||
| createKeyPairSignerFromPrivateKeyBytes: vi.fn(actual.createKeyPairSignerFromPrivateKeyBytes), | ||
| } | ||
| }) | ||
|
|
||
| import { generateVanityKeyPair, VANITY_MAX_ATTEMPTS } from './generate-vanity-key-pair.ts' | ||
|
|
||
| const ADDRESS_TEMPLATE = '11111111111111111111111111111111' | ||
|
|
||
| function createAddressValue({ prefix = '', suffix = '' }: { prefix?: string; suffix?: string } = {}): Address { | ||
| const fillerLength = Math.max(ADDRESS_TEMPLATE.length - prefix.length - suffix.length, 0) | ||
| const filler = ADDRESS_TEMPLATE.slice(0, fillerLength) | ||
| const value = `${prefix}${filler}${suffix}`.slice(0, ADDRESS_TEMPLATE.length) | ||
| return value as Address | ||
| } | ||
|
|
||
| function createCryptoKey(type: KeyType): CryptoKey { | ||
| return { | ||
| algorithm: { name: 'TEST' }, | ||
| extractable: false, | ||
| type, | ||
| usages: [], | ||
| } | ||
| } | ||
|
|
||
| function createCryptoKeyPair(): CryptoKeyPair { | ||
| return { | ||
| privateKey: createCryptoKey('private'), | ||
| publicKey: createCryptoKey('public'), | ||
| } | ||
| } | ||
|
|
||
| const noopSignMessages: KeyPairSigner['signMessages'] = async () => [] | ||
| const noopSignTransactions: KeyPairSigner['signTransactions'] = async () => [] | ||
|
|
||
| function createSignerStub(overrides: Partial<KeyPairSigner> = {}): KeyPairSigner { | ||
| const signer: KeyPairSigner = { | ||
| address: createAddressValue(), | ||
| keyPair: createCryptoKeyPair(), | ||
| signMessages: noopSignMessages, | ||
| signTransactions: noopSignTransactions, | ||
| } | ||
| return { ...signer, ...overrides } | ||
| } | ||
|
|
||
| describe('generateVanityKeyPair', () => { | ||
| afterEach(() => { | ||
| vi.resetAllMocks() | ||
| }) | ||
|
|
||
| describe('expected behavior', () => { | ||
| it('should generate a key pair with a specific prefix', async () => { | ||
| // ARRANGE | ||
| expect.assertions(2) | ||
| const prefix = 'MAD' | ||
| const signer = createSignerStub({ address: createAddressValue({ prefix }) }) | ||
| const spy = vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockResolvedValue(signer) | ||
|
|
||
| // ACT | ||
| const result = await generateVanityKeyPair({ prefix }) | ||
|
|
||
| // ASSERT | ||
| expect(result.signer.address.startsWith(prefix)).toBe(true) | ||
| expect(spy).toHaveBeenCalled() | ||
| }) | ||
| it('should generate a key pair with a specific suffix', async () => { | ||
| // ARRANGE | ||
| expect.assertions(2) | ||
| const suffix = 'XYZ' | ||
| const signer = createSignerStub({ address: createAddressValue({ suffix }) }) | ||
| const spy = vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockResolvedValue(signer) | ||
|
|
||
| // ACT | ||
| const result = await generateVanityKeyPair({ suffix }) | ||
|
|
||
| // ASSERT | ||
| expect(result.signer.address.endsWith(suffix)).toBe(true) | ||
| expect(spy).toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('should invoke onAttempt for every attempt', async () => { | ||
| // ARRANGE | ||
| expect.assertions(2) | ||
| const attempts: number[] = [] | ||
| const addresses = ['abc', 'def', 'ghi'].map((value) => createAddressValue({ prefix: value })) | ||
| let index = 0 | ||
| vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockImplementation(async () => | ||
| createSignerStub({ | ||
| address: addresses[Math.min(index++, addresses.length - 1)] ?? createAddressValue(), | ||
| }), | ||
| ) | ||
|
|
||
| // ACT | ||
| const result = await generateVanityKeyPair({ | ||
| onAttempt: (value) => attempts.push(value), | ||
| prefix: 'ghi', | ||
| }) | ||
|
|
||
| // ASSERT | ||
| expect(result.attempts).toBe(3) | ||
| expect(attempts).toEqual([1, 2, 3]) | ||
| }) | ||
| }) | ||
|
|
||
| describe('unexpected behavior', () => { | ||
| let consoleSpy: MockInstance | ||
|
|
||
| beforeEach(() => { | ||
| consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| consoleSpy.mockRestore() | ||
| }) | ||
|
|
||
| it('should throw when prefix and suffix are missing', async () => { | ||
| // ARRANGE | ||
| expect.assertions(1) | ||
|
|
||
| // ACT & ASSERT | ||
| await expect(generateVanityKeyPair({})).rejects.toThrow('generateVanityKeyPair requires a prefix or suffix') | ||
| }) | ||
|
|
||
| it('should surface failures from the underlying crypto primitive', async () => { | ||
| // ARRANGE | ||
| expect.assertions(1) | ||
| const error = new Error('crypto failure') | ||
| vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockRejectedValue(error) | ||
|
|
||
| // ACT & ASSERT | ||
| await expect(generateVanityKeyPair({ prefix: 'A' })).rejects.toThrow('crypto failure') | ||
| }) | ||
|
|
||
| it('should throw when the maximum attempts are exhausted without a match', async () => { | ||
| // ARRANGE | ||
| expect.assertions(1) | ||
| vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockResolvedValue(createSignerStub()) | ||
|
|
||
| // ACT & ASSERT | ||
| await expect(generateVanityKeyPair({ maxAttempts: 2, prefix: 'ZZZ' })).rejects.toThrow( | ||
| 'No vanity match found within 2 attempts, try a shorter pattern', | ||
| ) | ||
| }) | ||
|
|
||
| it('should respect the hard cap on attempts', async () => { | ||
| // ARRANGE | ||
| expect.assertions(2) | ||
| const attemptsHardCap = 5 | ||
| vi.mocked(createKeyPairSignerFromPrivateKeyBytes).mockResolvedValue(createSignerStub()) | ||
|
|
||
| // ACT & ASSERT | ||
| await expect( | ||
| generateVanityKeyPair({ attemptsHardCap, maxAttempts: VANITY_MAX_ATTEMPTS + 1, prefix: 'AAA' }), | ||
| ).rejects.toThrow(`No vanity match found within ${attemptsHardCap} attempts, try a shorter pattern`) | ||
| expect(createKeyPairSignerFromPrivateKeyBytes).toHaveBeenCalledTimes(attemptsHardCap) | ||
| }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { createKeyPairSignerFromPrivateKeyBytes, type KeyPairSigner } from '@solana/kit' | ||
|
|
||
| export const VANITY_MAX_ATTEMPTS = 20_000_000 | ||
|
|
||
| export interface GenerateVanityKeyPairOptions { | ||
| attemptsHardCap?: number | ||
| caseSensitive?: boolean | ||
| maxAttempts?: number | ||
| onAttempt?: (attempts: number) => void | ||
| prefix?: string | ||
| suffix?: string | ||
| } | ||
|
|
||
| export interface VanityKeyPairResult { | ||
| attempts: number | ||
| signer: KeyPairSigner | ||
| } | ||
|
|
||
| export async function generateVanityKeyPair({ | ||
| attemptsHardCap = VANITY_MAX_ATTEMPTS, | ||
| caseSensitive = true, | ||
| maxAttempts, | ||
| onAttempt, | ||
| prefix = '', | ||
| suffix = '', | ||
| }: GenerateVanityKeyPairOptions): Promise<VanityKeyPairResult> { | ||
| const sanitizedPrefix = prefix.slice(0, 4) | ||
| const sanitizedSuffix = suffix.slice(0, 4) | ||
| const hasPrefix = sanitizedPrefix.length > 0 | ||
| const hasSuffix = sanitizedSuffix.length > 0 | ||
|
|
||
| if (!hasPrefix && !hasSuffix) { | ||
| throw new Error('generateVanityKeyPair requires a prefix or suffix') | ||
| } | ||
|
|
||
| const normalizedPrefix = caseSensitive ? sanitizedPrefix : sanitizedPrefix.toLowerCase() | ||
| const normalizedSuffix = caseSensitive ? sanitizedSuffix : sanitizedSuffix.toLowerCase() | ||
|
|
||
| const normalizedHardCap = | ||
| typeof attemptsHardCap === 'number' && Number.isFinite(attemptsHardCap) && attemptsHardCap > 0 | ||
| ? Math.min(Math.floor(attemptsHardCap), VANITY_MAX_ATTEMPTS) | ||
| : VANITY_MAX_ATTEMPTS | ||
|
|
||
| const attemptsLimit = | ||
| typeof maxAttempts === 'number' && Number.isFinite(maxAttempts) && maxAttempts > 0 | ||
| ? Math.min(Math.floor(maxAttempts), normalizedHardCap) | ||
| : normalizedHardCap | ||
|
|
||
| for (let attempts = 1; attempts <= attemptsLimit; attempts += 1) { | ||
| const privateKeyBytes = crypto.getRandomValues(new Uint8Array(32)) | ||
| const signer = await createKeyPairSignerFromPrivateKeyBytes(privateKeyBytes, true) | ||
| const address = caseSensitive ? signer.address : signer.address.toLowerCase() | ||
|
|
||
| onAttempt?.(attempts) | ||
|
|
||
| if (hasPrefix && !address.startsWith(normalizedPrefix)) { | ||
| continue | ||
| } | ||
|
|
||
| if (hasSuffix && !address.endsWith(normalizedSuffix)) { | ||
| continue | ||
| } | ||
|
|
||
| return { attempts, signer } | ||
| } | ||
|
|
||
| throw new Error(`No vanity match found within ${attemptsLimit} attempts, try a shorter pattern`) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we simplify this? It's a ternary statement that goes over 4 lines. Code is untested but would this work?