Skip to content

Commit

Permalink
refactor asserting logic
Browse files Browse the repository at this point in the history
  • Loading branch information
0xverin committed Nov 1, 2024
1 parent 4c0ea4f commit f3110e3
Show file tree
Hide file tree
Showing 4 changed files with 264 additions and 235 deletions.
6 changes: 0 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,6 @@ jobs:
echo "MORALIS_API_KEY=${{ secrets.MORALIS_API_KEY }}" >> /opt/worker_configs/worker_env
echo "MAGIC_CRAFT_API_KEY=${{ secrets.MAGIC_CRAFT_API_KEY }}" >> /opt/worker_configs/worker_env
# - name: Start parachain-worker
# shell: bash
# run: |
# ./scripts/run_parachain_worker.sh
# docker ps

- name: Compile contracts
run: |
npm install --save-dev hardhat
Expand Down
231 changes: 124 additions & 107 deletions vc-di-tests/integration-tests/assertion_contracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ import { genesisSubstrateWallet } from './common/helpers'
import { KeyringPair } from '@polkadot/keyring/types'
import { subscribeToEvents } from './common/transactions'
import {
decryptWithAes,
encryptWithTeeShieldingKey,
PolkadotSigner,
} from './common/utils/crypto'
import { ethers } from 'ethers'
import { sleep } from './common/utils'
import { hexToU8a, stringToU8a, u8aToHex } from '@polkadot/util'
import { byId } from '@litentry/chaindata'
import { $ as zx } from 'zx'
import { log, $ as zx } from 'zx'
import { CredentialDefinition, credentialsJson } from './common/credential-json'
import { Keyring } from '@polkadot/keyring'
import { env } from './common/loadEnv'
Expand All @@ -55,6 +54,7 @@ describe('Test Vc (direct request)', function () {
const keyringPairs: KeyringPair[] = []
let alice: KeyringPair = undefined as any
let contractBytecode = undefined as any
const errorArray: { index: number; assertion: any; error: any }[] = []

const chain = byId['litentry-dev']
const nodeEndpoint = chain.rpcs[0].url
Expand Down Expand Up @@ -99,81 +99,128 @@ describe('Test Vc (direct request)', function () {
return contract.contractId
}

before(async () => {
console.log(`nodeEndpoint: ${nodeEndpoint}`)
console.log(`enclaveEndpoint: ${enclaveEndpoint}`)
context = await initIntegrationTestContext(
nodeEndpoint,
enclaveEndpoint
)

teeShieldingKey = await getTeeShieldingKey(context)
alice = genesisSubstrateWallet('Alice')

contracts = [
{
name: 'TokenMapping',
path: '../../artifacts/contracts/token_holding_amount/TokenMapping.sol/TokenMapping.json',
secrets: [
// The order is very important, refer to the order of secrets(/contracts/token_holding_amount/TokenQueryLogic.sol:queryBalance(...secrets)).
generateSecrets(env.GENIIDATA_API_KEY, context),
generateSecrets(env.NODEREAL_API_KEY, context),
generateSecrets(env.MORALIS_API_KEY, context),
],
bytecode: '',
contractId: randomContractId(),
},
{
name: 'PlatformUser',
path: '../../artifacts/contracts/platform_user/PlatformUser.sol/PlatformUser.json',
secrets: [],
bytecode: '',
contractId: randomContractId(),
},
// add more contracts here
]
})
async function requestVc(
credentialDefinition: CredentialDefinition,
index: number
) {
const contractId = matchContractId(credentialDefinition.contractName)
console.log(`contractId: ${contractId}`)
const requestIdentifier = `0x${randomBytes(32).toString('hex')}`
let currentNonce = (
await getSidechainNonce(context, substrateIdentities[index])
).toNumber()
const getNextNonce = () => currentNonce++
const nonce = getNextNonce()

const abiCoder = new ethers.utils.AbiCoder()
const encodedData = abiCoder.encode(
['string'],
[credentialDefinition.parameter]
)
const assertion = {
dynamic: context.api.createType('DynamicParams', [
contractId,
encodedData,
true,
]),
}
const requestVcCall = await createSignedTrustedCallRequestVc(
context.api,
context.mrEnclave,
context.api.createType('Index', nonce),
new PolkadotSigner(keyringPairs[index]),
substrateIdentities[index],
context.api.createType('Assertion', assertion).toHex(),
context.api.createType('Option<RequestAesKey>', aesKey).toHex(),
requestIdentifier
)
try {
const contractId = matchContractId(
credentialDefinition.contractName
)
console.log(`contractId: ${contractId}`)
const requestIdentifier = `0x${randomBytes(32).toString('hex')}`
let currentNonce = (
await getSidechainNonce(context, substrateIdentities[index])
).toNumber()
const getNextNonce = () => currentNonce++
const nonce = getNextNonce()

const onMessageReceived = async (res: WorkerRpcReturnValue) => {
const vcresponse = context.api.createType(
'RequestVcResultOrError',
res.value
const abiCoder = new ethers.utils.AbiCoder()
const encodedData = abiCoder.encode(
['string'],
[credentialDefinition.parameter]
)
console.log(
`vcresponse len: ${vcresponse.len}, idx: ${
vcresponse.idx
}, vc result: ${JSON.stringify(vcresponse.result)}`
const assertion = {
dynamic: context.api.createType('DynamicParams', [
contractId,
encodedData,
true,
]),
}
const requestVcCall = await createSignedTrustedCallRequestVc(
context.api,
context.mrEnclave,
context.api.createType('Index', nonce),
new PolkadotSigner(keyringPairs[index]),
substrateIdentities[index],
context.api.createType('Assertion', assertion).toHex(),
context.api.createType('Option<RequestAesKey>', aesKey).toHex(),
requestIdentifier
)
if (vcresponse.result.isOk)
await assertVc(

const asOkResult = await new Promise<any>((resolve, reject) => {
const onMessageReceived = async (res: WorkerRpcReturnValue) => {
try {
const vcresponse = context.api.createType(
'RequestVcResultOrError',
res.value
)
console.log(
`vcresponse len: ${vcresponse.len}, idx: ${
vcresponse.idx
}, vc result: ${JSON.stringify(vcresponse.result)}`
)
if (
vcresponse.result.isOk &&
vcresponse.result.asOk.toString() !== '0x'
) {
resolve(vcresponse.result.asOk)
}
} catch (error) {
reject(error)
}
}

sendRequestFromTrustedCall(
context,
substrateIdentities[index],
vcresponse.result.asOk
)
const decryptVcPayload = decryptWithAes(
aesKey,
vcresponse.vc_payload,
'utf-8'
).replace('0x', '')
const vcPayloadJson = JSON.parse(decryptVcPayload)
console.log(`vcPayloadJson: ${JSON.stringify(vcPayloadJson)}`)
assert.equal(
vcPayloadJson.credentialSubject.values[0],
credentialDefinition.expectedCredentialValue,
"credential value doesn't match, please check the credential json expectedCredentialValue"
teeShieldingKey,
requestVcCall,
onMessageReceived
).catch(reject)
})

await assertVc(
context,
substrateIdentities[index],
asOkResult,
credentialDefinition.expectedCredentialValue
)
} catch (error) {
errorArray.push({
index: index,
assertion: JSON.stringify(credentialDefinition.name),
error: error,
})
console.error(
`Error in requestVc for ${credentialDefinition.name} at index ${index}:`,
error
)
}
const callResults = await sendRequestFromTrustedCall(
context,
teeShieldingKey,
requestVcCall,
onMessageReceived
)
await assertIsInSidechainBlock(
`${Object.keys(assertion)[0]} requestVcCall`,
callResults
)
await sleep(12)
}
async function linkIdentityViaCli(
credentialDefinition: CredentialDefinition,
Expand Down Expand Up @@ -223,41 +270,6 @@ describe('Test Vc (direct request)', function () {
}
}
}
before(async () => {
console.log(`nodeEndpoint: ${nodeEndpoint}`)
console.log(`enclaveEndpoint: ${enclaveEndpoint}`)
context = await initIntegrationTestContext(
nodeEndpoint,
enclaveEndpoint
)

teeShieldingKey = await getTeeShieldingKey(context)
alice = genesisSubstrateWallet('Alice')

contracts = [
{
name: 'TokenMapping',
path: '../../artifacts/contracts/token_holding_amount/TokenMapping.sol/TokenMapping.json',
secrets: [
// The order is very important, refer to the order of secrets(/contracts/token_holding_amount/TokenQueryLogic.sol:queryBalance(...secrets)).
generateSecrets(env.GENIIDATA_API_KEY, context),
generateSecrets(env.NODEREAL_API_KEY, context),
generateSecrets(env.MORALIS_API_KEY, context),
],
bytecode: '',
contractId: randomContractId(),
},
{
name: 'PlatformUser',
path: '../../artifacts/contracts/platform_user/PlatformUser.sol/PlatformUser.json',
secrets: [],
bytecode: '',
contractId: randomContractId(),
},
// add more contracts here
]
})

step('loading contract bytecode', async function () {
for (const contract of contracts) {
const file = path.resolve('./', contract.path)
Expand Down Expand Up @@ -310,7 +322,7 @@ describe('Test Vc (direct request)', function () {
await sleep(12)
})

for (const [index, credentialDefinition] of credentialsJson.entries()) {
credentialsJson.forEach((credentialDefinition, index) => {
step(
`linking identity ${credentialDefinition.mockDid} via cli`,
async function () {
Expand All @@ -326,10 +338,15 @@ describe('Test Vc (direct request)', function () {

await linkIdentityViaCli(credentialDefinition, index)
await requestVc(credentialDefinition, index)
console.log('waiting 12 seconds...')

await sleep(12)
}
)
}
})
after(async function () {
if (errorArray.length > 0) {
console.log('errorArray:', errorArray)
throw new Error(
`${errorArray.length} tests failed. See above for details.`
)
}
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
"parameter": "btc",
"dataProvider": "blockchaininfo",
"network": "bitcoin",
"mockDid": "litentry:bitcoin:0x021001e74c3b0c1eff4695aaa3ee6b30a89ef8fbc124b8863c881f75efcd4dd0cc",
"mockDid": "litentry:bitcoin:0x03f5cb8154281a13256962c9a34b6c461f31431c55c506c77bc51cd21e1c7d2c13",
"mockWeb3Network": "bitcoinp2tr",
"expectedCredentialValue": false,
"addressSource": "https://www.blockchain.com/explorer/assets/btc"
Expand Down
Loading

0 comments on commit f3110e3

Please sign in to comment.