diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index 753f0152dd..e218e265a0 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -6,12 +6,7 @@ import { RpcInterface } from '@polkadot/rpc-core/jsonrpc.types'; import { ProviderInterface } from '@polkadot/rpc-provider/types'; import { Hash, RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces'; import { AnyFunction, CallFunction, Codec, CodecArg, ModulesWithCalls, RegistryTypes } from '@polkadot/types/types'; -import { - ApiInterfaceRx, ApiInterfaceEvents, ApiOptions, ApiTypes, DecorateMethodOptions, - DecoratedRpc, DecoratedRpcSection, - QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs, - SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer -} from './types'; +import { ApiInterfaceRx, ApiInterfaceEvents, ApiOptions, ApiTypes, DecorateMethodOptions, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, QueryableStorageMultiArgs, SignerPayloadRawBase, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics, Signer } from './types'; import EventEmitter from 'eventemitter3'; import { BehaviorSubject, Observable } from 'rxjs'; @@ -29,7 +24,7 @@ import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage'; import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/primitive/Extrinsic/constants'; import * as interfacesTypes from '@polkadot/types/interfaces/definitions'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; -import { assert, compactStripLength, isFunction, isObject, isUndefined, logger, u8aToHex, u8aToU8a } from '@polkadot/util'; +import { assert, compactStripLength, isFunction, isObject, isString, isUndefined, logger, u8aToHex, u8aToU8a } from '@polkadot/util'; import { cryptoWaitReady } from '@polkadot/util-crypto'; import createSubmittable, { SubmittableExtrinsic } from './SubmittableExtrinsic'; @@ -43,6 +38,10 @@ interface MetaDecoration { toJSON: () => any; } +interface KeyringSigner { + sign (message: Uint8Array): Uint8Array; +} + const INIT_ERROR = `Api needs to be initialised before using, listen on 'ready'`; const KEEPALIVE_INTERVAL = 15000; @@ -223,6 +222,28 @@ export default abstract class ApiBase { this._rx.signer = signer; } + /** + * @description Signs a raw signer payload, string or Uint8Array + */ + public async sign (signer: KeyringSigner | string, data: SignerPayloadRawBase): Promise { + // NOTE Do we really want to do this? Or turn it into an observable for rxjs? + if (isString(signer)) { + if (!this._rx.signer || !this._rx.signer.signRaw) { + throw new Error('No signer exists with a signRaw interface'); + } + + return ( + await this._rx.signer.signRaw({ + type: 'bytes', + ...data, + address: signer + }) + ).signature; + } + + return u8aToHex(signer.sign(u8aToU8a(data.data))); + } + /** * @description Derived results that are injected into the API, allowing for combinations of various query results. * diff --git a/packages/api/src/SignerPayload.ts b/packages/api/src/SignerPayload.ts index be519f5907..872d6ed76c 100644 --- a/packages/api/src/SignerPayload.ts +++ b/packages/api/src/SignerPayload.ts @@ -3,9 +3,9 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { Address, Balance, BlockNumber, Call, ExtrinsicEra, Hash, Index } from '@polkadot/types/interfaces'; -import { SignerPayload as ISignerPayload } from './types'; +import { SignerPayload, SignerPayloadRaw } from './types'; -import { ClassOf, Compact, Struct, u8 } from '@polkadot/types'; +import { createType, ClassOf, Compact, Struct, u8 } from '@polkadot/types'; export interface SignerPayloadType { address: Address; @@ -19,7 +19,7 @@ export interface SignerPayloadType { version: u8; } -export default class SignerPayload extends Struct.with({ +export default class Payload extends Struct.with({ address: ClassOf('Address'), blockHash: ClassOf('Hash'), blockNumber: ClassOf('BlockNumber'), @@ -40,7 +40,7 @@ export default class SignerPayload extends Struct.with({ /** * @description Creates an representation of the structure as an ISignerPayload JSON */ - public toPayload (): ISignerPayload { + public toPayload (): SignerPayload { const { address, blockHash, blockNumber, era, genesisHash, method, nonce, tip, version } = this.self; return { @@ -55,4 +55,18 @@ export default class SignerPayload extends Struct.with({ version: version.toNumber() }; } + + /** + * @description Creates a representation of the payload in raw Exrinsic form + */ + public toRaw (): SignerPayloadRaw { + const payload = this.toPayload(); + const data = createType('ExtrinsicPayload', payload, { version: payload.version }).toHex(); + + return { + address: payload.address, + data, + type: 'payload' + }; + } } diff --git a/packages/api/src/SubmittableExtrinsic.ts b/packages/api/src/SubmittableExtrinsic.ts index c90b010a04..00ab61618b 100644 --- a/packages/api/src/SubmittableExtrinsic.ts +++ b/packages/api/src/SubmittableExtrinsic.ts @@ -268,22 +268,29 @@ export default function createSubmittableExtrinsic ( if (isKeyringPair(account)) { this.sign(account, eraOptions); } else if (api.signer) { + const payload = new SignerPayload({ + ...eraOptions, + address, + method: _extrinsic.method, + blockNumber: header ? header.number : 0, + genesisHash: api.genesisHash, + version: api.extrinsicType + }); + if (api.signer.signPayload) { - const signPayload = new SignerPayload({ - ...eraOptions, - address, - method: _extrinsic.method, - blockNumber: header ? header.number : 0, - genesisHash: api.genesisHash, - version: api.extrinsicType - }); - const result = await api.signer.signPayload(signPayload.toPayload()); + const { id, signature } = await api.signer.signPayload(payload.toPayload()); // Here we explicitly call `toPayload()` again instead of working with an object // (reference) as passed to the signer. This means that we are sure that the // payload data is not modified from our inputs, but the signer - _extrinsic.addSignature(address, result.signature, signPayload.toPayload()); - updateId = result.id; + _extrinsic.addSignature(address, signature, payload.toPayload()); + updateId = id; + } else if (api.signer.signRaw) { + const { id, signature } = await api.signer.signRaw(payload.toRaw()); + + // as above, always trust our payload as the signle sourec of truth + _extrinsic.addSignature(address, signature, payload.toPayload()); + updateId = id; } else if (api.signer.sign) { console.warn('The Signer.sign interface is deprecated and will be removed in a future version, Swap to using the Signer.signPayload interface instead.'); diff --git a/packages/api/src/promise/Api.spec.ts b/packages/api/src/promise/Api.spec.ts index eef4372b59..5af17b0af0 100644 --- a/packages/api/src/promise/Api.spec.ts +++ b/packages/api/src/promise/Api.spec.ts @@ -2,50 +2,78 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import testingPairs from '@polkadot/keyring/testingPairs'; import Mock from '@polkadot/rpc-provider/mock/index'; import { createType } from '@polkadot/types'; import { ApiPromise } from '..'; +import { SingleAccountSigner } from '../../test/util'; import { ApiOptions } from '../types'; -describe('Metadata queries', (): void => { - let mock: Mock; +describe('ApiPromise', (): void => { + const keyring = testingPairs({ type: 'ed25519' }); + let provider: Mock; beforeEach((): void => { jest.setTimeout(3000000); - mock = new Mock(); + provider = new Mock(); }); - it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async (): Promise => { - const rpcData = await mock.send('state_getMetadata', []); - const genesisHash = createType('Hash', await mock.send('chain_getBlockHash', [])).toHex(); - const specVersion = 0; - const metadata: any = {}; - const key = `${genesisHash}-${specVersion}`; - metadata[key] = rpcData; - const api = await ApiPromise.create({ provider: mock, metadata } as unknown as ApiOptions); + describe('initialization', (): void => { + it('Create API instance with metadata map and makes the runtime, rpc, state & extrinsics available', async (): Promise => { + const rpcData = await provider.send('state_getMetadata', []); + const genesisHash = createType('Hash', await provider.send('chain_getBlockHash', [])).toHex(); + const specVersion = 0; + const metadata: any = {}; + const key = `${genesisHash}-${specVersion}`; + metadata[key] = rpcData; + const api = await ApiPromise.create({ provider, metadata } as unknown as ApiOptions); - expect(api.genesisHash).toBeDefined(); - expect(api.runtimeMetadata).toBeDefined(); - expect(api.runtimeVersion).toBeDefined(); - expect(api.rpc).toBeDefined(); - expect(api.query).toBeDefined(); - expect(api.tx).toBeDefined(); - expect(api.derive).toBeDefined(); - }); - - it('Create API instance without metadata and makes the runtime, rpc, state & extrinsics available', async (): Promise => { - const metadata = {}; - const api = await ApiPromise.create({ - provider: mock, metadata + expect(api.genesisHash).toBeDefined(); + expect(api.runtimeMetadata).toBeDefined(); + expect(api.runtimeVersion).toBeDefined(); + expect(api.rpc).toBeDefined(); + expect(api.query).toBeDefined(); + expect(api.tx).toBeDefined(); + expect(api.derive).toBeDefined(); }); - expect(api.genesisHash).toBeDefined(); - expect(api.runtimeMetadata).toBeDefined(); - expect(api.runtimeVersion).toBeDefined(); - expect(api.rpc).toBeDefined(); - expect(api.query).toBeDefined(); - expect(api.tx).toBeDefined(); - expect(api.derive).toBeDefined(); + it('Create API instance without metadata and makes the runtime, rpc, state & extrinsics available', async (): Promise => { + const metadata = {}; + const api = await ApiPromise.create({ provider, metadata }); + + expect(api.genesisHash).toBeDefined(); + expect(api.runtimeMetadata).toBeDefined(); + expect(api.runtimeVersion).toBeDefined(); + expect(api.rpc).toBeDefined(); + expect(api.query).toBeDefined(); + expect(api.tx).toBeDefined(); + expect(api.derive).toBeDefined(); + }); + }); + + describe('api.sign', (): void => { + const ADDR = '5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu'; + const TEST = { data: '0x0102030405060708090a0b0c0d0e0f112233445566778899aabbccddeeff' }; + const SIG = '0x659effefbbe5ab4d7136ebb5084b959eb424e32b862307371be4721ac2c46334245af4f1476c36c5e5aff04396c2fdd2ce561ec90382821d4aa071b559b1db0f'; + + it('signs data using a specified keyring', async (): Promise => { + const api = new ApiPromise({ provider }); + + expect( + await api.sign(keyring.alice_session, TEST) + ).toEqual(SIG); + }); + + it('signs data using an external signer', async (): Promise => { + const api = new ApiPromise({ + provider, + signer: new SingleAccountSigner(keyring.alice_session) + }); + + expect( + await api.sign(ADDR, TEST) + ).toEqual(SIG); + }); }); }); diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index bc3c7103d6..1ba417671a 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -259,6 +259,30 @@ export interface SignerPayload { version: number; } +export interface SignerPayloadRawBase { + /** + * @description The hex-encoded data for this request + */ + data: string; + + /** + * @description The type of the contained data + */ + type?: 'bytes' | 'payload'; +} + +export interface SignerPayloadRaw extends SignerPayloadRawBase { + /** + * @description The ss-58 encoded address + */ + address: string; + + /** + * @description The type of the contained data + */ + type: 'bytes' | 'payload'; +} + export interface SignerResult { /** * @description The id for this request @@ -273,7 +297,7 @@ export interface SignerResult { export interface Signer { /** - * @deprecated Implement and use signPayload instead + * @deprecated Implement and use signPayload and/or signRaw instead * @description Signs an extrinsic, returning an id (>0) that can be used to retrieve updates */ sign?: (extrinsic: IExtrinsic, address: string, options: SignerOptions) => Promise; @@ -281,7 +305,12 @@ export interface Signer { /** * @description signs an extrinsic payload from a serialized form */ - signPayload(payload: SignerPayload): Promise; + signPayload?: (payload: SignerPayload) => Promise; + + /** + * @description signs a raw payload, only the bytes data as supplied + */ + signRaw?: (raw: SignerPayloadRaw) => Promise; /** * @description Receives an update for the extrinsic signed by a `signer.sign` diff --git a/packages/api/test/util/SingleAccountSigner.ts b/packages/api/test/util/SingleAccountSigner.ts index e93c4056f2..befd9c4065 100644 --- a/packages/api/test/util/SingleAccountSigner.ts +++ b/packages/api/test/util/SingleAccountSigner.ts @@ -2,10 +2,11 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Signer, SignerPayload, SignerResult } from '@polkadot/api/types'; +import { Signer, SignerPayload, SignerResult, SignerPayloadRaw } from '@polkadot/api/types'; import { KeyringPair } from '@polkadot/keyring/types'; import { createType } from '@polkadot/types'; +import { hexToU8a, u8aToHex } from '@polkadot/util'; let id = 0; @@ -19,32 +20,36 @@ export class SingleAccountSigner implements Signer { this.signDelay = signDelay; } - // @deprecated Kept here until we have it removed completely - // public async sign (extrinsic: IExtrinsic, address: string, options: SignatureOptions): Promise { - // if (!this.keyringPair || String(address) !== this.keyringPair.address) { - // throw new Error('does not have the keyringPair'); - // } - - // return new Promise((resolve): void => { - // setTimeout((): void => { - // extrinsic.sign(this.keyringPair, options); - - // resolve(++id); - // }, this.signDelay); - // }); - // } - public async signPayload (payload: SignerPayload): Promise { - if (!this.keyringPair || payload.address !== this.keyringPair.address) { + if (payload.address !== this.keyringPair.address) { throw new Error('does not have the keyringPair'); } return new Promise((resolve): void => { setTimeout((): void => { const signed = createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.keyringPair); - const result: SignerResult = { id: ++id, ...signed }; - resolve(result); + resolve({ + id: ++id, + ...signed + }); + }, this.signDelay); + }); + } + + public async signRaw ({ address, data }: SignerPayloadRaw): Promise { + if (address !== this.keyringPair.address) { + throw new Error('does not have the keyringPair'); + } + + return new Promise((resolve): void => { + setTimeout((): void => { + const signature = u8aToHex(this.keyringPair.sign(hexToU8a(data))); + + resolve({ + id: ++id, + signature + }); }, this.signDelay); }); }