Skip to content

Commit

Permalink
Introduce support for checksum addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
axic authored and AgileWebDev92 committed Mar 8, 2016
1 parent 388826e commit c8856ab
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
32 changes: 32 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})

0 comments on commit c8856ab

Please sign in to comment.