rlp-encode.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //See: https://github.com/ethereum/wiki/wiki/RLP
  2. import { getBytes } from "./data.js";
  3. import type { RlpStructuredDataish } from "./rlp.js";
  4. function arrayifyInteger(value: number): Array<number> {
  5. const result: Array<number> = [];
  6. while (value) {
  7. result.unshift(value & 0xff);
  8. value >>= 8;
  9. }
  10. return result;
  11. }
  12. function _encode(object: Array<any> | string | Uint8Array): Array<number> {
  13. if (Array.isArray(object)) {
  14. let payload: Array<number> = [];
  15. object.forEach(function(child) {
  16. payload = payload.concat(_encode(child));
  17. });
  18. if (payload.length <= 55) {
  19. payload.unshift(0xc0 + payload.length)
  20. return payload;
  21. }
  22. const length = arrayifyInteger(payload.length);
  23. length.unshift(0xf7 + length.length);
  24. return length.concat(payload);
  25. }
  26. const data: Array<number> = Array.prototype.slice.call(getBytes(object, "object"));
  27. if (data.length === 1 && data[0] <= 0x7f) {
  28. return data;
  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: RlpStructuredDataish): string {
  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. }