Skip to content
This repository has been archived by the owner on Oct 7, 2024. It is now read-only.

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
adonesky1 committed Dec 6, 2022
1 parent c843d0e commit 160c5de
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 138 deletions.
139 changes: 6 additions & 133 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const { bytesToHex } = require('ethereum-cryptography/utils');
const {
stripHexPrefix,
privateToPublic,
bufferToHex,
publicToAddress,
ecsign,
arrToBufArr,
Expand Down Expand Up @@ -159,7 +158,7 @@ class HdKeyring {
// exportAccount should return a hex-encoded private key:
async exportAccount(address, opts = {}) {
const wallet = this._getWalletForAccount(address, opts);
return wallet.privateKey.toString('hex');
return bytesToHex(wallet.privKeyBytes);
}

// tx is an instance of the ethereumjs-transaction class.
Expand Down Expand Up @@ -213,18 +212,15 @@ class HdKeyring {
removeAccount(address) {
if (
!this._wallets
.map(({ publicKey }) =>
bufferToHex(publicToAddress(publicKey)).toLowerCase(),
)
.includes(address.toLowerCase())
.map(({ publicKey }) => this._AddressfromPublicKey(publicKey))
.includes(toChecksumAddress(address))
) {
throw new Error(`Address ${address} not found in this keyring`);
}

this._wallets = this._wallets.filter(
({ publicKey }) =>
bufferToHex(publicToAddress(publicKey)).toLowerCase() !==
address.toLowerCase(),
this._AddressfromPublicKey(publicKey) !== toChecksumAddress(address),
);
}

Expand All @@ -247,131 +243,8 @@ class HdKeyring {
const address = normalize(account);
let wallet = this._wallets.find(({ publicKey }) => {
return (
this._AddressfromPublicKey(publicKey).toLowerCase() ===
address.toLowerCase()
);
});
if (!wallet) {
throw new Error('Simple Keyring - Unable to find matching address.');
}

if (opts.withAppKeyOrigin) {
const { privateKey } = wallet;
const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');
const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
const appKeyPrivateKey = arrToBufArr(keccak256(appKeyBuffer, 256));
const appKeyPublicKey = privateToPublic(appKeyPrivateKey);
wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
}

return wallet;
}

/* BASE KEYRING METHODS */

// returns an address specific to an app
async getAppKeyAddress(address, origin) {
if (!origin || typeof origin !== 'string') {
throw new Error(`'origin' must be a non-empty string`);
}
const wallet = this._getWalletForAccount(address, {
withAppKeyOrigin: origin,
});
const appKeyAddress = normalize(
publicToAddress(wallet.publicKey).toString('hex'),
);
return appKeyAddress;
}

// exportAccount should return a hex-encoded private key:
async exportAccount(address, opts = {}) {
const wallet = this._getWalletForAccount(address, opts);
return wallet.privateKey.toString('hex');
}

// tx is an instance of the ethereumjs-transaction class.
async signTransaction(address, tx, opts = {}) {
const privKey = this._getPrivateKeyFor(address, opts);
const signedTx = tx.sign(privKey);
// Newer versions of Ethereumjs-tx are immutable and return a new tx object
return signedTx === undefined ? tx : signedTx;
}

// For eth_sign, we need to sign arbitrary data:
async signMessage(address, data, opts = {}) {
const message = stripHexPrefix(data);
const privKey = this._getPrivateKeyFor(address, opts);
const msgSig = ecsign(Buffer.from(message, 'hex'), privKey);
const rawMsgSig = concatSig(msgSig.v, msgSig.r, msgSig.s);
return rawMsgSig;
}

// For personal_sign, we need to prefix the message:
async signPersonalMessage(address, msgHex, opts = {}) {
const privKey = this._getPrivateKeyFor(address, opts);
const privateKey = Buffer.from(privKey, 'hex');
const sig = personalSign({ privateKey, data: msgHex });
return sig;
}

// For eth_decryptMessage:
async decryptMessage(withAccount, encryptedData) {
const wallet = this._getWalletForAccount(withAccount);
const { privateKey } = wallet;
const sig = decrypt({ privateKey, encryptedData });
return sig;
}

// personal_signTypedData, signs data along with the schema
async signTypedData(
withAccount,
typedData,
opts = { version: SignTypedDataVersion.V1 },
) {
// Treat invalid versions as "V1"
const version = Object.keys(SignTypedDataVersion).includes(opts.version)
? opts.version
: SignTypedDataVersion.V1;

const privateKey = this._getPrivateKeyFor(withAccount, opts);
return signTypedData({ privateKey, data: typedData, version });
}

removeAccount(address) {
if (
!this._wallets
.map((w) => normalize(w.getAddress().toString('hex')))
.includes(address.toLowerCase())
) {
throw new Error(`Address ${address} not found in this keyring`);
}

this._wallets = this._wallets.filter(
(w) =>
normalize(w.getAddress().toString('hex')) !== address.toLowerCase(),
);
}

// get public key for nacl
async getEncryptionPublicKey(withAccount, opts = {}) {
const privKey = this._getPrivateKeyFor(withAccount, opts);
const publicKey = getEncryptionPublicKey(privKey);
return publicKey;
}

_getPrivateKeyFor(address, opts = {}) {
if (!address) {
throw new Error('Must specify address.');
}
const wallet = this._getWalletForAccount(address, opts);
return wallet.privateKey;
}

_getWalletForAccount(account, opts = {}) {
const address = normalize(account);
let wallet = this._wallets.find((w) => {
return (
normalize(w.getAddress().toString('hex')) === address.toLowerCase()
this._AddressfromPublicKey(publicKey) ===
toChecksumAddress(address)
);
});
if (!wallet) {
Expand Down
17 changes: 12 additions & 5 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
toBuffer,
ecrecover,
pubToAddress,
toChecksumAddress,
} = require('@ethereumjs/util');
const {
TransactionFactory,
Expand Down Expand Up @@ -58,11 +59,17 @@ describe('hd-keyring', () => {
});
const newAccounts = await newHDKeyring.getAccounts();
const oldAccounts = await oldHDKeyring.getAccounts();
await expect(newAccounts[0]).toStrictEqual(oldAccounts[0]);
await expect(newAccounts[0]).toStrictEqual(
toChecksumAddress(oldAccounts[0]),
);

await expect(newAccounts[1]).toStrictEqual(oldAccounts[1]);
await expect(newAccounts[1]).toStrictEqual(
toChecksumAddress(oldAccounts[1]),
);

await expect(newAccounts[2]).toStrictEqual(oldAccounts[2]);
await expect(newAccounts[2]).toStrictEqual(
toChecksumAddress(oldAccounts[2]),
);
}),
);
});
Expand Down Expand Up @@ -578,7 +585,7 @@ describe('hd-keyring', () => {
const pub = ecrecover(m, v, r, s);
const adr = `0x${pubToAddress(pub).toString('hex')}`;

expect(adr).toBe(accountAddress);
expect(toChecksumAddress(adr)).toBe(accountAddress);
});
});

Expand Down Expand Up @@ -836,7 +843,7 @@ describe('hd-keyring', () => {
signature,
version: SignTypedDataVersion.V4,
});
expect(restored).toBe(address);
expect(toChecksumAddress(restored)).toBe(address);
});
});

Expand Down

0 comments on commit 160c5de

Please sign in to comment.