Add Ethereum-compatible seed from mnemonic (#662)

* Add Ethereum-compatible seed from mnemonic

* Change encode signature to allow publicKeys

* Make CC happier
This commit is contained in:
Jaco Greeff
2020-08-17 11:28:59 +02:00
committed by GitHub
parent 9cc984e8ae
commit 27ae11860d
15 changed files with 282 additions and 37 deletions
+25
View File
@@ -213,6 +213,31 @@ describe('keypair', (): void => {
});
});
describe('ethereum', (): void => {
const PHRASE = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
let keyring: Keyring;
beforeEach((): void => {
keyring = new Keyring({ type: 'ethereum' });
});
it('adds a pair with the correct address', (): void => {
const pair = keyring.createFromUri(PHRASE);
expect(pair.publicKey).toEqual(hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077'));
expect(pair.address).toEqual('0x4119b2e6c3Cb618F4f0B93ac77f9BeeC7FF02887');
});
it('allows adding from JSON', (): void => {
const pair = keyring.addFromJson(
JSON.parse('{"address":"34wtVv7QQ5NsJQDcyWYnz9J5XrNgYE3VcRfKQ6scSt7o1ixi","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}')
);
expect(pair.publicKey).toEqual(hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077'));
expect(pair.address).toEqual('0x4119b2e6c3Cb618F4f0B93ac77f9BeeC7FF02887');
});
});
describe('util', (): void => {
let keyring: Keyring;
+6 -7
View File
@@ -6,7 +6,7 @@ import { KeypairType, Keypair } from '@polkadot/util-crypto/types';
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$JsonEncodingTypes, KeyringPair$Meta, KeyringOptions } from './types';
import { assert, hexToU8a, isHex, isUndefined, stringToU8a } from '@polkadot/util';
import { base64Decode, decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, secp256k1KeypairFromSeed as secp256k1FromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { base64Decode, decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, secp256k1KeypairFromSeed as secp256k1FromSeed, mnemonicToBip39, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
import createPair from './pair';
@@ -48,7 +48,7 @@ export default class Keyring implements KeyringInstance {
constructor (options: KeyringOptions = {}) {
options.type = options.type || 'ed25519';
assert(options && ['ecdsa', 'ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519', 'sr25519' or 'ecdsa', found '${options.type}`);
assert(options && ['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519', 'sr25519' or 'ecdsa', found '${options.type}`);
this.#pairs = new Pairs();
this.#ss58 = options.ss58Format;
@@ -170,11 +170,9 @@ export default class Keyring implements KeyringInstance {
const parts = str.split(' ');
if ([12, 15, 18, 21, 24].includes(parts.length)) {
// FIXME This keeps compat with older versions, but breaks compat with subkey
// seed = type === 'sr25519'
// ? mnemonicToMiniSecret(phrase, password)
// : mnemonicToSeed(phrase, password);
seed = mnemonicToMiniSecret(phrase, password);
seed = type === 'ethereum'
? mnemonicToBip39(phrase)
: mnemonicToMiniSecret(phrase, password);
} else {
assert(str.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
@@ -182,6 +180,7 @@ export default class Keyring implements KeyringInstance {
}
}
// FIXME Need to support Ethereum-type derivation paths
const derived = keyFromPath(keypairFromSeed[type](seed), path, type);
return createPair({ toSS58: this.encodeAddress, type }, derived, meta, null);
+10
View File
@@ -4,6 +4,8 @@
import { cryptoWaitReady, encodeAddress as toSS58, setSS58Format } from '@polkadot/util-crypto';
import { hexToU8a } from '@polkadot/util';
import { PAIRS } from '../testing';
import testingPairs from '../testingPairs';
import createPair from '.';
@@ -103,4 +105,12 @@ describe('pair', (): void => {
pair.sign(new Uint8Array([0]))
).toThrow('Cannot sign with a locked key pair');
});
describe('ethereum', (): void => {
it('has a valid address from a known public', (): void => {
const pair = createPair({ toSS58, type: 'ethereum' }, { publicKey: hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077') });
expect(pair.address).toEqual('0x4119b2e6c3Cb618F4f0B93ac77f9BeeC7FF02887');
});
});
});
+7 -7
View File
@@ -7,7 +7,7 @@ import { KeyringPair, KeyringPair$Json, KeyringPair$JsonEncodingTypes, KeyringPa
import { PairInfo } from './types';
import { assert, u8aConcat } from '@polkadot/util';
import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, secp256k1Verify } from '@polkadot/util-crypto';
import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify, secp256k1Compress, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, secp256k1Verify } from '@polkadot/util-crypto';
import decode from './decode';
import encode from './encode';
@@ -74,14 +74,14 @@ function verify (type: KeypairType, message: Uint8Array, signature: Uint8Array,
}[type]();
}
function getAddress (type: KeypairType, publicKey: Uint8Array): Uint8Array {
function getAddress (type: KeypairType, publicKey: Uint8Array, isCompressed = false): Uint8Array {
if (type === 'ecdsa' && publicKey.length > 32) {
return blake2AsU8a(publicKey);
} else if (type === 'ethereum' && publicKey.length > 32) {
return keccakAsU8a(publicKey);
} else {
return publicKey;
} else if (type === 'ethereum' && isCompressed) {
return secp256k1Compress(publicKey).slice(-32);
}
return publicKey;
}
// Not 100% correct, since it can be a Uint8Array, but an invalid one - just say "undefined" is anything non-valid
@@ -182,7 +182,7 @@ export default function createPair ({ toSS58, type }: Setup, { publicKey, secret
return sign(type, message, { publicKey, secretKey }, options);
},
toJson: (passphrase?: string): KeyringPair$Json =>
toJson(type, { address: toSS58(getAddress(type, publicKey)), meta }, recode(passphrase), !!passphrase),
toJson(type, { address: toSS58(getAddress(type, publicKey, true)), meta }, recode(passphrase), !!passphrase),
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
verify(type, message, signature, publicKey)
};
@@ -4,26 +4,58 @@
import { ethereumEncode } from './';
const ADDRESS = '0x00a329c0648769A73afAc7F9381E08FB43dBEA72';
describe('formatAddress', () => {
it('returns 0x00..00 for no address', () => {
expect(ethereumEncode()).toBe('0x');
describe('address to address encoding', (): void => {
const ADDRESS = '0x00a329c0648769A73afAc7F9381E08FB43dBEA72';
it('returns 0x for no address', () => {
expect(ethereumEncode()).toBe('0x');
});
it('returns fails on invalid address', () => {
expect(
() => ethereumEncode('0xnotaddress')
).toThrow(/Invalid address or publicKey passed/);
});
it('converts lowercase to the checksummed address', () => {
expect(ethereumEncode(ADDRESS.toLowerCase())).toBe(ADDRESS);
});
it('converts uppercase to the checksummed address', () => {
expect(ethereumEncode(ADDRESS.toUpperCase().replace('0X', '0x'))).toBe(ADDRESS);
});
it('returns formatted address on checksum input', () => {
expect(ethereumEncode(ADDRESS)).toBe(ADDRESS);
});
});
it('returns 0x00..00 on invalid address', () => {
expect(ethereumEncode('0xnotaddress')).toBe('0x');
});
describe('from publicKey', (): void => {
const ADDRESS = '0x4119b2e6c3Cb618F4f0B93ac77f9BeeC7FF02887';
it('converts lowercase to the checksummed address', () => {
expect(ethereumEncode(ADDRESS.toLowerCase())).toBe(ADDRESS);
});
it('encodes a compressed publicKey', (): void => {
expect(
ethereumEncode('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
).toEqual(ADDRESS);
});
it('converts uppercase to the checksummed address', () => {
expect(ethereumEncode(ADDRESS.toUpperCase().replace('0X', '0x'))).toBe(ADDRESS);
});
it('encodes a compressed publicKey (indicator)', (): void => {
expect(
ethereumEncode('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
).toEqual(ADDRESS);
});
it('returns formatted address on checksum input', () => {
expect(ethereumEncode(ADDRESS)).toBe(ADDRESS);
it('encodes an expanded publicKey', (): void => {
expect(
ethereumEncode('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
).toEqual(ADDRESS);
});
it('encodes an expanded publicKey (indicator + x/y)', (): void => {
expect(
ethereumEncode('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
).toEqual(ADDRESS);
});
});
});
+10 -7
View File
@@ -2,22 +2,25 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aToHex, u8aToU8a } from '@polkadot/util';
import { assert, u8aToHex, u8aToU8a } from '@polkadot/util';
import { keccakAsU8a } from '../keccak';
import isEthereumAddress from './isAddress';
import { secp256k1Expand } from '../secp256k1';
export default function ethereumEncode (_address?: string | Uint8Array): string {
if (!_address) {
export default function ethereumEncode (addressOrPublic?: string | Uint8Array): string {
if (!addressOrPublic) {
return '0x';
}
const address = u8aToHex(u8aToU8a(_address), -1, false);
let u8aAddress = u8aToU8a(addressOrPublic);
if (!isEthereumAddress(`0x${address}`)) {
return '0x';
assert([20, 32, 33, 64, 65].includes(u8aAddress.length), 'Invalid address or publicKey passed');
if (u8aAddress.length > 20) {
u8aAddress = keccakAsU8a(secp256k1Expand(u8aAddress)).slice(-20);
}
const address = u8aToHex(u8aAddress, -1, false);
const hash = u8aToHex(keccakAsU8a(address), -1, false);
let result = '';
+1 -1
View File
@@ -7,7 +7,7 @@ import '../polyfill';
/**
* @summary Create valid mnemonic strings, validate them using BIP39, and convert them to valid seeds
*/
export { default as mnemonicToBip39 } from './toBip39';
export { default as mnemonicGenerate } from './generate';
export { default as mnemonicToEntropy } from './toEntropy';
export { default as mnemonicToMiniSecret } from './toMiniSecret';
@@ -0,0 +1,17 @@
// Copyright 2017-2020 @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 { u8aToHex } from '@polkadot/util';
import { mnemonicToBip39 } from './';
describe('mnemonicToBip39Seed', (): void => {
it('generates a valid seed', (): void => {
expect(
u8aToHex(
mnemonicToBip39('seed sock milk update focus rotate barely fade car face mechanic mercy')
)
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
});
});
@@ -0,0 +1,33 @@
// Copyright 2017-2020 @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 { mnemonicToSeedSync } from 'bip39';
import { bufferToU8a } from '@polkadot/util';
// import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
/**
* @name toSeed
* @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
* @example
* <BR>
*
* ```javascript
* import { mnemonicGenerate, mnemonicToBip39, mnemonicValidate } from '@polkadot/util-crypto';
*
* const mnemonic = mnemonicGenerate(); // => string
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
*
* if (isValidMnemonic) {
* console.log(`Seed generated from mnemonic: ${mnemonicToBip39(mnemonic)}`); => u8a
* }
* ```
*/
export default function toBip39 (mnemonic: string, password = ''): Uint8Array {
// FIXMe Re-add when we have support in the WASM libs again
// return isReady()
// ? bip39ToSeed(mnemonic, password)
return bufferToU8a(mnemonicToSeedSync(mnemonic, password)).subarray(0, 32);
}
@@ -0,0 +1,19 @@
// Copyright 2017-2020 @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 { hexToU8a } from '@polkadot/util';
import { secp256k1Compress } from './';
describe('secp256k1Compress', (): void => {
it('compresses a known key', (): void => {
expect(
secp256k1Compress(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
)
).toEqual(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
);
});
});
@@ -0,0 +1,18 @@
// Copyright 2017-2020 @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 elliptic from 'elliptic';
import sanitizePublic from './sanitizePublic';
const EC = elliptic.ec;
const ec = new EC('secp256k1');
export default function secp256k1Compress (publicKey: Uint8Array): Uint8Array {
return new Uint8Array(
ec.keyFromPublic(
sanitizePublic(publicKey)
).getPublic().encodeCompressed()
);
}
@@ -0,0 +1,49 @@
// Copyright 2017-2020 @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 { hexToU8a } from '@polkadot/util';
import { secp256k1Expand } from './';
describe('secp256k1Expand', (): void => {
it('expands a known key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
it('expands a known key (no indicator)', (): void => {
expect(
secp256k1Expand(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
it('expands a known full key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
it('expands a known full key (no indicator)', (): void => {
expect(
secp256k1Expand(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
});
@@ -0,0 +1,20 @@
// Copyright 2017-2020 @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 elliptic from 'elliptic';
import { bnToU8a, u8aConcat } from '@polkadot/util';
import sanitizePublic from './sanitizePublic';
const EC = elliptic.ec;
const ec = new EC('secp256k1');
export default function secp256k1Expand (publicKey: Uint8Array): Uint8Array {
const expanded = ec.keyFromPublic(sanitizePublic(publicKey)).getPublic();
return u8aConcat(
bnToU8a(expanded.getX(), { bitLength: 256, isLe: false }),
bnToU8a(expanded.getY(), { bitLength: 256, isLe: false })
);
}
@@ -2,6 +2,8 @@
// 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 secp256k1Compress } from './compress';
export { default as secp256k1Expand } from './expand';
export { default as secp256k1KeypairFromSeed } from './keypair/fromSeed';
export { default as secp256k1Recover } from './recover';
export { default as secp256k1Verify } from './verify';
@@ -0,0 +1,18 @@
// Copyright 2017-2020 @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 { assert, u8aConcat } from '@polkadot/util';
const INDICATOR_COMP = new Uint8Array([3]);
const INDICATOR_FULL = new Uint8Array([4]);
export default function sanitizePublic (publicKey: Uint8Array): Uint8Array {
assert([32, 33, 64, 65].includes(publicKey.length), 'Invalid publicKey provided');
return [33, 65].includes(publicKey.length)
? publicKey
: publicKey.length === 32
? u8aConcat(INDICATOR_COMP, publicKey)
: u8aConcat(INDICATOR_FULL, publicKey);
}