66 KeyPurpose ,
77 KeyRole ,
88 SerializableInMemoryKeyAgentData ,
9+ emip3decrypt ,
910 util
1011} from '../src' ;
1112import { Bip32Ed25519 } from '@cardano-sdk/crypto' ;
@@ -16,6 +17,11 @@ import { dummyLogger } from 'ts-log';
1617jest . mock ( '../src/util/ownSignatureKeyPaths' ) ;
1718const { ownSignatureKeyPaths } = jest . requireMock ( '../src/util/ownSignatureKeyPaths' ) ;
1819
20+ const makeEncryption = ( ) => ( {
21+ decrypt : jest . fn ( async ( encrypted : Uint8Array ) => encrypted . slice ( 1 ) ) ,
22+ encrypt : jest . fn ( async ( data : Uint8Array ) => Uint8Array . from ( [ 170 , ...data ] ) )
23+ } ) ;
24+
1925describe ( 'InMemoryKeyAgent' , ( ) => {
2026 let keyAgent : InMemoryKeyAgent ;
2127 let getPassphrase : jest . Mock ;
@@ -66,6 +72,38 @@ describe('InMemoryKeyAgent', () => {
6672 expect ( await saferKeyAgent . exportRootPrivateKey ( ) ) . not . toEqual ( await keyAgent . exportRootPrivateKey ( ) ) ;
6773 } ) ;
6874
75+ describe ( 'rootPrivateKeyEncryption injection' , ( ) => {
76+ it ( 'uses the injected encryption to encrypt the root private key' , async ( ) => {
77+ const encryption = makeEncryption ( ) ;
78+ const agent = await InMemoryKeyAgent . fromBip39MnemonicWords (
79+ { chainId : Cardano . ChainIds . Preview , getPassphrase, mnemonicWords } ,
80+ { bip32Ed25519, logger : dummyLogger , rootPrivateKeyEncryption : encryption }
81+ ) ;
82+
83+ expect ( encryption . encrypt ) . toHaveBeenCalledTimes ( 1 ) ;
84+ const { encryptedRootPrivateKeyBytes } = agent . serializableData as SerializableInMemoryKeyAgentData ;
85+ expect ( encryptedRootPrivateKeyBytes [ 0 ] ) . toBe ( 170 ) ;
86+ } ) ;
87+
88+ it ( 'uses the injected encryption to decrypt, recovering the same root key as the default' , async ( ) => {
89+ const encryption = makeEncryption ( ) ;
90+ const agent = await InMemoryKeyAgent . fromBip39MnemonicWords (
91+ { chainId : Cardano . ChainIds . Preview , getPassphrase, mnemonicWords } ,
92+ { bip32Ed25519, logger : dummyLogger , rootPrivateKeyEncryption : encryption }
93+ ) ;
94+
95+ const rootPrivateKey = await agent . exportRootPrivateKey ( ) ;
96+ expect ( encryption . decrypt ) . toHaveBeenCalled ( ) ;
97+ expect ( rootPrivateKey ) . toEqual ( await keyAgent . exportRootPrivateKey ( ) ) ;
98+ } ) ;
99+
100+ it ( 'defaults to EMIP-003 when no encryption is injected' , async ( ) => {
101+ const { encryptedRootPrivateKeyBytes } = keyAgent . serializableData as SerializableInMemoryKeyAgentData ;
102+ const decrypted = await emip3decrypt ( new Uint8Array ( encryptedRootPrivateKeyBytes ) , Buffer . from ( 'password' ) ) ;
103+ expect ( Buffer . from ( decrypted ) . toString ( 'hex' ) ) . toEqual ( await keyAgent . exportRootPrivateKey ( ) ) ;
104+ } ) ;
105+ } ) ;
106+
69107 describe ( 'serializableData' , ( ) => {
70108 let serializableData : SerializableInMemoryKeyAgentData ;
71109
0 commit comments