diff --git a/packages/keyring/src/index.spec.ts b/packages/keyring/src/index.spec.ts index f4e7cd4dc..e8273df36 100644 --- a/packages/keyring/src/index.spec.ts +++ b/packages/keyring/src/index.spec.ts @@ -309,16 +309,20 @@ describe('keypair', (): void => { ).toEqual(ETH_ADDRESS_ONE); }); - it('encodes a pair toJSON', (): void => { + it('encodes a pair toJSON (and decodes)', (): void => { const pair = keyring.createFromUri(PHRASE); const json = pair.toJson('password'); - expect(json.address).toEqual(ETH_ADDRESS_ONE); + expect(json.address).toEqual('0x0381351b1b46d2602b0992bb5d5531f9c1696b0812feb2534b6884adc47e2e1d8b'); expect(json.encoding).toEqual({ content: ['pkcs8', 'ethereum'], type: ['scrypt', 'xsalsa20-poly1305'], version: '3' }); + + const newPair = keyring.addFromJson(json); + + expect(newPair.publicKey).toEqual(pair.publicKey); }); it('allows adding from JSON', (): void => { diff --git a/packages/keyring/src/pair/index.ts b/packages/keyring/src/pair/index.ts index ec7e9967a..59bfe90ba 100644 --- a/packages/keyring/src/pair/index.ts +++ b/packages/keyring/src/pair/index.ts @@ -5,8 +5,8 @@ import type { Keypair, KeypairType } from '@polkadot/util-crypto/types'; import type { KeyringPair, KeyringPair$Json, KeyringPair$JsonEncodingTypes, KeyringPair$Meta, SignOptions } from '../types'; import type { PairInfo } from './types'; -import { assert, u8aConcat, u8aEq, u8aToU8a } from '@polkadot/util'; -import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVrfSign, schnorrkelVrfVerify, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto'; +import { assert, u8aConcat, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; +import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVrfSign, schnorrkelVrfVerify, secp256k1Compress, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto'; import { decodePair } from './decode'; import { encodePair } from './encode'; @@ -173,7 +173,11 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P ); }, toJson: (passphrase?: string): KeyringPair$Json => { - const address = encodeAddress(); + // NOTE: in the case of Ethereum and Ecdsa, we encode the ful publicKey - to allow extraction. This will NOT match + // e.g. an Ethereum address which is non-reversible, so not used here) + const address = ['ecdsa', 'ethereum'].includes(type) + ? u8aToHex(secp256k1Compress(publicKey)) + : encodeAddress(); return pairToJson(type, { address, meta }, recode(passphrase), !!passphrase); },