3

I am always curious what the documentation for the storage means when I see the following.

Enumerate all elements in the map in no particular order.

https://paritytech.github.io/substrate/master/frame_support/pallet_prelude/struct.StorageMap.html#method.iter

I assume that I can't expect a true random order here. This would simplify my use-case, but it is too good to be true.

So what is the underlying order here?

What is the best way to get n elements out of a storage map in a random order?

1 Answer 1

3

Not random.

The keys used in the merkle trie result from hashing with https://paritytech.github.io/substrate/master/frame_support/trait.StorageHasher.html.

So the iteration order is deterministic (just tree iteration), in the order of hashed keys.

2
  • Ok thanks, have you an idea how to select keys randomly out of a StorageMap?
    – Chralt
    Feb 2 at 14:05
  • 1
    given hash of key should be rather evenly distributed over the 32 byte of the hash used internally by the map (unless some key where target of hash collision which is often a possibility), then just get a random hash and use the next value using storage next_key host function. But the big question is how to get this random hash (especially onchain random: most way to get some random data from a runtime are seen as unsecure, usually stuff as use the hash of past block infos (I remember discussion about some design that could help, but not really sure it is doable yet).
    – cheme
    Feb 3 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.