Expand keyring tests for sr25519 (#302)

* Expand keyring tests for sr25519

* Update index.spec.ts

* Update index.spec.ts

* Support type conversion, type per pair

* toType tests
This commit is contained in:
Jaco Greeff
2019-02-14 22:04:12 +01:00
committed by GitHub
parent 97cee907e4
commit c3fafbeab7
14 changed files with 183 additions and 105 deletions
+92 -1
View File
@@ -19,7 +19,6 @@ describe('keypair', () => {
keypair = new Keyring({ type: 'ed25519' });
keypair.addFromSeed(seedOne, {});
setPrefix(42);
});
it('adds the pair', () => {
@@ -59,5 +58,97 @@ describe('keypair', () => {
new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79])
);
});
it('signs and verifies', () => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
it('converts, signs and verifies', () => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne).toType('sr25519');
const signature = pair.sign(MESSAGE);
expect(pair.type).toBe('sr25519');
expect(pair.publicKey()).toEqual(
new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99])
);
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
});
describe('sr25519', () => {
const publicKeyOne = new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99]);
const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f');
const seedOne = stringToU8a('12345678901234567890123456789012');
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
beforeEach(() => {
keypair = new Keyring({ type: 'sr25519' });
keypair.addFromSeed(seedOne, {});
});
it('adds the pair', () => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey()
).toEqual(publicKeyTwo);
});
it('adds from a mnemonic', () => {
setPrefix(68);
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address()
).toEqual('7nmZ1fkYHpnEz6tqR9cLkmwYRbqda9wPsiDq56JhgmNXqGjt');
});
it('allows publicKeys retrieval', () => {
keypair.addFromSeed(seedTwo, {});
expect(
keypair.getPublicKeys()
).toEqual([ publicKeyOne, publicKeyTwo ]);
});
it('allows retrieval of a specific item', () => {
expect(
keypair.getPair(publicKeyOne).publicKey()
).toEqual(publicKeyOne);
});
it('allows adding from JSON', () => {
expect(
keypair.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
).publicKey()
).toEqual(
new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79])
);
});
it('signs and verifies', () => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
it('converts, signs and verifies', () => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne).toType('ed25519');
const signature = pair.sign(MESSAGE);
expect(pair.type).toBe('ed25519');
expect(pair.publicKey()).toEqual(
new Uint8Array([47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238])
);
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
});
});
+16 -13
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions, PairType } from './types';
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions, KeyringPairType } from './types';
import { assert, hexToU8a, isNumber } from '@polkadot/util/index';
import { mnemonicToSeed , naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed } from '@polkadot/util-crypto/index';
@@ -29,13 +29,13 @@ import Pairs from './pairs';
*/
export default class Keyring implements KeyringInstance {
private _pairs: Pairs;
private _type: PairType;
private _type: KeyringPairType;
constructor (options: KeyringOptions) {
assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`);
this._pairs = new Pairs();
this._type = options.type as PairType;
this._type = options.type as KeyringPairType;
setAddressPrefix(isNumber(options.addressPrefix) ? options.addressPrefix : 42);
}
@@ -47,7 +47,7 @@ export default class Keyring implements KeyringInstance {
/**
* @description Returns the type of the keyring, either ed25519 of sr25519
*/
get type (): PairType {
get type (): KeyringPairType {
return this._type;
}
@@ -67,8 +67,8 @@ export default class Keyring implements KeyringInstance {
* of an account backup), and then generates a keyring pair from them that it passes to
* `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
*/
addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta, encoded: Uint8Array | null): KeyringPair {
return this.addPair(createPair(this._type, { publicKey: this.decodeAddress(address) }, meta, encoded));
addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta, encoded: Uint8Array | null, type: KeyringPairType = this.type): KeyringPair {
return this.addPair(createPair(type, { publicKey: this.decodeAddress(address) }, meta, encoded));
}
/**
@@ -78,8 +78,11 @@ export default class Keyring implements KeyringInstance {
* of an account backup), and then generates a keyring pair from it that it passes to
* `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
*/
addFromJson ({ address, encoded, meta }: KeyringPair$Json): KeyringPair {
return this.addFromAddress(address, meta, hexToU8a(encoded));
addFromJson ({ address, encoded, encoding: { type, version }, meta }: KeyringPair$Json): KeyringPair {
const keytype = version === '0' || !Array.isArray(type)
? this.type
: type[1];
return this.addFromAddress(address, meta, hexToU8a(encoded), keytype);
}
/**
@@ -90,8 +93,8 @@ export default class Keyring implements KeyringInstance {
* of an account backup), and then generates a keyring pair from it that it passes to
* `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
*/
addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta): KeyringPair {
return this.addFromSeed(mnemonicToSeed(mnemonic), meta);
addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta, type: KeyringPairType = this.type): KeyringPair {
return this.addFromSeed(mnemonicToSeed(mnemonic), meta, type);
}
/**
@@ -101,12 +104,12 @@ export default class Keyring implements KeyringInstance {
* Allows user to provide the account seed as an argument, and then generates a keyring pair from it that it passes to
* `addPair` to store in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
*/
addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta): KeyringPair {
const keypair = this._type === 'sr25519'
addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta, type: KeyringPairType = this.type): KeyringPair {
const keypair = type === 'sr25519'
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
return this.addPair(createPair(this._type, { ...keypair, seed }, meta, null));
return this.addPair(createPair(type, { ...keypair, seed }, meta, null));
}
/**
+2 -2
View File
@@ -4,6 +4,7 @@
import { assert, stringToU8a, u8aFixLength } from '@polkadot/util/index';
import { naclDecrypt } from '@polkadot/util-crypto/index';
import { PairInfo } from './types';
import { KEY_LENGTH, NONCE_LENGTH, PKCS8_DIVIDER, PKCS8_HEADER } from './defaults';
@@ -11,8 +12,7 @@ const SEED_OFFSET = PKCS8_HEADER.length;
const DIV_OFFSET = SEED_OFFSET + KEY_LENGTH;
const PUBLIC_OFFSET = DIV_OFFSET + PKCS8_DIVIDER.length;
type DecodeResult = {
publicKey: Uint8Array,
type DecodeResult = PairInfo & {
seed: Uint8Array
};
+3 -1
View File
@@ -2,12 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { PairInfo } from './types';
import { stringToU8a, u8aConcat, u8aFixLength, assert } from '@polkadot/util/index';
import { naclEncrypt } from '@polkadot/util-crypto/index';
import { PKCS8_DIVIDER, PKCS8_HEADER } from './defaults';
export default function encode (publicKey: Uint8Array, seed?: Uint8Array | null, passphrase?: string): Uint8Array {
export default function encode ({ publicKey, seed }: PairInfo, passphrase?: string): Uint8Array {
assert(seed, 'Expected a valid seed to be passed to encode');
const encoded = u8aConcat(
+33 -22
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeypairType } from '@polkadot/util-crypto/types';
import { KeyringPair, KeyringPair$Json, KeyringPair$Meta, PairType } from '../types';
import { KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringPairType } from '../types';
import { PairInfo } from './types';
import { naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto/index';
@@ -13,6 +13,21 @@ import decode from './decode';
import encode from './encode';
import toJson from './toJson';
const fromSeed = (type: KeyringPairType, seed: Uint8Array) =>
type === 'sr25519'
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
const sign = (type: KeyringPairType, message: Uint8Array, pair: Partial<KeypairType>) =>
type === 'sr25519'
? schnorrkelSign(message, pair)
: naclSign(message, pair);
const verify = (type: KeyringPairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array) =>
type === 'sr25519'
? schnorrkelVerify(message, signature, publicKey)
: naclVerify(message, signature, publicKey);
/**
* @name pair
* @summary Creates a keyring pair object
@@ -44,24 +59,18 @@ import toJson from './toJson';
* an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding`
* property that indicates whether the public key value of the `encoded` property is encoded or not.
*/
export default function pair (type: PairType, { publicKey, seed }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null): KeyringPair {
const fromSeed = (seed: Uint8Array) =>
type === 'sr25519'
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
const sign = (message: Uint8Array, pair: Partial<KeypairType>) =>
type === 'sr25519'
? schnorrkelSign(message, pair)
: naclSign(message, pair);
const verify = (message: Uint8Array, signature: Uint8Array) =>
type === 'sr25519'
? schnorrkelVerify(message, signature, publicKey)
: naclVerify(message, signature, publicKey);
let secretKey: Uint8Array | undefined = seed
? fromSeed(seed).secretKey
: undefined;
export default function createPair (type: KeyringPairType, { publicKey, seed }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null): KeyringPair {
let secretKey: Uint8Array | undefined;
if (seed) {
const pair = fromSeed(type, seed);
publicKey = pair.publicKey;
secretKey = pair.secretKey;
}
return {
type,
address: (): string =>
encodeAddress(publicKey),
decodePkcs8: (passphrase?: string, _encoded?: Uint8Array | null): void => {
@@ -69,10 +78,10 @@ export default function pair (type: PairType, { publicKey, seed }: PairInfo, met
publicKey = decoded.publicKey;
seed = decoded.seed;
secretKey = fromSeed(seed).secretKey;
secretKey = fromSeed(type, seed).secretKey;
},
encodePkcs8: (passphrase?: string): Uint8Array =>
encode(publicKey, seed, passphrase),
encode({ publicKey, seed }, passphrase),
getMeta: (): KeyringPair$Meta =>
meta,
isLocked: (): boolean =>
@@ -86,10 +95,12 @@ export default function pair (type: PairType, { publicKey, seed }: PairInfo, met
meta = meta;
},
sign: (message: Uint8Array): Uint8Array =>
sign(message, { publicKey, secretKey }),
sign(type, message, { publicKey, secretKey }),
toJson: (passphrase?: string): KeyringPair$Json =>
toJson({ meta, publicKey }, encode(publicKey, seed, passphrase), !!passphrase),
toJson(type, { meta, publicKey }, encode({ publicKey, seed }, passphrase), !!passphrase),
toType: (type: KeyringPairType): KeyringPair =>
createPair(type, { publicKey, seed }, meta, null),
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
verify(message, signature)
verify(type, message, signature, publicKey)
};
}
+4 -1
View File
@@ -15,7 +15,7 @@ const json: KeyringPair$Json = {
address,
encoded: '',
encoding: {
content: 'none',
content: ['pkcs8', 'ed25519'],
type: 'none',
version: '0'
},
@@ -24,6 +24,7 @@ const json: KeyringPair$Json = {
export default function everybody (): KeyringPair {
return {
type: 'ed25519',
address: (): string =>
address,
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
@@ -45,6 +46,8 @@ export default function everybody (): KeyringPair {
new Uint8Array(64),
toJson: (passphrase?: string): KeyringPair$Json =>
json,
toType: (): KeyringPair =>
everybody(),
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false
};
+2 -2
View File
@@ -14,7 +14,7 @@ describe('toJson', () => {
address: '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ',
encoded: '0x3053020101300506032b657004220420416c696365202020202020202020202020202020202020202020202020202020a123032100d172a74cda4c865912c32ba0a80a57ae69abae410e5ccb59dee84e2f4432db4f',
encoding: {
content: 'pkcs8',
content: ['pkcs8', 'ed25519'],
type: 'none',
version: '1'
},
@@ -32,7 +32,7 @@ describe('toJson', () => {
expect(json).toMatchObject({
address: '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ',
encoding: {
content: 'pkcs8',
content: ['pkcs8', 'ed25519'],
type: 'xsalsa20-poly1305',
version: '1'
}
+3 -3
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringPair$Json, KeyringPair$Meta } from '../types';
import { KeyringPair$Json, KeyringPair$Meta, KeyringPairType } from '../types';
import { u8aToHex } from '@polkadot/util/index';
@@ -12,12 +12,12 @@ type PairStateJson = KeyringPair$Meta & {
publicKey: Uint8Array
};
export default function toJson ({ publicKey, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
export default function toJson (type: KeyringPairType, { publicKey, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
return {
address: encodeAddress(publicKey),
encoded: u8aToHex(encoded),
encoding: {
content: 'pkcs8',
content: ['pkcs8', type],
type: isEncrypted
? 'xsalsa20-poly1305'
: 'none',
+1 -1
View File
@@ -4,5 +4,5 @@
export type PairInfo = {
publicKey: Uint8Array,
seed?: Uint8Array
seed?: Uint8Array | null
};
+23 -20
View File
@@ -4,11 +4,11 @@
import { Prefix } from './address/types';
export type PairType = 'ed25519' | 'sr25519';
export type KeyringPairType = 'ed25519' | 'sr25519';
export type KeyringOptions = {
addressPrefix?: Prefix,
type?: PairType
type?: KeyringPairType
};
export type KeyringPair$Meta = {
@@ -18,7 +18,7 @@ export type KeyringPair$Meta = {
export type KeyringPair$JsonVersion = '0' | '1';
export type KeyringPair$JsonEncoding = {
content: 'pkcs8' | 'none',
content: ['pkcs8', KeyringPairType],
type: 'xsalsa20-poly1305' | 'none',
version: KeyringPair$JsonVersion
};
@@ -30,19 +30,22 @@ export type KeyringPair$Json = {
meta: KeyringPair$Meta
};
export type KeyringPair = {
address: () => string,
decodePkcs8: (passphrase?: string, encoded?: Uint8Array) => void,
encodePkcs8: (passphrase?: string) => Uint8Array,
getMeta: () => KeyringPair$Meta,
isLocked: () => boolean,
lock: () => void,
publicKey: () => Uint8Array,
setMeta: (meta: KeyringPair$Meta) => void,
sign (message: Uint8Array): Uint8Array,
toJson (passphrase?: string): KeyringPair$Json,
verify (message: Uint8Array, signature: Uint8Array): boolean
};
export interface KeyringPair {
readonly type: KeyringPairType;
address: () => string;
decodePkcs8: (passphrase?: string, encoded?: Uint8Array) => void;
encodePkcs8: (passphrase?: string) => Uint8Array;
getMeta: () => KeyringPair$Meta;
isLocked: () => boolean;
lock: () => void;
publicKey: () => Uint8Array;
setMeta: (meta: KeyringPair$Meta) => void;
sign (message: Uint8Array): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
toType (type: KeyringPairType): KeyringPair;
verify (message: Uint8Array, signature: Uint8Array): boolean;
}
export interface KeyringPairs {
add: (pair: KeyringPair) => KeyringPair;
@@ -52,16 +55,16 @@ export interface KeyringPairs {
}
export interface KeyringInstance {
type: PairType;
readonly type: KeyringPairType;
decodeAddress (encoded: string | Uint8Array): Uint8Array;
encodeAddress (key: Uint8Array | string): string;
setAddressPrefix (prefix: Prefix): void;
addPair (pair: KeyringPair): KeyringPair;
addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta, encoded: Uint8Array | null): KeyringPair;
addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta): KeyringPair;
addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta): KeyringPair;
addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta, encoded: Uint8Array | null, type?: KeyringPairType): KeyringPair;
addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta, type?: KeyringPairType): KeyringPair;
addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta, type?: KeyringPairType): KeyringPair;
addFromJson (pair: KeyringPair$Json): KeyringPair;
getPair (address: string | Uint8Array): KeyringPair;
getPairs (): Array<KeyringPair>;
@@ -2,7 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as schnorrkelKeypairFromRandom } from './keypair/fromRandom';
export { default as schnorrkelKeypairFromSeed } from './keypair/fromSeed';
export { default as schnorrkelSign } from './sign';
export { default as schnorrkelVerify } from './verify';
@@ -1,19 +0,0 @@
// Copyright 2017-2019 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { schnorrkelKeypairFromRandom } from '../index';
describe('schnorrkelKeypairFromRandom', () => {
it('generates a valid publicKey', () => {
expect(
schnorrkelKeypairFromRandom().publicKey
).toHaveLength(32);
});
it('generates a valid secretKey', () => {
expect(
schnorrkelKeypairFromRandom().secretKey
).toHaveLength(64);
});
});
@@ -1,16 +0,0 @@
// Copyright 2017-2019 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeypairType } from '../../types';
import randomAsU8a from '../../random/asU8a';
import fromSeed from './fromSeed';
/**
* @name schnorrkelKeypairFromRandom
* @description Returns a new generate object containing a `publicKey` & `secretKey`.
*/
export default function schnorrkelKeypairFromRandom (): KeypairType {
return fromSeed(randomAsU8a(32));
}
@@ -4,7 +4,8 @@
import { stringToU8a } from '@polkadot/util/index';
import pairFromRandom from './keypair/fromRandom';
import randomAsU8a from '../random/asU8a';
import pairFromSeed from './keypair/fromSeed';
import sign from './sign';
import verify from './verify';
@@ -12,13 +13,13 @@ const MESSAGE = stringToU8a('this is a message');
describe('sign and verify', () => {
it('has 64-byte signatures', () => {
const pair = pairFromRandom();
const pair = pairFromSeed(randomAsU8a());
expect(sign(MESSAGE, pair)).toHaveLength(64);
});
it('can sign and verify a message', () => {
const pair = pairFromRandom();
const pair = pairFromSeed(randomAsU8a());
const signature = sign(MESSAGE, pair);
expect(verify(MESSAGE, signature, pair.publicKey)).toBe(true);