Skip to content
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

Fix: calculate genesis id properly #1359

Merged
merged 4 commits into from
Jul 19, 2023
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 app/StyledApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { getThemeById } from './theme';
import { init } from './sentry';
import WriteFilePermissionError from './screens/modal/WriteFilePermissionError';
import NoInternetConnection from './screens/modal/NoInternetConnection';
import GenesisIDMigrationFailed from './screens/modal/GenesisIDMigrationFailed';

const history = createMemoryHistory();

Expand Down Expand Up @@ -68,6 +69,7 @@ const StyledApp = () => {
))}
<Redirect to="/auth" />
</Switch>
<GenesisIDMigrationFailed />
<WriteFilePermissionError />
<NoInternetConnection />
<CloseAppModal />
Expand Down
6 changes: 4 additions & 2 deletions app/redux/ui/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { RootState } from '../../types';

export const getWarnings = (state: RootState) => state.ui.warnings;

export const getWarningByType = (type: WarningType) => (state: RootState) =>
export const getWarningByType = <T extends WarningType>(type: T) => (
state: RootState
) =>
getWarnings(state).find((w) => w.type === type) as
| WarningObject<WarningType.WriteFilePermission>
| WarningObject<T>
| undefined;
125 changes: 125 additions & 0 deletions app/screens/modal/GenesisIDMigrationFailed.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import React from 'react';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { WarningType } from '../../../shared/warning';
import { Button } from '../../basicComponents';
import Modal from '../../components/common/Modal';
import { eventsService } from '../../infra/eventsService';
import { getWarningByType } from '../../redux/ui/selectors';
import { smColors } from '../../vars';
import { omitWarning } from '../../redux/ui/actions';
import ReactPortal from './ReactPortal';

const ButtonsWrapper = styled.div<{ hasSingleButton?: boolean }>`
display: flex;
flex-direction: row;
justify-content: ${({ hasSingleButton }) =>
hasSingleButton ? 'center' : 'space-between'};
margin: auto 0 15px 0;
padding-top: 30px;
`;

const ErrorMessage = styled.pre`
font-size: 14px;
line-height: 1.33em;
word-wrap: break-word;
white-space: pre-wrap;
flex: 1;
overflow-y: auto;
height: 150px;
`;

const Code = styled.pre`
display: inline-block;
padding: 0.1em 0.4em;
background: ${smColors.black20Alpha};
border-radius: ${({ theme }) => theme.popups.boxRadius / 2}px;
margin-top: 0.2em;

direction: rtl;
text-overflow: ellipsis;
text-align: right;
max-width: 260px;
overflow: hidden;

margin-bottom: -0.4em;
margin-top: 0.4em;

cursor: pointer;
&:hover,
&:focus {
background: ${smColors.black30Alpha};
}
`;

const RedText = styled.span`
color: ${smColors.red};
`;

const GenesisIDMigrationFailed = () => {
const dispatch = useDispatch();
const warning = useSelector(
getWarningByType(WarningType.GenesisIDMigrationFailed)
);
if (!warning) {
return null;
}
const handleDismiss = () => {
dispatch(omitWarning(warning));
};

const revealInFinder = (filePath: string) => () =>
eventsService.showFileInFolder({ filePath });

return (
<ReactPortal modalId="spacemesh-genesis-id-migration-failed">
<Modal
header="Error"
subHeader="Cannot move files under correct Genesis ID"
width={600}
height={450}
>
<ErrorMessage>
<RedText>{warning.message}</RedText>
{'\n\n'}
<ul style={{ fontSize: '12px' }}>
<li>Please, check and rename these files/directories:</li>
<li>
1.
<Code onClick={revealInFinder(warning.payload.nodeConfig.prev)}>
{warning.payload.nodeConfig.prev}
</Code>
&nbsp;&rarr;&nbsp;
<Code onClick={revealInFinder(warning.payload.nodeConfig.next)}>
{warning.payload.nodeConfig.next}
</Code>
</li>
<li>
2.
<Code onClick={revealInFinder(warning.payload.nodeData.prev)}>
{warning.payload.nodeData.prev}
</Code>
&nbsp;&rarr;&nbsp;
<Code onClick={revealInFinder(warning.payload.nodeData.next)}>
{warning.payload.nodeData.next}
</Code>
</li>
<li style={{ marginTop: '1em' }}>
Note: Smapp does not rename the PoS directory.
<br />
<RedText>
Please, ensure that Smapp is using correct node-config and PoS
data.
</RedText>
</li>
</ul>
</ErrorMessage>
<ButtonsWrapper>
<Button isPrimary={false} onClick={handleDismiss} text="DISMISS" />
</ButtonsWrapper>
</Modal>
</ReactPortal>
);
};

export default GenesisIDMigrationFailed;
4 changes: 2 additions & 2 deletions desktop/NodeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { debounce } from 'throttle-debounce';
import rotator from 'logrotate-stream';
import { Subject } from 'rxjs';
import { ipcConsts } from '../app/vars';
import { debounceShared, delay } from '../shared/utils';
import { debounceShared, delay, getShortGenesisId } from '../shared/utils';
import { DEFAULT_NODE_STATUS } from '../shared/constants';
import {
HexString,
Expand Down Expand Up @@ -368,7 +368,7 @@ class NodeManager extends AbstractManager {
const nodePath = getNodePath();
const nodeDataFilesPath = path.join(
StoreService.get('node.dataPath'),
this.genesisID.substring(0, 8)
getShortGenesisId(this.genesisID)
);
const logFilePath = getNodeLogsPath(this.genesisID);

Expand Down
4 changes: 2 additions & 2 deletions desktop/SmesherManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
PostSetupStatus,
} from '../shared/types';
import { Event } from '../proto/spacemesh/v1/Event';
import { delay } from '../shared/utils';
import { delay, getShortGenesisId } from '../shared/utils';
import SmesherService from './SmesherService';
import Logger from './logger';
import AbstractManager from './AbstractManager';
Expand Down Expand Up @@ -75,7 +75,7 @@ class SmesherManager extends AbstractManager {
const DEFAULT_KEYBIN_PATH = path.resolve(
app.getPath('home'),
'./post/',
genesisID.substring(0, 8)
getShortGenesisId(genesisID)
);
return R.pathOr(
DEFAULT_KEYBIN_PATH,
Expand Down
8 changes: 5 additions & 3 deletions desktop/main/Networks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { hash } from '@spacemesh/sm-codec';
import { app } from 'electron';
import { Network, NodeConfig, PublicService } from '../../shared/types';
import { parseISODate } from '../../shared/datetime';
import { toHexString } from '../../shared/utils';
import { getStandaloneNetwork, isTestMode } from '../testMode';
import { fetchJSON, isDevNet } from '../utils';
Expand All @@ -11,7 +12,8 @@ import { toPublicService } from './utils';
//

export const generateGenesisID = (genesisTime: string, extraData: string) => {
return `${toHexString(hash(genesisTime + extraData)).substring(0, 40)}`;
const time = parseISODate(genesisTime).getTime() / 1000;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parseISODate returns milliseconds?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah

Agree about fetching from grpc, but we're indexing networks by genesis id (auto-connect to them, store logs using it and etc) — so we need it earlier (and even if Node does not work).

But probably Smapp should show some alerts in case the calculated genesis id and the one returned from API are different.

return toHexString(hash(`${time}${extraData}`)).substring(0, 40);
};

export const generateGenesisIDFromConfig = (nodeConfig: NodeConfig) => {
Expand All @@ -20,8 +22,8 @@ export const generateGenesisIDFromConfig = (nodeConfig: NodeConfig) => {
nodeConfig?.genesis?.['genesis-extra-data']
) {
return generateGenesisID(
nodeConfig.genesis['genesis-time'] || '',
nodeConfig.genesis['genesis-extra-data'] || ''
nodeConfig.genesis['genesis-time'],
nodeConfig.genesis['genesis-extra-data']
);
}

Expand Down
12 changes: 6 additions & 6 deletions desktop/main/NodeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Warning, {
} from '../../shared/warning';
import { fetchNodeConfig } from '../utils';
import StoreService from '../storeService';
import { getShortGenesisId } from '../../shared/utils';
import { NODE_CONFIG_FILE, USERDATA_DIR } from './constants';
import { generateGenesisIDFromConfig } from './Networks';
import { safeSmeshingOpts } from './smeshingOpts';
Expand Down Expand Up @@ -42,16 +43,15 @@ export const writeNodeConfig = async (config: NodeConfig): Promise<void> => {
};

const getCustomNodeConfigName = (genesisID: string) =>
`node-config.${genesisID.substring(0, 8)}.json`;
`node-config.${getShortGenesisId(genesisID)}.json`;

export const getCustomNodeConfigPath = (genesisID: string) =>
path.join(USERDATA_DIR, getCustomNodeConfigName(genesisID));

export const loadCustomNodeConfig = async (
genesisID: string
): Promise<Partial<NodeConfig>> => {
const customConfigPath = path.join(
USERDATA_DIR,
getCustomNodeConfigName(genesisID)
);

const customConfigPath = getCustomNodeConfigPath(genesisID);
return existsSync(customConfigPath)
? fs
.readFile(customConfigPath, {
Expand Down
10 changes: 5 additions & 5 deletions desktop/main/smeshingOpts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { homedir } from 'os';
import { resolve } from 'path';
import Bech32 from '@spacemesh/address-wasm';
import { HexString } from '../../shared/types';
import { fromHexString } from '../../shared/utils';
import { fromHexString, getShortGenesisId } from '../../shared/utils';
import { DEFAULT_SMESHING_BATCH_SIZE } from './constants';

export type NoSmeshingDefaults = {
Expand Down Expand Up @@ -44,14 +44,14 @@ export const isSmeshingOpts = (a: any): a is SmeshingOpts =>
a['smeshing-opts']['smeshing-opts-numunits'] >= 1 &&
a['smeshing-opts']['smeshing-opts-provider'] >= 0;

export const getDefaultPosDir = (genesisId: HexString) =>
resolve(homedir(), `./post/${getShortGenesisId(genesisId)}`);

export const safeSmeshingOpts = (
opts: any,
genesisId: HexString
): ValidSmeshingOpts => {
const defaultPosDir = resolve(
homedir(),
`./post/${genesisId.substring(0, 8)}`
);
const defaultPosDir = getDefaultPosDir(genesisId);
const defaultSmeshingOpts = {
'smeshing-opts': {
'smeshing-opts-datadir': defaultPosDir,
Expand Down
8 changes: 6 additions & 2 deletions desktop/main/sources/currentNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
iif,
map,
Observable,
share,
Subject,
switchMap,
} from 'rxjs';
Expand All @@ -20,7 +21,6 @@ export default (
) =>
$networks.pipe(
combineLatestWith($runNodeBeforeLogin, $wallet),
distinctUntilChanged(),
switchMap(([_, runNodeOnStart, wallet]) => {
return iif(
() => runNodeOnStart && !wallet,
Expand All @@ -34,8 +34,12 @@ export default (
)
);
}),
distinctUntilChanged(
(prev, next) => prev[0] === next[0] && prev[1] === next[1]
),
map(
([networks, genesisID]) =>
find((net) => net.genesisID === genesisID, networks) || null
)
),
share()
);
5 changes: 5 additions & 0 deletions desktop/main/sources/fetchDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { handleIPC, handlerResult, makeSubscription } from '../rx.utils';
import { fetchNodeConfig } from '../../utils';
import { Managers } from '../app.types';
import Logger from '../../logger';
import { getWrongGenesisID } from '../../migrations/migrateWrongGenesisId';

const logger = Logger({ className: 'fetchDiscovery' });

Expand All @@ -50,6 +51,10 @@ export const withGenesisID = () =>
(net, i): Network => ({
...net,
genesisID: generateGenesisIDFromConfig(configs[i]),
_wrongGenesisID: getWrongGenesisID(
configs[i].genesis['genesis-time'],
configs[i].genesis['genesis-extra-data']
),
})
);
})
Expand Down
Loading
Loading