Skip to content

Commit

Permalink
feat: Add check ckb node update or compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
yanguoyu committed Aug 16, 2023
1 parent 64c416e commit 6c004f7
Show file tree
Hide file tree
Showing 17 changed files with 195 additions and 74 deletions.
1 change: 1 addition & 0 deletions packages/neuron-ui/src/containers/Main/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const MainContent = () => {
show={!!globalAlertDialog}
title={globalAlertDialog?.title}
message={globalAlertDialog?.message}
action={globalAlertDialog?.action}
type={globalAlertDialog?.type ?? 'success'}
onCancel={onCancelGlobalDialog}
/>
Expand Down
58 changes: 55 additions & 3 deletions packages/neuron-ui/src/containers/Navbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ import React, { useCallback, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { useLocation, NavLink, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { NeuronWalletActions, useDispatch, useState as useGlobalState } from 'states'
import { checkForUpdates } from 'services/remote'
import { NeuronWalletActions, showGlobalAlertDialog, useDispatch, useState as useGlobalState } from 'states'
import {
VerifyCkbVersionResult,
VerifyExternalCkbNodeRes,
checkForUpdates,
getVersion,
verifyExternalCkbNode,
} from 'services/remote'
import { AppUpdater as AppUpdaterSubject } from 'services/subjects'
import Badge from 'widgets/Badge'
import Logo from 'widgets/Icons/Logo.png'
Expand All @@ -18,7 +24,7 @@ import {
ArrowOpenRight,
MenuExpand,
} from 'widgets/Icons/icon'
import { RoutePath, clsx, useOnLocaleChange } from 'utils'
import { RoutePath, clsx, isSuccessResponse, useOnLocaleChange } from 'utils'
import Tooltip from 'widgets/Tooltip'

import styles from './navbar.module.scss'
Expand Down Expand Up @@ -105,6 +111,52 @@ const Navbar = () => {
}
}, [])

const [verifyCkbResult, setVerifyCkbResult] = useState<VerifyExternalCkbNodeRes>()

useEffect(() => {
verifyExternalCkbNode().then(res => {
if (isSuccessResponse(res) && res.result) {
setVerifyCkbResult(res.result)
}
})
}, [])

useEffect(() => {
if (!verifyCkbResult) {
return
}
switch (verifyCkbResult.ckb) {
case VerifyCkbVersionResult.Same:
case VerifyCkbVersionResult.Compatibility:
if (!verifyCkbResult.withIndexer) {
showGlobalAlertDialog({
type: 'warning',
message: t('navbar.ckb-without-indexer'),
action: 'ok',
})(dispatch)
}
break
case VerifyCkbVersionResult.ShouldUpdate:
if (version) {
showGlobalAlertDialog({
type: 'warning',
message: t('navbar.update-neuron-with-ckb', { version: getVersion() }),
action: 'ok',
})(dispatch)
}
break
case VerifyCkbVersionResult.NotCompatibility:
showGlobalAlertDialog({
type: 'warning',
message: t('navbar.ckb-node-compatible', { version: getVersion() }),
action: 'ok',
})(dispatch)
break
default:
break
}
}, [verifyCkbResult, version])

useEffect(() => {
if (pathname.includes(RoutePath.Settings)) {
setIsClickedSetting(true)
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"sync-not-start": "Sync not started yet",
"connecting": "Connecting",
"experimental-functions": "Experimental",
"s-udt": "Asset Accounts"
"s-udt": "Asset Accounts",
"update-neuron-with-ckb": "The version of the CKB node does not match Neuron (v{{ version }}), which may cause compatibility issues. Please update to the latest version of Neuron.",
"ckb-node-compatible": "CKB node is not compatible with Neuron (v{{ version }}), please check before using it.",
"ckb-without-indexer": "Please add '--indexer' option to start local node"
},
"network-status": {
"tooltip": {
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/zh-tw.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"sync-not-start": "同步尚未開始",
"connecting": "正在連接節點",
"experimental-functions": "實驗性功能",
"s-udt": "資產賬戶"
"s-udt": "資產賬戶",
"update-neuron-with-ckb": "CKB 節點版本與 Neuron v({{ version }} 不匹配,可能導致兼容性問題。請更新到最新版 Neuron。",
"ckb-node-compatible": "CKB 節點版本與 Neuron v({{ version }}) 不兼容,請檢查後使用。",
"ckb-without-indexer": "請添加 '--indexer' 參數來啟動本地節點"
},
"network-status": {
"tooltip": {
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"sync-not-start": "同步尚未开始",
"connecting": "正在连接节点",
"experimental-functions": "实验性功能",
"s-udt": "资产账户"
"s-udt": "资产账户",
"update-neuron-with-ckb": "CKB 节点版本与 Neuron v({{ version }} 不匹配,可能导致兼容性问题。请更新到最新版 Neuron。",
"ckb-node-compatible": "CKB 节点版本与 Neuron v({{ version }}) 不兼容,请检查后使用。",
"ckb-without-indexer": "请添加 '--indexer' 参数来启动本地节点"
},
"network-status": {
"tooltip": {
Expand Down
16 changes: 16 additions & 0 deletions packages/neuron-ui/src/services/remote/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ export const stopProcessMonitor = remoteApi<'ckb'>('stop-process-monitor')
export const startProcessMonitor = remoteApi<'ckb'>('start-process-monitor')
export const getIsCkbRunExternal = remoteApi<void, boolean>('is-ckb-run-external')

export enum VerifyCkbVersionResult {
Same,
Compatibility,
ShouldUpdate,
NotCompatibility,
}

export type VerifyExternalCkbNodeRes =
| {
ckb: VerifyCkbVersionResult
withIndexer: boolean
}
| undefined

export const verifyExternalCkbNode = remoteApi<void, VerifyExternalCkbNodeRes>('verify-external-ckb-node')

export const clearCellCache = remoteApi<Controller.ClearCache.Params>('clear-cache')

export const invokeShowErrorMessage = remoteApi<{ title: string; content: string }>('show-error-message')
Expand Down
1 change: 1 addition & 0 deletions packages/neuron-ui/src/services/remote/remoteApiWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ type Action =
| 'is-dark'
| 'set-theme'
| 'is-ckb-run-external'
| 'verify-external-ckb-node'
// Wallets
| 'get-all-wallets'
| 'get-current-wallet'
Expand Down
1 change: 1 addition & 0 deletions packages/neuron-ui/src/types/App/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ declare namespace State {
title?: string
message?: string
type: 'success' | 'failed' | 'warning'
action?: 'ok' | 'cancel' | 'all'
onClose?: () => void
onOk?: () => void
onCancel?: () => void
Expand Down
1 change: 1 addition & 0 deletions packages/neuron-ui/src/types/Subject/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,6 @@ declare namespace Subject {
title?: string
message?: string
type: 'success' | 'failed' | 'warning'
action?: 'ok' | 'cancel'
}
}
22 changes: 15 additions & 7 deletions packages/neuron-ui/src/widgets/AlertDialog/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useRef } from 'react'
import React, { useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useDialog } from 'utils'
import Button from 'widgets/Button'
Expand All @@ -8,6 +8,7 @@ import Tips from 'widgets/Icons/Tips.png'
import styles from './alertDialog.module.scss'

type AlertType = 'success' | 'failed' | 'warning'
type Action = 'ok' | 'cancel' | 'all'

const AlertDialog = ({
show,
Expand All @@ -17,6 +18,7 @@ const AlertDialog = ({
onClose,
onOk,
onCancel,
action,
}: {
show?: boolean
title?: string
Expand All @@ -25,10 +27,17 @@ const AlertDialog = ({
onClose?: () => void
onOk?: () => void
onCancel?: () => void
action?: Action
}) => {
const [t] = useTranslation()
const dialogRef = useRef<HTMLDialogElement | null>(null)
useDialog({ show, dialogRef, onClose: onClose || (() => {}) })
const actions = useMemo<('cancel' | 'ok')[]>(() => {
if (action) {
return action === 'all' ? ['cancel', 'ok'] : [action]
}
return type === 'warning' ? ['cancel', 'ok'] : ['ok']
}, [action, type])

return (
<dialog ref={dialogRef} className={styles.alertDialog}>
Expand All @@ -38,13 +47,12 @@ const AlertDialog = ({
<h2 className={styles.title}>{title}</h2>
<p className={styles.message}>{message}</p>
<div className={styles.actions}>
{type === 'failed' && <Button type="confirm" onClick={onCancel} label={t('common.confirm')} />}
{type === 'success' && <Button type="confirm" onClick={onCancel || onOk} label={t('common.confirm')} />}
{type === 'warning' && (
<>
{actions.map(v =>
v === 'cancel' ? (
<Button type="cancel" onClick={onCancel} label={t('common.cancel')} />
<Button type="confirm" onClick={onOk} label={t('common.confirm')} />
</>
) : (
<Button type="confirm" onClick={onCancel || onOk} label={t('common.confirm')} />
)
)}
</div>
</dialog>
Expand Down
7 changes: 7 additions & 0 deletions packages/neuron-wallet/src/controllers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,13 @@ export default class ApiController {
}
})

handle('verify-external-ckb-node', async () => {
return {
status: ResponseCode.Success,
result: await NodeService.getInstance().verifyExternalCkbNode(),
}
})

// Wallets

handle('get-all-wallets', async () => {
Expand Down
6 changes: 0 additions & 6 deletions packages/neuron-wallet/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,6 @@ export default {
cancel: 'Cancel',
},
},
'node-version-different': {
message: 'The node version is inconsistent with Neuron(v {{ version }}), please use after confirmation',
},
'ckb-without-indexer': {
message: "Please add '--indexer' option to start local node",
},
},
prompt: {
password: {
Expand Down
6 changes: 0 additions & 6 deletions packages/neuron-wallet/src/locales/zh-tw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,6 @@ export default {
cancel: '取消',
},
},
'node-version-different': {
message: '節點版本與 Neuron(v {{ version }}) 不壹致,請確認後使用',
},
'ckb-without-indexer': {
message: "請添加 '--indexer' 參數來啟動本地節點",
},
},
prompt: {
password: {
Expand Down
6 changes: 0 additions & 6 deletions packages/neuron-wallet/src/locales/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,6 @@ export default {
cancel: '取消',
},
},
'node-version-different': {
message: '节点版本与 Neuron(v {{ version }}) 不一致,请确认后使用',
},
'ckb-without-indexer': {
message: "请添加 '--indexer' 参数来启动本地节点",
},
},
prompt: {
password: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const ShowGlobalDialogSubject = new Subject<{
title?: string
message?: string
type: 'success' | 'failed' | 'warning'
action?: 'ok' | 'cancel'
}>()

export default ShowGlobalDialogSubject
54 changes: 33 additions & 21 deletions packages/neuron-wallet/src/services/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ import { generateRPC } from '../utils/ckb-rpc'
import startMonitor from './monitor'
import { CKBLightRunner } from './light-runner'

export enum VerifyCkbVersionResult {
Same,
Compatibility,
ShouldUpdate,
NotCompatibility,
}

const supportCkbVersions = ['0.110', '0.109']

class NodeService {
private static instance: NodeService

Expand Down Expand Up @@ -137,16 +146,22 @@ class NodeService {
const isDefaultCKBNeedStart = await this.isDefaultCKBNeedRestart()
if (isDefaultCKBNeedStart) {
logger.info('CKB:\texternal RPC on default uri not detected, starting bundled CKB node.')
this._isCkbNodeExternal = false
const redistReady = await redistCheck()
await (redistReady ? this.startNode() : this.showGuideDialog())
await startMonitor()
} else {
logger.info('CKB:\texternal RPC on default uri detected, skip starting bundled CKB node.')
this._isCkbNodeExternal = true
const network = NetworksService.getInstance().getCurrent()
if (network.type !== NetworkType.Light) {
await this.verifyNodeVersion()
await this.verifyStartWithIndexer()
}
}

public async verifyExternalCkbNode() {
const network = NetworksService.getInstance().getCurrent()
if (this._isCkbNodeExternal && network.type !== NetworkType.Light) {
return {
ckb: await this.verifyCkbNodeVersion(),
withIndexer: await this.isStartWithIndexer(),
}
}
}
Expand Down Expand Up @@ -219,38 +234,35 @@ class NodeService {
}
}

private async verifyNodeVersion() {
private async verifyCkbNodeVersion() {
const network = NetworksService.getInstance().getCurrent()
const localNodeInfo = await new RpcService(network.remote).localNodeInfo()
const internalNodeVersion = this.getInternalNodeVersion()
const [internalMajor, internalMinor] = internalNodeVersion?.split('.') ?? []
const [externalMajor, externalMinor] = localNodeInfo.version?.split('.') ?? []
const [internalMajor, internalMinor] = internalNodeVersion?.split('.')?.map(v => +v) ?? []
const [externalMajor, externalMinor] = localNodeInfo.version?.split('.')?.map(v => +v) ?? []

if (internalMajor !== externalMajor || (externalMajor === '0' && internalMinor !== externalMinor)) {
dialog.showMessageBox({
type: 'warning',
message: t('messageBox.node-version-different.message', { version: internalNodeVersion }),
})
if (internalMajor === externalMajor && internalMinor === externalMinor) return VerifyCkbVersionResult.Same
if (internalMajor < externalMajor || (internalMajor === externalMajor && internalMinor < externalMinor)) {
return VerifyCkbVersionResult.ShouldUpdate
}
if (supportCkbVersions.every(v => !localNodeInfo.version.startsWith(v))) {
return VerifyCkbVersionResult.NotCompatibility
}
return VerifyCkbVersionResult.Compatibility
}

private async verifyStartWithIndexer() {
private async isStartWithIndexer() {
const network = NetworksService.getInstance().getCurrent()
try {
const res = await rpcRequest<{ error?: { code: number } }>(network.remote, { method: 'get_indexer_tip' })
if (res.error?.code === START_WITHOUT_INDEXER) {
logger.info('Node:\tthe ckb node does not start with --indexer')
dialog.showMessageBox({
type: 'warning',
message: t('messageBox.ckb-without-indexer.message'),
})
return false
}
return true
} catch (error) {
logger.info('Node:\tcalling get_indexer_tip failed')
dialog.showMessageBox({
type: 'warning',
message: t('messageBox.ckb-without-indexer.message'),
})
return false
}
}
}
Expand Down
Loading

0 comments on commit 6c004f7

Please sign in to comment.