address.ts 5.8 KB

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