我们在使用以太坊钱包,比如imToken的时候,会发现以太坊账户地址是大小写混合的,看起来似乎并没有什么特别的规律,但实际上以太坊地址编码是有规范的。只是有些软件并不关心这个规范,也不强制进行地址编码格式校验,从技术原理上讲,这没有什么问题,但在用户实际使用这类软件的过程中,可能会发生由于漏写、错写某个地址,导致数字货币被存入黑洞地址。因此若账户地址编码带有一定的自校验结构,就很大程度上避免因地址书写错误而造成的财产损失。以太坊地址是通过有规律的大小写混合实现地址自校验结构,可参见https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md。
符合EIP55规范的软件或APP应该对传入的地址进行一次检验,以防止人为书写错误。总结起来就是一句话:对账户地址求keccak256哈希运算,根据运算结果值的二进制位图决定地址十六进制字符串(0-9,a-f)的大写或小些。实际操作例子如下:
1.把下面的代码存为ethaddr.js文件:
const createKeccakHash = require('keccak')
function toChecksumAddress (address) {
address = address.toLowerCase().replace('0x', '')
varhash = createKeccakHash('keccak256').update(address).digest('hex')
varret = '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
}
console.log(toChecksumAddress('0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed'))
console.log(toChecksumAddress('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359'))
console.log(toChecksumAddress('0xdbf03b407c01e7cd3cbea99509d93f8dddc8c6fb'))
console.log(toChecksumAddress('0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb'))
console.log(toChecksumAddress('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359'))
console.log(toChecksumAddress('0x9e8a9d48439e88260e00d663d4fdacc9f02b50ad'))
2. 在Shell命令行执行npm install keccak,运行node ethaddr.js,可以看到在代码中传入的地址都是小写,但是转换为大小写混合编码校验后的地址输出为:
0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed
0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359
0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB
0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb
0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359
0x9e8a9D48439E88260e00d663d4fDaCc9F02B50aD
3. 可以在一些网站提供的网页版工具验证以太坊地址是否符合校验规范:
https://tokenmarket.net/ethereum-address-validator
Ethereum address validator,Copy-paste Ethereum address in a format that starts 0x:
验证框里输入0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed,输出错误格式提示
Address is not in a checksummed formatbecause it is all lowercase.
验证框里输入0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed,输出正确格式提示:
This Ethereum address is valid. Note thatwe only check if the address is correctly typed and we cannot check if thereceiver holds a private key for this address.
验证框里输入0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD,输出错误格式提示:
This Ethereum address is invalid.
网友评论