Skip to content

Commit

Permalink
feat: Prefer network's chain and genesis hash when syncing
Browse files Browse the repository at this point in the history
App should always return data even when node is not available.
  • Loading branch information
ashchan committed Nov 15, 2019
1 parent 74b6fa3 commit 9b5b52c
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 44 deletions.
10 changes: 3 additions & 7 deletions packages/neuron-ui/src/services/remote/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import { apiMethodWrapper } from './apiMethodWrapper'

export const getNeuronWalletState = apiMethodWrapper<void>(controller => () => controller.loadInitData())
export const getNeuronWalletState = apiMethodWrapper<void>(api => () => api.loadInitData())

export const handleViewError = apiMethodWrapper<string>(controller => errorMessage =>
controller.handleViewError(errorMessage)
)
export const contextMenu = apiMethodWrapper<{ type: string; id: string }>(controller => params =>
controller.contextMenu(params)
)
export const handleViewError = apiMethodWrapper<string>(api => errorMessage => api.handleViewError(errorMessage))
export const contextMenu = apiMethodWrapper<{ type: string; id: string }>(api => params => api.contextMenu(params))

export default {
getNeuronWalletState,
Expand Down
31 changes: 16 additions & 15 deletions packages/neuron-wallet/src/controllers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ export default class ApiController {
public static async loadInitData() {
const walletsService = WalletsService.getInstance()
const networksService = NetworksService.getInstance()

const currentWallet = walletsService.getCurrent()
const wallets = walletsService.getAll()

const [
currentWallet = null,
wallets = [],
currentNetworkID = '',
networks = [],
syncedBlockNumber = '0',
connectionStatus = false,
codeHash = '',
] = await Promise.all([
walletsService.getCurrent(),
walletsService.getAll(),
networksService.getCurrentID(),
networksService.getAll(),

Expand All @@ -48,18 +48,21 @@ export default class ApiController {
return '0'
})
.catch(() => '0'),

new Promise(resolve => {
ConnectionStatusSubject.pipe(take(1)).subscribe(
status => {
resolve(status)
},
() => {
resolve(false)
},
status => { resolve(status) },
() => { resolve(false) },
() => { resolve(false) }
)
}),

new Promise(resolve => {
SystemScriptSubject.pipe(take(1)).subscribe(({ codeHash: currentCodeHash }) => resolve(currentCodeHash))
SystemScriptSubject.pipe(take(1)).subscribe(
({ codeHash: currentCodeHash }) => resolve(currentCodeHash),
() => { resolve('') },
() => { resolve('') }
)
}),
])

Expand All @@ -78,7 +81,7 @@ export default class ApiController {

const initState = {
currentWallet,
wallets: [...wallets.map(({ name, id }) => ({ id, name }))],
wallets: wallets,
currentNetworkID,
networks,
addresses,
Expand Down Expand Up @@ -268,9 +271,7 @@ export default class ApiController {
// Transactions

@MapApiResponse
public static async getTransactionList(
params: Controller.Params.TransactionsByKeywords
) {
public static async getTransactionList(params: Controller.Params.TransactionsByKeywords) {
return TransactionsController.getAllByKeywords(params)
}

Expand Down
14 changes: 8 additions & 6 deletions packages/neuron-wallet/src/controllers/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ export default class TransactionsController {
): Promise<Controller.Response<PaginationResult<Transaction> & Controller.Params.TransactionsByKeywords>> {
const { pageNo = 1, pageSize = 15, keywords = '', walletID = '' } = params

const addresses = (await AddressesService.allAddressesByWalletId(walletID)).map(addr => addr.address)
const addresses = AddressesService.allAddressesByWalletId(walletID).map(addr => addr.address)

const transactions = await TransactionsService.getAllByAddresses({ pageNo, pageSize, addresses }, keywords.trim())
const transactions = await TransactionsService
.getAllByAddresses({ pageNo, pageSize, addresses }, keywords.trim())
.catch(() => ({
totalCount: 0,
items: []
}))

if (!transactions) {
throw new ServiceHasNoResponse('Transactions')
}
return {
status: ResponseCode.Success,
result: {
Expand All @@ -64,7 +66,7 @@ export default class TransactionsController {
if (!wallet) {
throw new CurrentWalletNotSet()
}
searchAddresses = (await AddressesService.allAddressesByWalletId(wallet.id)).map(addr => addr.address)
searchAddresses = AddressesService.allAddressesByWalletId(wallet.id).map(addr => addr.address)
}

const transactions = await TransactionsService.getAllByAddresses({ pageNo, pageSize, addresses: searchAddresses })
Expand Down
8 changes: 4 additions & 4 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Store from 'models/store'
import { Validate, Required } from 'decorators'
import { UsedName, NetworkNotFound, InvalidFormat } from 'exceptions'
import { NetworkListSubject, CurrentNetworkIDSubject } from 'models/subjects/networks'
import { MAINNET_GENESIS_HASH, NetworkID, NetworkName, NetworkRemote, NetworksKey, NetworkType, Network, NetworkWithID } from 'types/network'
import { MAINNET_GENESIS_HASH, EMPTY_GENESIS_HASH, NetworkID, NetworkName, NetworkRemote, NetworksKey, NetworkType, Network, NetworkWithID } from 'types/network'
import logger from 'utils/logger'

export const networkSwitchSubject = new BehaviorSubject<undefined | NetworkWithID>(undefined)
Expand Down Expand Up @@ -137,7 +137,7 @@ export default class NetworksService extends Store {
.catch(() => 'ckb_dev')
const genesisHash = await core.rpc
.getBlockHash('0x0')
.catch(() => '0x')
.catch(() => EMPTY_GENESIS_HASH)

const newOne = {
id: uuid(),
Expand Down Expand Up @@ -172,7 +172,7 @@ export default class NetworksService extends Store {

const genesisHash = await core.rpc
.getBlockHash('0x0')
.catch(() => '0x')
.catch(() => EMPTY_GENESIS_HASH)
network.genesisHash = genesisHash
}

Expand Down Expand Up @@ -220,7 +220,7 @@ export default class NetworksService extends Store {

const genesisHash = await core.rpc
.getBlockHash('0x0')
.catch(() => '0x')
.catch(() => EMPTY_GENESIS_HASH)

if (chain && chain !== network.chain && genesisHash && genesisHash !== network.genesisHash) {
this.update(id, { chain, genesisHash })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ networkSwitchSubject.subscribe(async (network: NetworkWithID | undefined) => {
// TODO: only switch if genesisHash is different

await InitDatabase.getInstance().stopAndWait()
const info = await InitDatabase.getInstance().init(network.remote)
const info = await InitDatabase.getInstance().init(network)

DataUpdateSubject.next({
dataType: 'transaction',
Expand Down
23 changes: 13 additions & 10 deletions packages/neuron-wallet/src/startup/sync-block-task/init-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import LockUtils from 'models/lock-utils'
import logger from 'utils/logger'
import genesisBlockHash, { getChain } from './genesis'
import ChainInfo from 'models/chain-info'
import DaoUtils from '../../models/dao-utils';
import DaoUtils from '../../models/dao-utils'
import { NetworkWithID, EMPTY_GENESIS_HASH } from 'types/network'

// only used by main process
export class InitDatabase {
Expand All @@ -19,9 +20,7 @@ export class InitDatabase {
}

private stopped: boolean = false
// private nodeURL: string
private inProcess: boolean = false

private success: boolean = false

public id: number = +new Date()
Expand All @@ -30,25 +29,29 @@ export class InitDatabase {

private killed: boolean = false

public init = async (url: string) => {
public init = async (network: NetworkWithID) => {
if (InitDatabase.previous) {
await InitDatabase.previous.stopAndWait()
}

this.inProcess = true

let hash: string | undefined
let chain: string | undefined
let hash: string = network.genesisHash
let chain: string = network.chain
while (!this.stopped && !this.success) {
try {
hash = await genesisBlockHash(url)
if (hash === EMPTY_GENESIS_HASH) {
hash = await genesisBlockHash(network.remote)
}
await initConnection(hash)
chain = await getChain(url)
if (chain === '') {
chain = await getChain(network.remote)
}
ChainInfo.getInstance().setChain(chain)

try {
const systemScriptInfo = await LockUtils.systemScript(url)
const daoScriptInfo = await DaoUtils.daoScript(url)
const systemScriptInfo = await LockUtils.systemScript(network.remote)
const daoScriptInfo = await DaoUtils.daoScript(network.remote)
updateMetaInfo({ genesisBlockHash: hash, systemScriptInfo, chain, daoScriptInfo })
} catch (err) {
logger.error('update systemScriptInfo failed:', err)
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/types/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export enum NetworkType {
Normal,
}

export const MAINNET_GENESIS_HASH = "0x" // TODO: set this when mainnet launches!
export const MAINNET_GENESIS_HASH = "0xeeee" // TODO: set this when mainnet launches!
export const EMPTY_GENESIS_HASH = "0x"

export interface Network {
name: NetworkName
Expand Down

0 comments on commit 9b5b52c

Please sign in to comment.