@@ -12,12 +12,12 @@ library RNG {
1212 // How many bits a position uses per level of the tree;
1313 // each branch of the tree contains 2**SLOT_BITS slots.
1414 uint256 constant SLOT_BITS = 3 ;
15- uint256 constant LEVELS = 7 ;
1615 ////////////////////////////////////////////////////////////////////////////
1716
1817 ////////////////////////////////////////////////////////////////////////////
1918 // Derived constants, do not touch
20- uint256 constant POSITION_BITS = LEVELS * SLOT_BITS;
19+ uint256 constant SLOT_COUNT = 2 ** SLOT_BITS;
20+ uint256 constant WEIGHT_WIDTH = 256 / SLOT_COUNT;
2121 ////////////////////////////////////////////////////////////////////////////
2222
2323 struct State {
@@ -127,30 +127,26 @@ library RNG {
127127 /// @notice Calculate how many bits are required
128128 /// for an index in the range `[0 .. range-1]`.
129129 ///
130- /// @dev Our sortition pool can support up to 2^21 virtual stakers,
131- /// therefore we calculate how many bits we need from 1 to 21.
132- ///
133130 /// @param range The upper bound of the desired range, exclusive.
134131 ///
135132 /// @return uint The smallest number of bits
136133 /// that can contain the number `range-1`.
137134 function bitsRequired (uint256 range ) internal pure returns (uint256 ) {
138- uint256 bits;
139- // Start at 19 to be faster for large ranges
140- for (bits = (POSITION_BITS - 1 ); bits >= 0 ; bits-- ) {
141- // Left shift by `bits`,
142- // so we have a 1 in the (bits + 1)th least significant bit
143- // and 0 in other bits.
144- // If this number is equal or greater than `range`,
145- // the range [0, range-1] fits in `bits` bits.
146- //
147- // Because we loop from high bits to low bits,
148- // we find the highest number of bits that doesn't fit the range,
149- // and return that number + 1.
150- if (1 << bits < range) {
151- break ;
152- }
135+ uint256 bits = WEIGHT_WIDTH - 1 ;
136+
137+ // Left shift by `bits`,
138+ // so we have a 1 in the (bits + 1)th least significant bit
139+ // and 0 in other bits.
140+ // If this number is equal or greater than `range`,
141+ // the range [0, range-1] fits in `bits` bits.
142+ //
143+ // Because we loop from high bits to low bits,
144+ // we find the highest number of bits that doesn't fit the range,
145+ // and return that number + 1.
146+ while (1 << bits >= range) {
147+ bits-- ;
153148 }
149+
154150 return bits + 1 ;
155151 }
156152
@@ -197,7 +193,7 @@ library RNG {
197193 {
198194 uint256 bits = bitsRequired (range);
199195 bool found = false ;
200- uint256 index;
196+ uint256 index = 0 ;
201197 bytes32 newState = state;
202198 while (! found) {
203199 index = truncate (bits, uint256 (newState));
0 commit comments