Skip to content

Commit c8856ab

Browse files
axicgodking29
authored andcommitted
Introduce support for checksum addresses
ethereum/EIPs#55
1 parent 388826e commit c8856ab

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

index.js

+32
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,38 @@ exports.privateToAddress = function (privateKey) {
325325
return exports.publicToAddress(privateToPublic(privateKey))
326326
}
327327

328+
/**
329+
* Returns a checksummed address
330+
* @method toChecksumAddress
331+
* @param {String} address
332+
* @return {String}
333+
*/
334+
exports.toChecksumAddress = function (address) {
335+
address = exports.stripHexPrefix(address)
336+
var hash = exports.sha3(address).toString('hex')
337+
var ret = '0x'
338+
339+
for (var i = 0; i < address.length; i++) {
340+
if (parseInt(hash[i], 16) >= 8) {
341+
ret += address[i].toUpperCase()
342+
} else {
343+
ret += address[i]
344+
}
345+
}
346+
347+
return ret
348+
}
349+
350+
/**
351+
* Checks if the address is a valid checksummed address
352+
* @method isValidChecksumAddress
353+
* @param {Buffer} address
354+
* @return {Boolean}
355+
*/
356+
exports.isValidChecksumAddress = function (address) {
357+
return exports.toChecksumAddress(address.toLowerCase()) === address
358+
}
359+
328360
/**
329361
* Generates an address of a newly created contract
330362
* @method generateAddress

test/index.js

+34
Original file line numberDiff line numberDiff line change
@@ -380,3 +380,37 @@ describe('ecrecover', function () {
380380
})
381381
})
382382
})
383+
384+
var checksumAddresses = [
385+
// All caps
386+
'0x52908400098527886E0F7030069857D2E4169EE7',
387+
'0x8617E340B3D01FA5F11F306F4090FD50E238070D',
388+
// All Lower
389+
'0xde709f2102306220921060314715629080e2fb77',
390+
'0x27b1fdb04752bbc536007a920d24acb045561c26',
391+
// Normal
392+
'0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed',
393+
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
394+
'0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB',
395+
'0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb'
396+
]
397+
398+
describe('.toChecksumAddress()', function () {
399+
it('should work', function () {
400+
for (var i = 0; i < checksumAddresses.length; i++) {
401+
var tmp = checksumAddresses[i]
402+
assert.equal(ethUtils.toChecksumAddress(tmp.toLowerCase()), tmp)
403+
}
404+
})
405+
})
406+
407+
describe('.isValidChecksumAddress()', function () {
408+
it('should return true', function () {
409+
for (var i = 0; i < checksumAddresses.length; i++) {
410+
assert.equal(ethUtils.isValidChecksumAddress(checksumAddresses[i]), true)
411+
}
412+
})
413+
it('should validate', function () {
414+
assert.equal(ethUtils.isValidChecksumAddress('0x2f015c60e0be116b1f0cd534704db9c92118fb6a'), false)
415+
})
416+
})

0 commit comments

Comments
 (0)