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

Refactor: replace 'HexUtils' with lumos functionalities #2718

Merged
merged 10 commits into from
Jul 20, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import LockInfoDialog from 'components/LockInfoDialog'
import { useState as useGlobalState } from 'states'
import styles from './cellsCard.module.scss'

const TabsVariantWithCellsCard: FC<VariantProps<{
title: string
cells: (State.DetailedInput | State.DetailedOutput)[]
}>> = ({ tabs, selectedTab, onTabChange }) => {
const TabsVariantWithCellsCard: FC<
VariantProps<{
title: string
cells: (State.DetailedInput | State.DetailedOutput)[]
}>
> = ({ tabs, selectedTab, onTabChange }) => {
const [t] = useTranslation()
const {
chain: { networkID },
Expand Down
10 changes: 6 additions & 4 deletions packages/neuron-ui/src/components/NervosDAODetail/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ import styles from './nervosDAODetail.module.scss'
import hooks from './hooks'
import CellsCard from './CellsCard'

const TabsVariantWithTxTypes: FC<VariantProps<{
title: string
hash: string
}>> = ({ tabs, selectedTab, onTabChange }) => {
const TabsVariantWithTxTypes: FC<
VariantProps<{
title: string
hash: string
}>
> = ({ tabs, selectedTab, onTabChange }) => {
const [t] = useTranslation()
const [transaction, setTransaction] = useState(transactionState)
const [error, setError] = useState<string>()
Expand Down
1 change: 1 addition & 0 deletions packages/neuron-wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
},
"dependencies": {
"@ckb-lumos/base": "0.20.0-alpha.3",
"@ckb-lumos/bi": "0.20.0-alpha.3",
"@ckb-lumos/ckb-indexer": "0.20.0-alpha.3",
"@ckb-lumos/codec": "0.20.0-alpha.3",
"@ckb-lumos/rpc": "0.20.0-alpha.3",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BI } from '@ckb-lumos/bi'
import { Subject } from 'rxjs'
import { queue, QueueObject } from 'async'
import { HexString, QueryOptions } from '@ckb-lumos/base'
Expand All @@ -10,7 +11,6 @@ import SyncProgressService from '../../services/sync-progress'
import { BlockTips, LumosCellQuery, Connector, AppendScript } from './connector'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { FetchTransactionReturnType, LightRPC, LightScriptFilter } from '../../utils/ckb-rpc'
import HexUtils from '../../utils/hex'
import Multisig from '../../services/multisig'
import { SyncAddressType } from '../../database/chain/entities/sync-progress'
import WalletService from '../../services/wallets'
Expand Down Expand Up @@ -118,7 +118,7 @@ export default class LightConnector extends Connector<CKBComponents.Hash> {
hashType: v.hashType,
args: v.args,
},
blockRange: [HexUtils.toHex(v.blockStartNumber), HexUtils.toHex(v.blockEndNumber)],
blockRange: [BI.from(v.blockStartNumber).toHexString(), BI.from(v.blockEndNumber).toHexString()],
scriptType: v.scriptType,
cursor: v.cursor,
})
Expand All @@ -135,7 +135,7 @@ export default class LightConnector extends Connector<CKBComponents.Hash> {
) {
this.syncQueue.push({
script: syncScript.script,
blockRange: [HexUtils.toHex(syncStatus.blockEndNumber), syncScript.blockNumber],
blockRange: [BI.from(syncStatus.blockEndNumber).toHexString(), syncScript.blockNumber],
scriptType: syncScript.scriptType,
cursor: undefined,
})
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/database/address/meta.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { bytes } from '@ckb-lumos/codec'
import { Address, AddressVersion } from '../../models/address'
import { AddressType } from '../../models/keys/address'
import Script from '../../models/chain/script'
Expand Down Expand Up @@ -116,6 +117,6 @@ export default class AddressMeta implements Address {
public generateChequeLockScriptWithReceiverLockHash(): Script {
const defaultLockScript = this.generateDefaultLockScript()
const assetAccountInfo = new AssetAccountInfo()
return assetAccountInfo.generateChequeScript(defaultLockScript.computeHash(), '0'.repeat(40))
return assetAccountInfo.generateChequeScript(defaultLockScript.computeHash(), bytes.hexify(Buffer.alloc(20)))
}
}
42 changes: 26 additions & 16 deletions packages/neuron-wallet/src/models/asset-account-info.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { bytes, molecule } from '@ckb-lumos/codec'
import CellDep, { DepType } from './chain/cell-dep'
import Script, { ScriptHashType } from './chain/script'
import OutPoint from './chain/out-point'
import NetworksService from '../services/networks'
import Transaction from './chain/transaction'
import HexUtils from '../utils/hex'
import SystemScriptInfo from './system-script-info'
import { Address } from './address'
import { createFixedHexBytesCodec } from '@ckb-lumos/codec/lib/blockchain'

export interface ScriptCellInfo {
cellDep: CellDep
Expand Down Expand Up @@ -244,9 +245,7 @@ export default class AssetAccountInfo {
}

public generateChequeScript(receiverLockHash: string, senderLockHash: string): Script {
const receiverLockHash20 = HexUtils.removePrefix(receiverLockHash).slice(0, 40)
const senderLockHash20 = HexUtils.removePrefix(senderLockHash).slice(0, 40)
const args = `0x${receiverLockHash20}${senderLockHash20}`
const args = bytes.hexify(bytes.concat(receiverLockHash.slice(0, 42), senderLockHash.slice(0, 42)))
const info = this.chequeInfo
return new Script(info.codeHash, args, info.hashType)
}
Expand Down Expand Up @@ -286,20 +285,31 @@ export default class AssetAccountInfo {
}

public static findSignPathForCheque(addressInfos: Address[], chequeLockArgs: string) {
const receiverLockHash = HexUtils.removePrefix(chequeLockArgs).slice(0, 40)
const senderLockHash = HexUtils.removePrefix(chequeLockArgs).slice(40)
const Bytes20 = createFixedHexBytesCodec(20)
const ChequeLockArgsCodec = molecule.struct(
{
receiverLockHash: Bytes20,
senderLockHash: Bytes20,
},
['receiverLockHash', 'senderLockHash']
)

for (const lockHash20 of [receiverLockHash, senderLockHash]) {
const foundAddressInfo = addressInfos.find(info => {
const defaultLockScript = SystemScriptInfo.generateSecpScript(info.blake160)
const addressLockHash20 = HexUtils.removePrefix(defaultLockScript.computeHash()).slice(0, 40)
return lockHash20 === addressLockHash20
})
if (foundAddressInfo) {
return foundAddressInfo
}
const { receiverLockHash, senderLockHash } = ChequeLockArgsCodec.unpack(chequeLockArgs)

const foundReceiver = addressInfos.find(info => {
const target = bytes.bytify(SystemScriptInfo.generateSecpScript(info.blake160).computeHash()).slice(0, 20)
return bytes.equal(target, receiverLockHash)
})

if (foundReceiver) {
return foundReceiver
}

return null
const foundSender = addressInfos.find(info => {
const target = bytes.bytify(SystemScriptInfo.generateSecpScript(info.blake160).computeHash()).slice(0, 20)
return bytes.equal(target, senderLockHash)
})

return foundSender || null
}
}
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/models/chain/input.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import OutPoint from './out-point'
import Script from './script'
import HexUtils from '../../utils/hex'
import { BI } from '@ckb-lumos/bi'
import TypeChecker from '../../utils/type-checker'

export default class Input {
Expand Down Expand Up @@ -112,7 +112,7 @@ export default class Input {

public toSDK(): CKBComponents.CellInput {
return {
since: HexUtils.toHex(this.since!),
since: BI.from(this.since || 0).toHexString(),
homura marked this conversation as resolved.
Show resolved Hide resolved
previousOutput: this.previousOutput?.toSDK() || null,
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/models/chain/out-point.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import HexUtils from '../../utils/hex'
import { BI } from '@ckb-lumos/bi'
import TypeChecker from '../../utils/type-checker'

export default class OutPoint {
Expand All @@ -21,7 +21,7 @@ export default class OutPoint {
public toSDK(): CKBComponents.OutPoint {
return {
txHash: this.txHash,
index: HexUtils.toHex(this.index),
index: BI.from(this.index).toHexString(),
}
}

Expand Down
7 changes: 4 additions & 3 deletions packages/neuron-wallet/src/models/chain/output.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Script from './script'
import OutPoint from './out-point'
import HexUtils from '../../utils/hex'
import { bytes as byteUtils } from '@ckb-lumos/codec'
import { BI } from '@ckb-lumos/bi'
import TypeChecker from '../../utils/type-checker'

// sent: pending transaction's output
Expand Down Expand Up @@ -203,7 +204,7 @@ export default class Output {
}

public calculateBytesize(): number {
let bytesize = 8 + HexUtils.byteLength(this.data) + this.lock.calculateBytesize()
let bytesize = 8 + byteUtils.bytify(this.data).byteLength + this.lock.calculateBytesize()
if (this.type) {
bytesize += this.type.calculateBytesize()
}
Expand All @@ -212,7 +213,7 @@ export default class Output {

public toSDK(): CKBComponents.CellOutput {
return {
capacity: HexUtils.toHex(this.capacity),
capacity: BI.from(this.capacity).toHexString(),
lock: this.lock.toSDK(),
type: this.type ? this.type.toSDK() : this.type,
}
Expand Down
14 changes: 10 additions & 4 deletions packages/neuron-wallet/src/models/chain/script.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import HexUtils from '../../utils/hex'
import { bytes as byteUtils } from '@ckb-lumos/codec'
import TypeChecker from '../../utils/type-checker'

export enum ScriptHashType {
Expand Down Expand Up @@ -34,12 +34,18 @@ export default class Script {
}

public computeHash(): string {
const hash: string = scriptToHash(this.toSDK())
return HexUtils.addPrefix(hash)
return scriptToHash(this.toSDK())
}

/**
* @deprecated please move to `calculateOccupiedByteSize`
*/
public calculateBytesize(): number {
homura marked this conversation as resolved.
Show resolved Hide resolved
return 1 + HexUtils.byteLength(this.codeHash) + HexUtils.byteLength(this.args)
return this.calculateOccupiedByteSize()
}

public calculateOccupiedByteSize(): number {
return 1 + byteUtils.concat(this.args, this.codeHash).byteLength
}

public toSDK(): CKBComponents.Script {
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/models/chain/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import CellDep from './cell-dep'
import Input from './input'
import Output from './output'
import WitnessArgs from './witness-args'
import HexUtils from '../../utils/hex'
import { BI } from '@ckb-lumos/bi'
import { serializeWitnessArgs, rawTransactionToHash } from '@nervosnetwork/ckb-sdk-utils'
import BlockHeader from './block-header'
import TypeCheckerUtils from '../../utils/type-checker'
Expand Down Expand Up @@ -273,7 +273,7 @@ export default class Transaction {

public toSDKRawTransaction(): CKBComponents.RawTransaction {
return {
version: HexUtils.toHex(this.version),
version: BI.from(this.version).toHexString(),
inputs: this.inputs.map(i => i.toSDK()),
outputs: this.outputs.map(o => o.toSDK()),
cellDeps: this.cellDeps.map(cd => cd.toSDK()),
Expand Down
8 changes: 4 additions & 4 deletions packages/neuron-wallet/src/models/transaction-size.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { serializeOutput, serializeWitnessArgs } from '@nervosnetwork/ckb-sdk-utils/lib/serialization/transaction'
import HexUtils from '../utils/hex'
import { serializeFixVec } from '@nervosnetwork/ckb-sdk-utils/lib/serialization'
import Output from './chain/output'
import WitnessArgs from './chain/witness-args'
import Transaction from './chain/transaction'
import Multisig from './multisig'
import Script, { ScriptHashType } from './chain/script'
import BufferUtils from '../utils/buffer'
import { bytes as byteUtils } from '@ckb-lumos/codec'

export default class TransactionSize {
public static SERIALIZED_OFFSET_BYTESIZE = 4
Expand All @@ -29,7 +29,7 @@ export default class TransactionSize {

public static output(output: Output): number {
const bytes = serializeOutput(output.toSDK())
return HexUtils.byteLength(bytes) + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
return byteUtils.bytify(bytes).byteLength + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
}

public static ckbAnyoneCanPayOutput(): number {
Expand All @@ -56,7 +56,7 @@ export default class TransactionSize {

public static outputData(data: string): number {
const bytes = serializeFixVec(data)
return HexUtils.byteLength(bytes) + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
return byteUtils.bytify(bytes).byteLength + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
}

// TODO: and here
Expand All @@ -68,7 +68,7 @@ export default class TransactionSize {
public static witness(witness: WitnessArgs | string): number {
const wit: string = typeof witness === 'string' ? witness : serializeWitnessArgs(witness.toSDK())
const bytes = serializeFixVec(wit)
return HexUtils.byteLength(bytes) + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
return byteUtils.bytify(bytes).byteLength + TransactionSize.SERIALIZED_OFFSET_BYTESIZE
}

public static secpLockWitness(): number {
Expand Down
19 changes: 16 additions & 3 deletions packages/neuron-wallet/src/services/hardware/ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { takeUntil, filter, scan } from 'rxjs/operators'
import Transaction from '../../models/chain/transaction'
import NodeService from '../../services/node'
import Address, { AddressType } from '../../models/keys/address'
import HexUtils from '../../utils/hex'
import logger from '../../utils/logger'
import NetworksService from '../../services/networks'
import { generateRPC } from '../../utils/ckb-rpc'
Expand Down Expand Up @@ -76,13 +75,13 @@ export default class Ledger extends Hardware {
}

async signMessage(path: string, messageHex: string) {
const message = HexUtils.removePrefix(messageHex)
const message = this.removePrefix(messageHex)
const signed = await this.ledgerCKB!.signMessage(
path === Address.pathForReceiving(0) ? this.defaultPath : path,
message,
false
)
return HexUtils.addPrefix(signed)
return this.addPrefix(signed)
}

async getAppVersion(): Promise<string> {
Expand Down Expand Up @@ -149,4 +148,18 @@ export default class Ledger extends Hardware {
.catch(() => [] as DeviceInfo[])
)
}

private removePrefix(hex: string): string {
if (hex.startsWith('0x')) {
return hex.slice(2)
}
return hex
}

private addPrefix(hex: string): string {
if (hex.startsWith('0x')) {
return hex
}
return `0x${hex}`
}
}
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/services/node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from 'fs'
import path from 'path'
import { BI } from '@ckb-lumos/bi'
import { app as electronApp, dialog, shell } from 'electron'
import { t } from 'i18next'
import { interval, BehaviorSubject, merge } from 'rxjs'
Expand All @@ -17,7 +18,6 @@ import logger from '../utils/logger'
import redistCheck from '../utils/redist-check'
import { rpcRequest } from '../utils/rpc-request'
import { generateRPC } from '../utils/ckb-rpc'
import HexUtils from '..//utils/hex'
import startMonitor from './monitor'
import { CKBLightRunner } from './light-runner'

Expand Down Expand Up @@ -119,7 +119,7 @@ class NodeService {
if (!this.delayTime) {
this.delayTime = 0
}
const tip: string = HexUtils.toDecimal(tipNumber)
const tip: string = BI.from(tipNumber).toString()
this._tipBlockNumber = tip
this.tipNumberSubject.next(tip)
},
Expand Down
6 changes: 3 additions & 3 deletions packages/neuron-wallet/src/services/transaction-sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import Script from '../models/chain/script'
import Multisig from '../models/multisig'
import Blake2b from '../models/blake2b'
import logger from '../utils/logger'
import HexUtils from '../utils/hex'
import { bytes as byteUtils } from '@ckb-lumos/codec'
import SystemScriptInfo from '../models/system-script-info'
import AddressParser from '../models/address-parser'
import HardwareWalletService from './hardware'
Expand Down Expand Up @@ -400,15 +400,15 @@ export default class TransactionSender {
lock: `0x` + serializedMultiSign.slice(2) + '0'.repeat(130 * m),
})
const serializedEmptyWitness = serializeWitnessArgs(emptyWitness.toSDK())
const serializedEmptyWitnessSize = HexUtils.byteLength(serializedEmptyWitness)
const serializedEmptyWitnessSize = byteUtils.bytify(serializedEmptyWitness).byteLength
const blake2b = new Blake2b()
blake2b.update(txHash)
blake2b.update(toUint64Le(`0x${serializedEmptyWitnessSize.toString(16)}`))
blake2b.update(serializedEmptyWitness)

restWitnesses.forEach(w => {
const wit: string = typeof w === 'string' ? w : serializeWitnessArgs(w.toSDK())
const byteLength = HexUtils.byteLength(wit)
const byteLength = byteUtils.bytify(wit).byteLength
blake2b.update(toUint64Le(`0x${byteLength.toString(16)}`))
blake2b.update(wit)
})
Expand Down
Loading