Source: blockchains/ethereum/common.js

  1. 'use strict';
  2. /**
  3. * @module lib/blockchains/ethereum/accounts
  4. * @summary Whiteflag API Ethereum common functions module
  5. * @description Module for common functions used by all Ethereum wub-modules
  6. */
  7. module.exports = {
  8. formatAddressApi,
  9. formatPubkeyApi,
  10. formatHexApi,
  11. formatHexEthereum
  12. };
  13. // Module constants //
  14. const ETHHEXPREFIX = '0x';
  15. const SECPUBKEYPREFIX = '04';
  16. // KEY AND ADDRESS FORMATTERS //
  17. /**
  18. * Ensures that addresses are in generic api format
  19. * @function formatAddressApi
  20. * @returns {string} The Ethereum address without 0x hex prefix
  21. */
  22. function formatAddressApi(addressHexString) {
  23. // The api addresses keys WITHOUT 0x prefix
  24. // Note that Ethereum addresses use capitials as a checksum, so no toLowerCase()
  25. if (!addressHexString) return null;
  26. if (addressHexString.substring(0, 2) === ETHHEXPREFIX) {
  27. return addressHexString.substr(2);
  28. }
  29. return addressHexString;
  30. }
  31. /**
  32. * Ensures that public keys are in generic api format
  33. * @function formatPubkeyApi
  34. * @returns {string} The Ethereum public key without 0x hex prefix but with prefix byte
  35. */
  36. function formatPubkeyApi(pubkeyHexString) {
  37. // The api uses uncompressed keys, WITHOUT 0x prefix, but WITH the SEC 0x04 prefix byte
  38. if (!pubkeyHexString) return null;
  39. pubkeyHexString = formatHexApi(pubkeyHexString);
  40. if (pubkeyHexString.length === 128) {
  41. pubkeyHexString = SECPUBKEYPREFIX + pubkeyHexString;
  42. }
  43. return pubkeyHexString;
  44. }
  45. /**
  46. * Ensures that keys are in generic api format
  47. * @function formatHexApi
  48. * @returns {string} The Ethereum key without 0x hex prefix
  49. */
  50. function formatHexApi(hexString) {
  51. // The api uses keys WITHOUT 0x prefix
  52. if (!hexString) return null;
  53. if (hexString.substring(0, 2) === ETHHEXPREFIX) {
  54. return hexString.substr(2).toLowerCase();
  55. }
  56. return hexString.toLowerCase();
  57. }
  58. /**
  59. * Ensures that addresses and keys are in Ethereum format
  60. * @function formatHexEthereum
  61. * @returns {string} The Ethereum address or key with the 0x hex prefix
  62. */
  63. function formatHexEthereum(hexString) {
  64. // Ethereum uses all hex strings WITH 0x prefix
  65. if (hexString.substring(0, 2) !== ETHHEXPREFIX) {
  66. return (ETHHEXPREFIX + hexString);
  67. }
  68. return hexString;
  69. }