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: use lumos to calculate script hash #2802

Merged
merged 7 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import AddressMeta from '../../database/address/meta'
import { scheduler } from 'timers/promises'
import SyncProgressService from '../../services/sync-progress'
import { BlockTips, LumosCellQuery, Connector, AppendScript } from './connector'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { FetchTransactionReturnType, LightRPC, LightScriptFilter } from '../../utils/ckb-rpc'
import Multisig from '../../services/multisig'
import { SyncAddressType } from '../../database/chain/entities/sync-progress'
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/sudt.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import LiveCellService from '../services/live-cell-service'
import AssetAccountInfo from '../models/asset-account-info'
import Script, { ScriptHashType } from '../models/chain/script'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Entity, BaseEntity, Column, PrimaryColumn } from 'typeorm'
import Script, { ScriptHashType } from '../../../models/chain/script'
import OutPoint from '../../../models/chain/out-point'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { OutputStatus } from '../../../models/chain/output'

@Entity()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HexString } from '@ckb-lumos/base'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { Entity, PrimaryColumn, Column } from 'typeorm'

export enum SyncAddressType {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { In, MigrationInterface, QueryRunner } from "typeorm";
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { ScriptHashType } from "../../../models/chain/script";
import Output from "../entities/output";



export class UpdateOutputChequeLockHash1652945662504 implements MigrationInterface {
name = 'UpdateOutputChequeLockHash1652945662504'

Expand Down
13 changes: 11 additions & 2 deletions packages/neuron-wallet/src/models/chain/script.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { bytes as byteUtils } from '@ckb-lumos/codec'
import TypeChecker from '../../utils/type-checker'

Expand Down Expand Up @@ -34,7 +34,16 @@ export default class Script {
}

public computeHash(): string {
return scriptToHash(this.toSDK())
const script = this.toSDK()
if (!script || !script.codeHash || !script.hashType) {
throw new Error('Invalid script')
}
// empty string is not allowed for args
const formattedScript = {
...script,
args: script.args || '0x',
}
return scriptToHash(formattedScript)
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/models/multisig-config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import Multisig from './multisig'

export default class MultisigConfigModel {
Expand Down
5 changes: 3 additions & 2 deletions packages/neuron-wallet/src/models/system-script-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import CellDep, { DepType } from './chain/cell-dep'
import NetworksService from '../services/networks'
import RpcService from '../services/rpc-service'
import Script, { ScriptHashType } from './chain/script'
import { systemScripts } from '@nervosnetwork/ckb-sdk-utils'

export default class SystemScriptInfo {
static SECP_CODE_HASH = process.env.SECP256K1_CODE_HASH!
Expand All @@ -14,9 +15,9 @@ export default class SystemScriptInfo {
static MULTI_SIGN_HASH_TYPE = ScriptHashType.Type

static DAO_SCRIPT_HASH = new Script(
SystemScriptInfo.DAO_CODE_HASH,
systemScripts.NERVOS_DAO.codeHash,
zhangyouxin marked this conversation as resolved.
Show resolved Hide resolved
'0x',
SystemScriptInfo.DAO_HASH_TYPE
systemScripts.NERVOS_DAO.hashType as ScriptHashType
).computeHash()

private static instance: SystemScriptInfo
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/multisig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import MultisigConfig from '../database/chain/entities/multisig-config'
import MultisigOutput from '../database/chain/entities/multisig-output'
import { MultisigConfigNotExistError, MultisigConfigExistError } from '../exceptions/multisig'
import { rpcBatchRequest } from '../utils/rpc-request'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import MultisigOutputChangedSubject from '../models/subjects/multisig-output-db-changed-subject'
import Transaction from '../models/chain/transaction'
import { OutputStatus } from '../models/chain/output'
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/sync-progress.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Equal, getConnection, In, Not } from 'typeorm'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import { HexString } from '@ckb-lumos/base'
import SyncProgress, { SyncAddressType } from '../database/chain/entities/sync-progress'
import WalletService from './wallets'
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/utils/multisig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import Multisig from '../models/multisig'
import MultisigConfigModel from '../models/multisig-config'
import { Signatures, SignStatus } from '../models/offline-sign'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'
import LightConnector from '../../src/block-sync-renderer/sync/light-connector'
import SyncProgress from '../../src/database/chain/entities/sync-progress'
import { BI } from '@ckb-lumos/bi'
Expand Down
53 changes: 35 additions & 18 deletions packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ describe('queue', () => {
const fakeWalletId = 'w1'
const addressInfo: Address = {
address,
blake160: '0xfakeblake160',
blake160: `0x${'0'.repeat(40)}`,
walletId: fakeWalletId,
path: '',
addressType: AddressType.Receiving,
Expand All @@ -123,7 +123,7 @@ describe('queue', () => {
jest.useFakeTimers('legacy')

stubbedBlockTipsSubject = new Subject<Tip>()
stubbedTransactionsSubject = new Subject<{ txHashes: CKBComponents.Hash[], params: unknown }>()
stubbedTransactionsSubject = new Subject<{ txHashes: CKBComponents.Hash[]; params: unknown }>()
const stubbedIndexerConnector = jest.fn().mockImplementation((...args) => {
stubbedIndexerConnectorConstructor(...args)
return {
Expand Down Expand Up @@ -175,11 +175,11 @@ describe('queue', () => {
return {
createBatchRequest() {
return {
exec: stubbedRPCCreateBatchRequestExecFn
exec: stubbedRPCCreateBatchRequestExecFn,
}
}
},
}
}
},
}
})
const Queue = require('../../src/block-sync-renderer/sync/queue').default
Expand Down Expand Up @@ -223,10 +223,17 @@ describe('queue', () => {
beforeEach(() => {
stubbedAddressesFn.mockResolvedValue([true, addresses.map(addressMeta => addressMeta.address), []])
stubbedGetTransactionFn.mockResolvedValue(fakeTxWithStatus1)
stubbedRPCCreateBatchRequestExecFn
.mockResolvedValueOnce(fakeTxs)
.mockResolvedValueOnce(fakeTxs.map(v => ({ ...fakeBlockHeader, timestamp: v.transaction.timestamp, number: v.transaction.blockNumber })))
stubbedTransactionsSubject.next({ txHashes: fakeTxs.map(v => v.transaction.hash), params: fakeTxs[0].transaction.blockNumber })
stubbedRPCCreateBatchRequestExecFn.mockResolvedValueOnce(fakeTxs).mockResolvedValueOnce(
fakeTxs.map(v => ({
...fakeBlockHeader,
timestamp: v.transaction.timestamp,
number: v.transaction.blockNumber,
}))
)
stubbedTransactionsSubject.next({
txHashes: fakeTxs.map(v => v.transaction.hash),
params: fakeTxs[0].transaction.blockNumber,
})
})
describe('when saving transactions is succeeded', () => {
beforeEach(flushPromises)
Expand All @@ -250,11 +257,14 @@ describe('queue', () => {
tx.blockHash = fakeTxWithStatus2.txStatus.blockHash!
tx.blockNumber = BigInt(fakeTxWithStatus2.transaction.blockNumber!).toString()
tx.timestamp = BigInt(fakeTxWithStatus2.transaction.timestamp!).toString()
expect(stubbedSaveFetchFn).toHaveBeenCalledWith(tx, new Set([
addressInfo.blake160,
Multisig.hash([addressInfo.blake160]),
SystemScriptInfo.generateSecpScript(addressInfo.blake160).computeHash().slice(0, 42),
]))
expect(stubbedSaveFetchFn).toHaveBeenCalledWith(
tx,
new Set([
addressInfo.blake160,
Multisig.hash([addressInfo.blake160]),
SystemScriptInfo.generateSecpScript(addressInfo.blake160).computeHash().slice(0, 42),
])
)
}
})
it('checks and generate new addresses', () => {
Expand All @@ -276,10 +286,17 @@ describe('queue', () => {
const err = new Error()
beforeEach(async () => {
stubbedSaveFetchFn.mockRejectedValueOnce(err)
stubbedRPCCreateBatchRequestExecFn
.mockResolvedValueOnce(fakeTxs)
.mockResolvedValueOnce(fakeTxs.map(v => ({ ...fakeBlockHeader, timestamp: v.transaction.timestamp, number: v.transaction.blockNumber })))
stubbedTransactionsSubject.next({ txHashes: fakeTxs.map(v => v.transaction.hash), params: fakeTxs[0].transaction.blockNumber })
stubbedRPCCreateBatchRequestExecFn.mockResolvedValueOnce(fakeTxs).mockResolvedValueOnce(
fakeTxs.map(v => ({
...fakeBlockHeader,
timestamp: v.transaction.timestamp,
number: v.transaction.blockNumber,
}))
)
stubbedTransactionsSubject.next({
txHashes: fakeTxs.map(v => v.transaction.hash),
params: fakeTxs[0].transaction.blockNumber,
})
await flushPromises()
})
it('handles the exception', async () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-wallet/tests/controllers/multisig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ jest.mock('services/wallets', () => ({
return {
getCurrent() {
return jest.fn()
}
},
}
}
},
}))

jest.mock('../../src/services/multisig')
Expand Down
5 changes: 3 additions & 2 deletions packages/neuron-wallet/tests/controllers/sudt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ describe('SUDTController', () => {
'txHash',
'0',
'10000',
Script.fromObject({ codeHash: '', args: '', hashType: ScriptHashType.Type }),
Script.fromObject({ codeHash: '', args: '', hashType: ScriptHashType.Type }),
// codeHash and args are required for Script
Script.fromObject({ codeHash: `0x${'00'.repeat(32)}`, args: '0x', hashType: ScriptHashType.Type }),
Script.fromObject({ codeHash: `0x${'00'.repeat(32)}`, args: '0x', hashType: ScriptHashType.Type }),
'0x080a456972632d320a455432'
)
beforeEach(async () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/neuron-wallet/tests/services/cells.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1091,9 +1091,9 @@ describe('CellsService', () => {
})

describe('#usedByAnyoneCanPayBlake160s', () => {
const fakeArgs1 = '0x1'
const fakeArgs2 = '0x2'
const fakeArgs3 = '0x3'
const fakeArgs1 = '0x01'
const fakeArgs2 = '0x02'
const fakeArgs3 = '0x03'
const codeHash = randomHex()
const lockScript1 = new Script(codeHash, fakeArgs1, ScriptHashType.Type)
const lockScript2 = new Script(codeHash, fakeArgs2, ScriptHashType.Type)
Expand Down
42 changes: 20 additions & 22 deletions packages/neuron-wallet/tests/services/multisig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { OutputStatus } from '../../src/models/chain/output'
import { keyInfos } from '../setupAndTeardown/public-key-info.fixture'
import Multisig from '../../src/models/multisig'
import SystemScriptInfo from '../../src/models/system-script-info'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils'

const [alice, bob, charlie] = keyInfos

Expand Down Expand Up @@ -195,13 +195,11 @@ describe('multisig service', () => {

describe('removeDulpicateConfig', () => {
it('exist duplicate config', () => {
const multisigConfigModel = new MultisigConfigModel(
'walletId',
1,
2,
3,
[alice.publicKeyInBlake160, bob.publicKeyInBlake160, charlie.publicKeyInBlake160],
)
const multisigConfigModel = new MultisigConfigModel('walletId', 1, 2, 3, [
alice.publicKeyInBlake160,
bob.publicKeyInBlake160,
charlie.publicKeyInBlake160,
])
const multisigConfigs = [
MultisigConfig.fromModel(multisigConfigModel),
MultisigConfig.fromModel(multisigConfigModel),
Expand All @@ -212,20 +210,20 @@ describe('multisig service', () => {
})
it('non-exist duplicate config', () => {
const multisigConfigs = [
MultisigConfig.fromModel(new MultisigConfigModel(
'walletId',
1,
2,
3,
[alice.publicKeyInBlake160, bob.publicKeyInBlake160, charlie.publicKeyInBlake160],
)),
MultisigConfig.fromModel(new MultisigConfigModel(
'walletId',
2,
2,
3,
[alice.publicKeyInBlake160, bob.publicKeyInBlake160, charlie.publicKeyInBlake160],
)),
MultisigConfig.fromModel(
new MultisigConfigModel('walletId', 1, 2, 3, [
alice.publicKeyInBlake160,
bob.publicKeyInBlake160,
charlie.publicKeyInBlake160,
])
),
MultisigConfig.fromModel(
new MultisigConfigModel('walletId', 2, 2, 3, [
alice.publicKeyInBlake160,
bob.publicKeyInBlake160,
charlie.publicKeyInBlake160,
])
),
]
//@ts-ignore private-method
const res = MultisigService.removeDulpicateConfig(multisigConfigs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1196,7 +1196,7 @@ describe('TransactionGenerator', () => {
const targetOutput: Output = Output.fromObject({
capacity: toShannon('61'),
lock: aliceAnyoneCanPayLockScript,
type: assetAccountInfo.generateSudtScript('0xuuid'),
type: assetAccountInfo.generateSudtScript('0x1234'),
data: '0x',
})

Expand Down
Loading