address.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import { keccak256 } from "../crypto/index.js";
  2. import { getBytes, assertArgument } from "../utils/index.js";
  3. const BN_0 = BigInt(0);
  4. const BN_36 = BigInt(36);
  5. function getChecksumAddress(address) {
  6. // if (!isHexString(address, 20)) {
  7. // logger.throwArgumentError("invalid address", "address", address);
  8. // }
  9. address = address.toLowerCase();
  10. const chars = address.substring(2).split("");
  11. const expanded = new Uint8Array(40);
  12. for (let i = 0; i < 40; i++) {
  13. expanded[i] = chars[i].charCodeAt(0);
  14. }
  15. const hashed = getBytes(keccak256(expanded));
  16. for (let i = 0; i < 40; i += 2) {
  17. if ((hashed[i >> 1] >> 4) >= 8) {
  18. chars[i] = chars[i].toUpperCase();
  19. }
  20. if ((hashed[i >> 1] & 0x0f) >= 8) {
  21. chars[i + 1] = chars[i + 1].toUpperCase();
  22. }
  23. }
  24. return "0x" + chars.join("");
  25. }
  26. // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
  27. // Create lookup table
  28. const ibanLookup = {};
  29. for (let i = 0; i < 10; i++) {
  30. ibanLookup[String(i)] = String(i);
  31. }
  32. for (let i = 0; i < 26; i++) {
  33. ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
  34. }
  35. // How many decimal digits can we process? (for 64-bit float, this is 15)
  36. // i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER));
  37. const safeDigits = 15;
  38. function ibanChecksum(address) {
  39. address = address.toUpperCase();
  40. address = address.substring(4) + address.substring(0, 2) + "00";
  41. let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");
  42. // Javascript can handle integers safely up to 15 (decimal) digits
  43. while (expanded.length >= safeDigits) {
  44. let block = expanded.substring(0, safeDigits);
  45. expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
  46. }
  47. let checksum = String(98 - (parseInt(expanded, 10) % 97));
  48. while (checksum.length < 2) {
  49. checksum = "0" + checksum;
  50. }
  51. return checksum;
  52. }
  53. ;
  54. const Base36 = (function () {
  55. ;
  56. const result = {};
  57. for (let i = 0; i < 36; i++) {
  58. const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i];
  59. result[key] = BigInt(i);
  60. }
  61. return result;
  62. })();
  63. function fromBase36(value) {
  64. value = value.toLowerCase();
  65. let result = BN_0;
  66. for (let i = 0; i < value.length; i++) {
  67. result = result * BN_36 + Base36[value[i]];
  68. }
  69. return result;
  70. }
  71. /**
  72. * Returns a normalized and checksumed address for %%address%%.
  73. * This accepts non-checksum addresses, checksum addresses and
  74. * [[getIcapAddress]] formats.
  75. *
  76. * The checksum in Ethereum uses the capitalization (upper-case
  77. * vs lower-case) of the characters within an address to encode
  78. * its checksum, which offers, on average, a checksum of 15-bits.
  79. *
  80. * If %%address%% contains both upper-case and lower-case, it is
  81. * assumed to already be a checksum address and its checksum is
  82. * validated, and if the address fails its expected checksum an
  83. * error is thrown.
  84. *
  85. * If you wish the checksum of %%address%% to be ignore, it should
  86. * be converted to lower-case (i.e. ``.toLowercase()``) before
  87. * being passed in. This should be a very rare situation though,
  88. * that you wish to bypass the safegaurds in place to protect
  89. * against an address that has been incorrectly copied from another
  90. * source.
  91. *
  92. * @example:
  93. * // Adds the checksum (via upper-casing specific letters)
  94. * getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72")
  95. * //_result:
  96. *
  97. * // Converts ICAP address and adds checksum
  98. * getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  99. * //_result:
  100. *
  101. * // Throws an error if an address contains mixed case,
  102. * // but the checksum fails
  103. * getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
  104. * //_error:
  105. */
  106. export function getAddress(address) {
  107. assertArgument(typeof (address) === "string", "invalid address", "address", address);
  108. if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
  109. // Missing the 0x prefix
  110. if (!address.startsWith("0x")) {
  111. address = "0x" + address;
  112. }
  113. const result = getChecksumAddress(address);
  114. // It is a checksummed address with a bad checksum
  115. assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address);
  116. return result;
  117. }
  118. // Maybe ICAP? (we only support direct mode)
  119. if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
  120. // It is an ICAP address with a bad checksum
  121. assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address);
  122. let result = fromBase36(address.substring(4)).toString(16);
  123. while (result.length < 40) {
  124. result = "0" + result;
  125. }
  126. return getChecksumAddress("0x" + result);
  127. }
  128. assertArgument(false, "invalid address", "address", address);
  129. }
  130. /**
  131. * The [ICAP Address format](link-icap) format is an early checksum
  132. * format which attempts to be compatible with the banking
  133. * industry [IBAN format](link-wiki-iban) for bank accounts.
  134. *
  135. * It is no longer common or a recommended format.
  136. *
  137. * @example:
  138. * getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72");
  139. * //_result:
  140. *
  141. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  142. * //_result:
  143. *
  144. * // Throws an error if the ICAP checksum is wrong
  145. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37");
  146. * //_error:
  147. */
  148. export function getIcapAddress(address) {
  149. //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();
  150. let base36 = BigInt(getAddress(address)).toString(36).toUpperCase();
  151. while (base36.length < 30) {
  152. base36 = "0" + base36;
  153. }
  154. return "XE" + ibanChecksum("XE00" + base36) + base36;
  155. }
  156. //# sourceMappingURL=address.js.map