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 generics on chain queries #260

Merged
merged 13 commits into from
Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
43 changes: 24 additions & 19 deletions src/attestation/Attestation.chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
* @packageDocumentation
* @ignore
*/
import { Option, Text } from '@polkadot/types'
import { Codec } from '@polkadot/types/types'
import { Option, Text, Tuple } from '@polkadot/types'
import { SubmittableExtrinsic } from '@polkadot/api/promise/types'

import { SubmittableResult } from '@polkadot/api'
import { Codec } from '@polkadot/types/types'
import { hasNonNullByte, assertCodecIsType } from '../util/Decode'
import { getCached } from '../blockchainApiConnection'
import { QueryResult } from '../blockchain/Blockchain'
import Identity from '../identity/Identity'
import { factory } from '../config/ConfigLog'
import IAttestation from '../types/Attestation'
Expand Down Expand Up @@ -37,17 +37,21 @@ export async function store(
return blockchain.submitTx(identity, tx)
}

function decode(encoded: QueryResult, claimHash: string): Attestation | null {
if (encoded && encoded.encodedLength) {
const attestationTuple = encoded.toJSON()
if (
attestationTuple instanceof Array &&
typeof attestationTuple[0] === 'string' &&
typeof attestationTuple[1] === 'string' &&
(typeof attestationTuple[2] === 'string' ||
attestationTuple[2] === null) &&
typeof attestationTuple[3] === 'boolean'
) {
interface IChainAttestation extends Codec {
toJSON: () => [string, string, string | null, boolean] | null
}

function decode(
encoded: Option<Tuple> | Tuple,
claimHash: string // all the other decoders do not use extra data; they just return partial types
): Attestation | null {
assertCodecIsType(encoded, [
'Option<(H256,AccountId,Option<H256>,bool)>',
'(H256,AccountId,Option<H256>,bool)',
])
if (encoded instanceof Option || hasNonNullByte(encoded)) {
const attestationTuple = (encoded as IChainAttestation).toJSON()
if (attestationTuple instanceof Array) {
const attestation: IAttestation = {
claimHash,
cTypeHash: attestationTuple[0],
Expand All @@ -62,17 +66,18 @@ function decode(encoded: QueryResult, claimHash: string): Attestation | null {
return null
}

async function queryRaw(claimHash: string): Promise<Codec | null> {
// return types reflect backwards compatibility with mashnet-node v 0.22
async function queryRaw(claimHash: string): Promise<Option<Tuple> | Tuple> {
log.debug(() => `Query chain for attestations with claim hash ${claimHash}`)
const blockchain = await getCached()
const result: QueryResult = await blockchain.api.query.attestation.attestations(
claimHash
)
const result = await blockchain.api.query.attestation.attestations<
Option<Tuple> | Tuple
>(claimHash)
return result
}

export async function query(claimHash: string): Promise<Attestation | null> {
const encoded: QueryResult = await queryRaw(claimHash)
const encoded = await queryRaw(claimHash)
return decode(encoded, claimHash)
}

Expand Down
26 changes: 12 additions & 14 deletions src/attestation/Attestation.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Text } from '@polkadot/types'
import { H256 } from '@polkadot/types'
import Bool from '@polkadot/types/primitive/Bool'
import AccountId from '@polkadot/types/primitive/Generic/AccountId'
import { Tuple, Option } from '@polkadot/types/codec'
Expand Down Expand Up @@ -52,13 +52,12 @@ describe('Attestation', () => {

it('stores attestation', async () => {
blockchainApi.query.attestation.attestations.mockReturnValue(
new Option(
Tuple,
new Tuple(
[Text, AccountId, Text, Bool],
[testCType.hash, identityAlice.address, undefined, false]
)
)
new Option(Tuple.with([H256, AccountId, Option.with(H256), Bool]), [
testCType.hash,
identityAlice.address,
null,
false,
])
)

const attestation: Attestation = Attestation.fromRequestAndPublicIdentity(
Expand All @@ -70,7 +69,7 @@ describe('Attestation', () => {

it('verify attestations not on chain', async () => {
blockchainApi.query.attestation.attestations.mockReturnValue(
new Option(Tuple)
new Option(Tuple.with([H256, AccountId, Option.with(H256), Bool]))
)

const attestation: Attestation = Attestation.fromAttestation({
Expand All @@ -86,12 +85,11 @@ describe('Attestation', () => {
it('verify attestation revoked', async () => {
blockchainApi.query.attestation.attestations.mockReturnValue(
new Option(
Tuple,
new Tuple(
Tuple.with(
// Attestations: claim-hash -> (ctype-hash, account, delegation-id?, revoked)
[Text, AccountId, Text, Bool],
[testCType.hash, identityAlice.address, undefined, true]
)
[H256, AccountId, 'Option<H256>', Bool]
),
[testCType.hash, identityAlice.address, null, true]
)
)

Expand Down
22 changes: 6 additions & 16 deletions src/blockchain/Blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,14 @@ import { ApiPromise, SubmittableResult } from '@polkadot/api'
import { SubmittableExtrinsic } from '@polkadot/api/promise/types'
import { Header } from '@polkadot/types/interfaces/types'
import { Codec, AnyJson } from '@polkadot/types/types'
import { Text } from '@polkadot/types'
import { Text, u64 } from '@polkadot/types'
import { ErrorHandler } from '../errorhandling/ErrorHandler'
import { factory as LoggerFactory } from '../config/ConfigLog'
import { ERROR_UNKNOWN, ExtrinsicError } from '../errorhandling/ExtrinsicError'
import Identity from '../identity/Identity'

const log = LoggerFactory.getLogger('Blockchain')

export type QueryResult = Codec | undefined | null

export type Stats = {
chain: string
nodeName: string
Expand All @@ -44,12 +42,9 @@ export interface IBlockchainApi {
// https://polkadot.js.org/api/api/classes/_promise_index_.apipromise.html

export default class Blockchain implements IBlockchainApi {
public static asArray(queryResult: QueryResult): AnyJson[] {
const json =
queryResult && queryResult.encodedLength ? queryResult.toJSON() : null
if (json instanceof Array) {
return json
}
public static asArray(queryResult: Codec): AnyJson[] {
const json = queryResult.toJSON()
if (json instanceof Array) return json
return []
}

Expand Down Expand Up @@ -122,12 +117,7 @@ export default class Blockchain implements IBlockchainApi {
})
}

public async getNonce(accountAddress: string): Promise<Codec> {
const nonce = await this.api.query.system.accountNonce(accountAddress)
if (!nonce) {
throw Error(`Nonce not found for account ${accountAddress}`)
}

return nonce
public async getNonce(accountAddress: string): Promise<u64> {
return this.api.query.system.accountNonce<u64>(accountAddress)
}
}
48 changes: 31 additions & 17 deletions src/blockchainApiConnection/__mocks__/BlockchainApiConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ import { Option, Tuple, Vec, H256, u64, u128 } from '@polkadot/types'
import { SubmittableExtrinsic } from '@polkadot/api/promise/types'
import { ExtrinsicStatus } from '@polkadot/types/interfaces'
import AccountId from '@polkadot/types/primitive/Generic/AccountId'
import Bool from '@polkadot/types/primitive/Bool'
import U32 from '@polkadot/types/primitive/U32'

const BlockchainApiConnection = jest.requireActual('../BlockchainApiConnection')

Expand Down Expand Up @@ -176,12 +178,15 @@ const __mocked_api: any = {
*/

// default return value decodes to null, represents attestation not found
attestations: jest.fn(async (claim_hash: string) => new Option(Tuple)),
attestations: jest.fn(
async (claim_hash: string) =>
new Option(Tuple.with([H256, AccountId, 'Option<H256>', Bool]))
),
/* example return value:
new Option(
Tuple,
new Tuple(
[H256, AccountId, 'Option<H256>', Bool],
Tuple.with(
[H256, AccountId, 'Option<H256>', Bool]
),
[
'0x1234', // ctype hash
'5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu', // Account
Expand All @@ -201,12 +206,15 @@ const __mocked_api: any = {
},
delegation: {
// default return value decodes to null, represents delegation not found
root: jest.fn(async (rootId: string) => new Option(Tuple)),
root: jest.fn(
async (rootId: string) =>
new Option(Tuple.with([H256, AccountId, Bool]))
),
/* example return value:
new Option(
Tuple,
new Tuple(
[H256, AccountId, Bool],
Tuple.with(
[H256, AccountId, Bool]
),
[
'0x1234', // ctype hash
'5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu', // Account
Expand All @@ -216,12 +224,15 @@ const __mocked_api: any = {
) */

// default return value decodes to null, represents delegation not found
delegations: jest.fn(async (delegationId: string) => new Option(Tuple)),
delegations: jest.fn(
async (delegationId: string) =>
new Option(Tuple.with([H256, 'Option<H256>', AccountId, U32, Bool]))
),
/* example return value:
new Option(
Tuple,
new Tuple(
[H256,'Option<H256>',AccountId,U32,Bool],
Tuple.with(
[H256,'Option<H256>',AccountId,U32,Bool]
),
[
'0x1234', // root-id
null, // parent-id?
Expand All @@ -233,7 +244,7 @@ const __mocked_api: any = {
) */

// default return value decodes to [], represents: no children found
children: jest.fn(async (id: string) => new Vec(H256, [])),
children: jest.fn(async (id: string) => new Vec(H256)),
/* example return value:
new Vec(
H256,
Expand All @@ -243,12 +254,15 @@ const __mocked_api: any = {
},
did: {
// default return value decodes to null, represents dID not found
dIDs: jest.fn(async (address: string) => new Option(Tuple)),
dIDs: jest.fn(
async (address: string) =>
new Option(Tuple.with([H256, H256, 'Option<Bytes>']))
),
/* example return value:
new Option(
Tuple,
new Tuple(
[H256,H256,'Option<Bytes>'],
Tuple.with(
[H256,H256,'Option<Bytes>']
),
[
'publicSigningKey', // publicSigningKey
'publicBoxKey', // publicBoxKey
Expand Down
20 changes: 12 additions & 8 deletions src/ctype/CType.chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@

import { SubmittableExtrinsic } from '@polkadot/api/promise/types'
import { SubmittableResult } from '@polkadot/api'
import { QueryResult } from '../blockchain/Blockchain'
import { AccountId } from '@polkadot/types/interfaces'
import { Option } from '@polkadot/types'
import { getCached } from '../blockchainApiConnection'
import Identity from '../identity/Identity'
import IPublicIdentity from '../types/PublicIdentity'
import { factory } from '../config/ConfigLog'
import ICType from '../types/CType'
import { assertCodecIsType } from '../util/Decode'

const log = factory.getLogger('CType')

Expand All @@ -24,19 +26,21 @@ export async function store(
return blockchain.submitTx(identity, tx)
}

function decode(encoded: QueryResult): IPublicIdentity['address'] | null {
return encoded && encoded.encodedLength && !encoded.isEmpty
? encoded.toString()
: null
// decoding is backwards compatible with mashnet-node 0.22
export function decode(
encoded: Option<AccountId> | AccountId
): IPublicIdentity['address'] | null {
assertCodecIsType(encoded, ['AccountId', 'Option<AccountId>'])
return !encoded.isEmpty ? encoded.toString() : null
}

export async function getOwner(
ctypeHash: ICType['hash']
): Promise<IPublicIdentity['address'] | null> {
const blockchain = await getCached()
const encoded: QueryResult = await blockchain.api.query.ctype.cTYPEs(
ctypeHash
)
const encoded = await blockchain.api.query.ctype.cTYPEs<
Option<AccountId> | AccountId
>(ctypeHash)
const queriedCTypeAccount = decode(encoded)
return queriedCTypeAccount
}
38 changes: 14 additions & 24 deletions src/delegation/Delegation.chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,34 @@
* @ignore
*/

import { AnyJson } from '@polkadot/types/types'
import { Vec, H256, Option, Tuple } from '@polkadot/types'
import { getCached } from '../blockchainApiConnection'
import Blockchain, { QueryResult } from '../blockchain/Blockchain'
import { CodecWithId } from './DelegationDecoder'
import { IDelegationBaseNode } from '../types/Delegation'
import { assertCodecIsType } from '../util/Decode'

function isString(element: AnyJson): element is string {
return typeof element === 'string'
}

function decodeDelegatedAttestations(queryResult: QueryResult): string[] {
const json =
queryResult && queryResult.encodedLength ? queryResult.toJSON() : []
if (json instanceof Array) {
const delegatedAttestations: string[] = json.filter<string>(isString)
return delegatedAttestations
}
return []
function decodeDelegatedAttestations(queryResult: Vec<H256>): string[] {
assertCodecIsType(queryResult, 'Vec<H256>')
return queryResult.map(hash => hash.toString())
}

export async function getAttestationHashes(
id: IDelegationBaseNode['id']
): Promise<string[]> {
const blockchain = await getCached()
const encodedHashes = await blockchain.api.query.attestation.delegatedAttestations(
id
)
const encodedHashes = await blockchain.api.query.attestation.delegatedAttestations<
Vec<H256>
>(id)
return decodeDelegatedAttestations(encodedHashes)
}

export async function getChildIds(
id: IDelegationBaseNode['id']
): Promise<string[]> {
const blockchain = await getCached()
const childIds = Blockchain.asArray(
await blockchain.api.query.delegation.children(id)
)
return childIds.filter((e): e is string => typeof e === 'string')
const childIds = await blockchain.api.query.delegation.children<Vec<H256>>(id)
assertCodecIsType(childIds, 'Vec<H256>')
return childIds.map(hash => hash.toString())
}

export async function fetchChildren(
Expand All @@ -49,9 +39,9 @@ export async function fetchChildren(
const blockchain = await getCached()
const val: CodecWithId[] = await Promise.all(
childIds.map(async (childId: string) => {
const queryResult: QueryResult = await blockchain.api.query.delegation.delegations(
childId
)
const queryResult = await blockchain.api.query.delegation.delegations<
Option<Tuple> | Tuple
>(childId)
return {
id: childId,
codec: queryResult,
Expand Down
Loading