rlp-encode.js 1.4 KB

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