Vanity as functional (#2522)

* Vanity as functional

* Table layout
This commit is contained in:
Jaco Greeff 2020-04-07 07:22:13 +02:00 committed by GitHub
parent 1508f7bc13
commit 5475b770f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 234 additions and 252 deletions

View File

@ -33,37 +33,40 @@ function Match ({ address, className, count, offset, onCreateToggle, onRemove, s
);
return (
<div className={className}>
<div className='vanity--Match-item'>
<tr className={className}>
<td
className='number'
colSpan={2}
>
<IdentityIcon
className='vanity--Match-icon'
size={48}
size={32}
value={address}
/>
<div className='vanity--Match-data'>
<div className='vanity--Match-addr'>
<span className='no'>{address.slice(0, offset)}</span><span className='yes'>{address.slice(offset, count + offset)}</span><span className='no'>{address.slice(count + offset)}</span>
</div>
<div className='vanity--Match-seed'>
{hexSeed}
</div>
</td>
<td className='address all'>
<div className='vanity--Match-addr'>
<span className='no'>{address.slice(0, offset)}</span><span className='yes'>{address.slice(offset, count + offset)}</span><span className='no'>{address.slice(count + offset)}</span>
</div>
<div className='vanity--Match-buttons'>
<Button
icon='plus'
isPrimary
onClick={_onCreate}
size='tiny'
/>
<Button
icon='close'
isNegative
onClick={_onRemove}
size='tiny'
/>
</div>
</div>
</div>
</td>
<td className='hash'>
{hexSeed}
</td>
<td className='button'>
<Button
icon='plus'
isPrimary
onClick={_onCreate}
size='tiny'
/>
<Button
icon='close'
isNegative
onClick={_onRemove}
size='tiny'
/>
</td>
</tr>
);
}
@ -75,8 +78,7 @@ export default React.memo(styled(Match)`
}
.vanity--Match-addr {
font-size: 1.5rem;
padding: 0 1rem;
font-size: 1.25rem;
.no {
color: inherit;

View File

@ -2,38 +2,35 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { I18nProps } from '@polkadot/react-components/types';
import { KeypairType } from '@polkadot/util-crypto/types';
import { GeneratorMatches, GeneratorMatch, GeneratorResult } from '@polkadot/vanitygen/types';
import { ComponentProps } from '../types';
import { ComponentProps as Props } from '../types';
import React from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { Button, Dropdown, Input, TxComponent } from '@polkadot/react-components';
import { Button, Dropdown, Input, Table } from '@polkadot/react-components';
import { useIsMountedRef } from '@polkadot/react-hooks';
import uiSettings from '@polkadot/ui-settings';
import generator from '@polkadot/vanitygen/generator';
import matchRegex from '@polkadot/vanitygen/regex';
import generatorSort from '@polkadot/vanitygen/sort';
import CreateModal from '../Accounts/modals/Create';
import translate from '../translate';
import { useTranslation } from '../translate';
import Match from './Match';
interface Props extends ComponentProps, I18nProps {}
interface State {
createSeed: string | null;
elapsed: number;
interface Match {
isMatchValid: boolean;
isRunning: boolean;
keyCount: 0;
keyTime: 0;
match: string;
}
interface Results {
elapsed: number;
isRunning: boolean;
keyCount: number;
keyTime: number;
matches: GeneratorMatches;
startAt: number;
type: KeypairType;
withCase: boolean;
withHex: boolean;
}
const DEFAULT_MATCH = 'Some';
@ -42,244 +39,227 @@ const BOOL_OPTIONS = [
{ text: 'Yes', value: true }
];
class VanityApp extends TxComponent<Props, State> {
private results: GeneratorResult[] = [];
public state: State = {
createSeed: null,
function VanityApp ({ className, onStatusChange }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const results = useRef<GeneratorResult[]>([]);
const runningRef = useRef(false);
const mountedRef = useIsMountedRef();
const [createSeed, setCreateSeed] = useState<string | null>(null);
const [{ elapsed, isRunning, keyCount, matches }, setResults] = useState<Results>({
elapsed: 0,
isMatchValid: true,
isRunning: false,
keyCount: 0,
keyCount: -1,
keyTime: 0,
match: DEFAULT_MATCH,
matches: [],
startAt: 0,
type: 'ed25519',
withCase: true,
withHex: true
};
startAt: 0
});
const [{ isMatchValid, match }, setMatch] = useState<Match>({ isMatchValid: true, match: DEFAULT_MATCH });
const [type, setType] = useState<KeypairType>('ed25519');
const [withCase, setWithCase] = useState(true);
private _isActive = false;
const _clearSeed = useCallback(
() => setCreateSeed(null),
[]
);
public componentWillUnmount (): void {
this._isActive = false;
}
const _checkMatches = useCallback(
(): void => {
const checks = results.current;
public render (): React.ReactNode {
const { className, onStatusChange, t } = this.props;
const { createSeed, elapsed, isMatchValid, isRunning, keyCount, match, matches, type, withCase } = this.state;
results.current = [];
return (
<div className={className}>
<div className='ui--row'>
<Input
autoFocus
className='medium'
help={t('Type here what you would like your address to contain. This tool will generate the keys and show the associated addresses that best match your search. You can use "?" as a wildcard for a character.')}
isDisabled={isRunning}
isError={!isMatchValid}
label={t('Search for')}
onChange={this.onChangeMatch}
onEnter={this.submit}
value={match}
/>
<Dropdown
className='medium'
help={t('Should the search be case sensitive, e.g if you select "no" your search for "Some" may return addresses containing "somE" or "sOme"...')}
isDisabled={isRunning}
label={t('case sensitive')}
onChange={this.onChangeCase}
options={BOOL_OPTIONS}
value={withCase}
/>
</div>
<div className='ui--row'>
<Dropdown
className='medium'
defaultValue={type}
help={t('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')}
label={t('keypair crypto type')}
onChange={this.onChangeType}
options={uiSettings.availableCryptos}
/>
</div>
<Button.Group>
<Button
icon={
isRunning
? 'stop'
: 'sign-in'
}
isDisabled={!isMatchValid}
label={
isRunning
? t('Stop generation')
: t('Start generation')
}
onClick={this.toggleStart}
/>
</Button.Group>
{keyCount !== 0 && (
<div className='vanity--App-stats'>
{t('Evaluated {{count}} keys in {{elapsed}}s ({{avg}} keys/s)', {
replace: {
avg: (keyCount / (elapsed / 1000)).toFixed(3),
count: keyCount,
elapsed: (elapsed / 1000).toFixed(2)
}
})}
</div>
)}
<div className='vanity--App-matches'>
{matches.map((match): React.ReactNode => (
<Match
{...match}
key={match.address}
onCreateToggle={this.onCreateToggle}
onRemove={this.onRemove}
/>
))}
</div>
{createSeed && (
<CreateModal
onClose={this.closeCreate}
onStatusChange={onStatusChange}
seed={createSeed}
type={type}
/>
)}
</div>
);
}
if (checks.length === 0 || !mountedRef.current) {
return;
}
private checkMatches (): void {
const results = this.results;
this.results = [];
if (results.length === 0 || !this._isActive) {
return;
}
this.setState(
({ keyCount, keyTime, matches, startAt }: State): Pick<State, never> => {
let newKeyCount = keyCount;
let newKeyTime = keyTime;
const newMatches = results
.reduce((result, { elapsed, found }): GeneratorMatch[] => {
setResults(
({ isRunning, keyCount, keyTime, matches, startAt }: Results): Results => {
let newKeyCount = keyCount;
let newKeyTime = keyTime;
const newMatches = checks.reduce((result, { elapsed, found }): GeneratorMatch[] => {
newKeyCount += found.length;
newKeyTime += elapsed;
return result.concat(found);
}, matches)
.sort(generatorSort)
.slice(0, 25);
const elapsed = Date.now() - startAt;
}, matches);
return {
elapsed,
keyCount: newKeyCount,
keyTime: newKeyTime,
matches: newMatches
};
}
);
}
private executeGeneration = (): void => {
if (!this.state.isRunning) {
this.checkMatches();
return;
}
setImmediate((): void => {
if (this._isActive) {
if (this.results.length === 25) {
this.checkMatches();
return {
elapsed: Date.now() - startAt,
isRunning,
keyCount: newKeyCount,
keyTime: newKeyTime,
matches: newMatches.sort(generatorSort).slice(0, 25),
startAt
};
}
);
},
[mountedRef]
);
const { match, type, withCase, withHex } = this.state;
this.results.push(
generator({
match,
runs: 10,
type,
withCase,
withHex
})
);
this.executeGeneration();
const _executeGeneration = useCallback(
(): void => {
if (!runningRef.current) {
return _checkMatches();
}
});
}
private onCreateToggle = (createSeed: string): void => {
this.setState({ createSeed });
}
setImmediate((): void => {
if (mountedRef.current) {
if (results.current.length === 25) {
_checkMatches();
}
private onChangeCase = (withCase: boolean): void => {
this.setState({ withCase });
}
results.current.push(
generator({ match, runs: 10, type, withCase, withHex: true })
);
private onChangeMatch = (match: string): void => {
this.setState({
_executeGeneration();
}
});
},
[_checkMatches, match, mountedRef, runningRef, type, withCase]
);
const _onChangeMatch = useCallback(
(match: string): void => setMatch({
isMatchValid:
matchRegex.test(match) &&
(match.length !== 0) &&
(match.length < 31),
match
});
}
}),
[]
);
private onChangeType = (type: KeypairType): void => {
this.setState({ type });
}
private onRemove = (address: string): void => {
this.setState(
({ matches }: State): Pick<State, never> => ({
matches: matches.filter((item): boolean =>
item.address !== address
)
const _onRemove = useCallback(
(address: string): void => setResults(
(results: Results): Results => ({
...results,
matches: results.matches.filter((item) => item.address !== address)
})
);
}
),
[]
);
private toggleStart = (): void => {
this.setState(
({ isRunning, keyCount, keyTime, startAt }: State): Pick<State, never> => {
this._isActive = !isRunning;
const _toggleStart = useCallback(
(): void => setResults(
({ elapsed, isRunning, keyCount, keyTime, matches, startAt }: Results): Results => ({
elapsed,
isRunning: !isRunning,
keyCount: isRunning ? keyCount : 0,
keyTime: isRunning ? keyTime : 0,
matches,
startAt: isRunning ? startAt : Date.now()
})
),
[]
);
return {
isRunning: this._isActive,
keyCount: this._isActive ? 0 : keyCount,
keyTime: this._isActive ? 0 : keyTime,
startAt: this._isActive ? Date.now() : startAt
};
},
this.executeGeneration
);
}
useEffect((): void => {
runningRef.current = isRunning;
private closeCreate = (): void => {
this.setState({ createSeed: null });
}
if (isRunning) {
_executeGeneration();
}
}, [_executeGeneration, isRunning]);
return (
<div className={className}>
<div className='ui--row'>
<Input
autoFocus
className='medium'
help={t('Type here what you would like your address to contain. This tool will generate the keys and show the associated addresses that best match your search. You can use "?" as a wildcard for a character.')}
isDisabled={isRunning}
isError={!isMatchValid}
label={t('Search for')}
onChange={_onChangeMatch}
onEnter={_toggleStart}
value={match}
/>
<Dropdown
className='medium'
help={t('Should the search be case sensitive, e.g if you select "no" your search for "Some" may return addresses containing "somE" or "sOme"...')}
isDisabled={isRunning}
label={t('case sensitive')}
onChange={setWithCase}
options={BOOL_OPTIONS}
value={withCase}
/>
</div>
<div className='ui--row'>
<Dropdown
className='medium'
defaultValue={type}
help={t('Determines what cryptography will be used to create this account. Note that to validate on Polkadot, the session account must use "ed25519".')}
label={t('keypair crypto type')}
onChange={setType}
options={uiSettings.availableCryptos}
/>
</div>
<Button.Group>
<Button
icon={
isRunning
? 'stop'
: 'sign-in'
}
isDisabled={!isMatchValid}
label={
isRunning
? t('Stop generation')
: t('Start generation')
}
onClick={_toggleStart}
/>
</Button.Group>
{matches.length !== 0 && (
<Table
className='vanity--App-matches'
empty={t('No matches found')}
header={[
[t('matches'), 'start', 2],
[t('Evaluated {{count}} keys in {{elapsed}}s ({{avg}} keys/s)', {
replace: {
avg: (keyCount / (elapsed / 1000)).toFixed(3),
count: keyCount,
elapsed: (elapsed / 1000).toFixed(2)
}
}), 'start'],
[t('secret'), 'start'],
[]
]}
>
{matches.map((match): React.ReactNode => (
<Match
{...match}
key={match.address}
onCreateToggle={setCreateSeed}
onRemove={_onRemove}
/>
))}
</Table>
)}
{createSeed && (
<CreateModal
onClose={_clearSeed}
onStatusChange={onStatusChange}
seed={createSeed}
type={type}
/>
)}
</div>
);
}
export default translate(
styled(VanityApp)`
.vanity--App-matches {
padding: 1em 0;
}
export default React.memo(styled(VanityApp)`
.vanity--App-matches {
padding: 1em 0;
}
.vanity--App-stats {
padding: 1em 0 0 0;
opacity: 0.45;
text-align: center;
}
`
);
.vanity--App-stats {
padding: 1em 0 0 0;
opacity: 0.45;
text-align: center;
}
`);