Ether

如何檢查乙太坊地址是否有效?

  • January 27, 2022

我讀過很多次,除非您想不小心將乙太幣發送到無人區,否則您永遠不應該手動輸入地址。我想知道這些校驗和可能是什麼。有沒有辦法告訴發生了錯字?如何,以及它的格式規則是什麼?我問,所以我可以潛在地創建一個包裝函式,在送出到網路之前檢查這些東西。

正常地址

EIP 55添加了一個“基於大寫的校驗和”,由 Geth 於 2016 年 5 月實施。以下是Geth 的 Javascript 程式碼:

/**
* Checks if the given string is an address
*
* @method isAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isAddress = function (address) {
   if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
       // check if it has the basic requirements of an address
       return false;
   } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
       // If it's all small caps or all all caps, return true
       return true;
   } else {
       // Otherwise check each case
       return isChecksumAddress(address);
   }
};

/**
* Checks if the given string is a checksummed address
*
* @method isChecksumAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isChecksumAddress = function (address) {
   // Check each case
   address = address.replace('0x','');
   var addressHash = sha3(address.toLowerCase());
   for (var i = 0; i < 40; i++ ) {
       // the nth letter should be uppercase if the nth digit of casemap is 1
       if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
           return false;
       }
   }
   return true;
};

ICAP 地址

ICAP 有一個可以驗證的校驗和。您可以查看Geth 的 icap.go,這是其中的一個片段:

// https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN
func validCheckSum(s string) error {
   s = join(s[4:], s[:4])
   expanded, err := iso13616Expand(s)
   if err != nil {
       return err
   }
   checkSumNum, _ := new(big.Int).SetString(expanded, 10)
   if checkSumNum.Mod(checkSumNum, Big97).Cmp(Big1) != 0 {
       return ICAPChecksumError
   }
   return nil
}

引用自:https://ethereum.stackexchange.com/questions/1374