cbor-x icon indicating copy to clipboard operation
cbor-x copied to clipboard

Sort record keys

Open atomictag opened this issue 2 years ago • 2 comments

Currently

    const obj1 = { a: "A", b: "B", c: "C" };
    const obj2 = { c: "C", b: "B", a: "A" };

serialize to different CBOR bytes because keys are sorted differently (although the objects are deep-equal).

I'm not sure what the specs say in this regard, but it would be very useful to have the possibility (perhaps via an option flag) to get record keys sorted lexicographically so that equal objects would produce the same octet stream. This could be useful in a number of contexts - e.g. signatures, hashing...

It could be something as trivial as

Object.keys(record)
.sort()
.reduce((obj, key) => {
   obj[key] = record[key];
   return obj;
 }, {});

atomictag avatar Oct 14 '22 22:10 atomictag

Do you think it would work just as well to do this lexicographic sorting before submitting the object(s) to cbor-x?

kriszyp avatar Oct 16 '22 03:10 kriszyp

Do you think it would work just as well to do this lexicographic sorting before submitting the object(s) to cbor-x?

That's actually what I am currently doing and it works well. The order of JavaScript properties is guaranteed to be preserved since (I believe) ES2015. However this is more a food-for-thoughts and a nice-to-have than an issue with cbor-x per-se - it would just be handy if serialized records followed some key-sorting rule in order to make the CBOR output deterministic given an equal set of record inputs where the order of keys may be different.

atomictag avatar Oct 16 '22 13:10 atomictag