rlp-encode.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. //See: https://github.com/ethereum/wiki/wiki/RLP
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.encodeRlp = void 0;
  5. const data_js_1 = require("./data.js");
  6. function arrayifyInteger(value) {
  7. const result = [];
  8. while (value) {
  9. result.unshift(value & 0xff);
  10. value >>= 8;
  11. }
  12. return result;
  13. }
  14. function _encode(object) {
  15. if (Array.isArray(object)) {
  16. let payload = [];
  17. object.forEach(function (child) {
  18. payload = payload.concat(_encode(child));
  19. });
  20. if (payload.length <= 55) {
  21. payload.unshift(0xc0 + payload.length);
  22. return payload;
  23. }
  24. const length = arrayifyInteger(payload.length);
  25. length.unshift(0xf7 + length.length);
  26. return length.concat(payload);
  27. }
  28. const data = Array.prototype.slice.call((0, data_js_1.getBytes)(object, "object"));
  29. if (data.length === 1 && data[0] <= 0x7f) {
  30. return data;
  31. }
  32. else if (data.length <= 55) {
  33. data.unshift(0x80 + data.length);
  34. return data;
  35. }
  36. const length = arrayifyInteger(data.length);
  37. length.unshift(0xb7 + length.length);
  38. return length.concat(data);
  39. }
  40. const nibbles = "0123456789abcdef";
  41. /**
  42. * Encodes %%object%% as an RLP-encoded [[DataHexString]].
  43. */
  44. function encodeRlp(object) {
  45. let result = "0x";
  46. for (const v of _encode(object)) {
  47. result += nibbles[v >> 4];
  48. result += nibbles[v & 0xf];
  49. }
  50. return result;
  51. }
  52. exports.encodeRlp = encodeRlp;
  53. //# sourceMappingURL=rlp-encode.js.map