From c8856abc51aa3b5c768beea67df5ac5759f524e7 Mon Sep 17 00:00:00 2001 From: AgileWebDev92 Date: Tue, 8 Mar 2016 19:49:16 +0000 Subject: [PATCH] Introduce support for checksum addresses https://github.com/ethereum/EIPs/issues/55 --- index.js | 32 ++++++++++++++++++++++++++++++++ test/index.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/index.js b/index.js index da38815..d8bed58 100644 --- a/index.js +++ b/index.js @@ -325,6 +325,38 @@ exports.privateToAddress = function (privateKey) { return exports.publicToAddress(privateToPublic(privateKey)) } +/** + * Returns a checksummed address + * @method toChecksumAddress + * @param {String} address + * @return {String} + */ +exports.toChecksumAddress = function (address) { + address = exports.stripHexPrefix(address) + var hash = exports.sha3(address).toString('hex') + var ret = '0x' + + for (var i = 0; i < address.length; i++) { + if (parseInt(hash[i], 16) >= 8) { + ret += address[i].toUpperCase() + } else { + ret += address[i] + } + } + + return ret +} + +/** + * Checks if the address is a valid checksummed address + * @method isValidChecksumAddress + * @param {Buffer} address + * @return {Boolean} + */ +exports.isValidChecksumAddress = function (address) { + return exports.toChecksumAddress(address.toLowerCase()) === address +} + /** * Generates an address of a newly created contract * @method generateAddress diff --git a/test/index.js b/test/index.js index 18dc2b8..8ebffa1 100644 --- a/test/index.js +++ b/test/index.js @@ -380,3 +380,37 @@ describe('ecrecover', function () { }) }) }) + +var checksumAddresses = [ + // All caps + '0x52908400098527886E0F7030069857D2E4169EE7', + '0x8617E340B3D01FA5F11F306F4090FD50E238070D', + // All Lower + '0xde709f2102306220921060314715629080e2fb77', + '0x27b1fdb04752bbc536007a920d24acb045561c26', + // Normal + '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed', + '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359', + '0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB', + '0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb' +] + +describe('.toChecksumAddress()', function () { + it('should work', function () { + for (var i = 0; i < checksumAddresses.length; i++) { + var tmp = checksumAddresses[i] + assert.equal(ethUtils.toChecksumAddress(tmp.toLowerCase()), tmp) + } + }) +}) + +describe('.isValidChecksumAddress()', function () { + it('should return true', function () { + for (var i = 0; i < checksumAddresses.length; i++) { + assert.equal(ethUtils.isValidChecksumAddress(checksumAddresses[i]), true) + } + }) + it('should validate', function () { + assert.equal(ethUtils.isValidChecksumAddress('0x2f015c60e0be116b1f0cd534704db9c92118fb6a'), false) + }) +})