Home

Awesome

<kbd><img src="images/PrincessLeiaPeachExpelsARainbowBigBang-RBT-940x198.png" /></kbd>

<br /> <hr />

BokkyPooBahs Red-Black Binary Search Tree Library

Status: Currently being tested and bug bounty open. Don't use in production without an audit, yet.

A gas-efficient Solidity library using the iterative (rather than recursive) Red-Black binary search tree algorithm to help you maintain a sorted uint key index for your data. Insertions, deletions and searches are in O(log n) time (and ~gas). Note that the key of 0 is prohibited. Use the sorted keys as indices to your mapping tables of data to access your data in sorted order.

Inserting a key into an empty tree costs 68,459 gas. Inserting a key into a tree with 9,999 keys costs 127,210 gas on average. Removing an element from a tree with a single key costs 44,835 gas. Removing a key from a tree with 10,000 keys cost 81,486 gas on average.

An important use-case for this library is to maintain a sorted on-chain order book in decentralised exchange smart contracts, providing a provably fair order matching algorithm.

Check out the online Red-black tree visualization tool- type in some 4 digit numbers and press Insert or Delete to see the insertions and rebalances animated.

See also Hitchen's Order Statistics Tree, an extension built from this library.

<br /> <hr />

Table Of Contents

<br /> <hr />

Overview

Binary Search Tree

The Red-Black Tree binary search tree is a self-rebalancing binary search tree. Following is a diagram of a fairly well-balanced binary search tree.

<kbd><img src="https://upload.wikimedia.org/wikipedia/commons/d/da/Binary_search_tree.svg" /></kbd>

The following unbalanced binary search tree was generated by inserting the numbers 1 to 32 in sequential order [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32]:

<kbd><img src="docs/RedBlackTree1To32SequentialNoRebalance.png" /></kbd>

Inserting the keys into the binary search tree in sequential order will result in this unbalanced tree resembling a linked-list.

<br />

Red-Black Binary Search Tree

The red-black algorithm maintains a red or black colouring for each node in the tree, and uses this information to maintain a reasonably balanced tree. From Wikipedia:

In addition to the requirements imposed on a binary search tree the following must be satisfied by a red–black tree:

When an element is inserted into or removed from a red-black tree, the binary search tree is rebalanced to satisfy the red-black rules.

From Wikipedia's Red-Black Tree page, the following Red-Black tree was created by inserting the items [13,8,17,11,15,22,25,27,1,6]:

<kbd><img src="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg" /></kbd>

<br />

Red-Black Tree With Random Insertion

The following fairly well-balanced red-black tree was generated by inserting the numbers 1 to 32 in random order [15,14,20,3,7,10,11,16,18,2,4,5,8,19,1,9,12,6,17,13]:

<kbd><img src="docs/RedBlackTree1To32Random.png" /></kbd>

The root node of the tree is 18, k represents the key numbers, p the parent, l the left node, r the right node. Nodes with l0 r0 are the leaves of the tree.

<br />

Red-Black Tree With Sequential Insertion

The following red-black tree was generated by inserting the numbers 1 to 32 in sequential order [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32]:

<kbd><img src="docs/RedBlackTree1To32Sequential.png" /></kbd>

A property of the red-black tree is that the path from the root to the farthest leaf is no more than twice as long as the path from the root to the nearest leaf. The shortest path has all black nodes and the longest path alternate between red and black nodes.

The shortest path is 4 levels deep: (8 black), (4 black), (2 black), (1 black).

The longest path is 8 levels deep: (8 black), (16 red), (20 black), (24 red), (28 black), (30 red), (31 black), (32 red). This is no more than twice as long as the shortest path.

<br /> <hr />

Gas Cost

Following is a chart with the minimum, average and maximum gas cost for insertions and deletions from a Red-Black Tree. The result have been generated by insering random data in the first case, and sequential data in the second case.

<kbd><img src="images/GasStatistics.png" /></kbd>

Data and chart - docs/GasStatistics.xlsx. These statistics have been generated using the test/02_test2.sh script with the results logged in test/test2results.txt - the parameters NUMBEROFITEMS, BATCHSIZE were varied for the results with different number of items, and the insertItems = shuffle(insertItems); and removeItems = shuffle(removeItems); commented out for sequential insertions.

<br />

Random Insertion Gas Cost

The following table shows the minimum, average and maximum gas cost for the insertion of items in a random order and removal of items from a red-black tree:

ItemsIns MinIns AvgIns MaxRem MinRem AvgRem Max
168,91368,91368,91344,65444,65444,654
568,91399,588140,40429,82740,89156,405
1068,913108,635141,51827,37544,88090,688
5068,913121,753182,64527,37564,977179,109
10068,913122,549186,76627,37565,447143,832
50068,913124,790191,55927,37566,629215,994
1,00068,977128,550195,71927,37567,331195,574
5,00068,977127,029200,23327,37566,966258,858
10,00068,977127,516200,90727,37566,781240,152

Note that the statistics above will change with each execution, as the data inserted is randomised.

<br />

Sequential Insertion Gas Cost

The following table shows the minimum, average and maximum gas cost for the insertion of items in a sequential order and removal of items from a red-black tree:

ItemsIns MinIns AvgIns MaxRem MinRem AvgRem Max
168,91368,91368,91344,65444,65444,654
568,913107,761141,12929,82744,88380,922
1068,913116,896149,93829,82753,457104,650
5068,913138,234158,84429,82761,485151,002
10068,913143,145163,29729,82763,540174,178
50068,913149,417191,13429,85966,239219,978
1,00068,913150,878208,36029,85966,774243,154
5,00068,913153,219242,81329,85967,276304,485
10,00068,913154,017260,04029,85967,352327,661
<br /> <hr />

History

VersionDateNotes
v0.90-pre-releaseFeb 17 2019Bug bounty added
v1.0 pre-release-aMar 8 2019Incorporated suggestions from Rob Hitchens
<br /> <hr />

Bug Bounty Scope And Donations

Details of the bug bounty program for this project can be found at BokkyPooBah's Hall Of Fame And Bug Bounties. Please consider donating to support the bug bounty, and the development and maintenance of decentralised applications.

The scope of the bug bounty for this project follows:

<br />

Bounties awarded for this project:

<br /> <hr />

Deployment

This library has been designed to be automatically compiled into your Ethereum Solidity contract or library, instead of having to deploy this library and then linking your contract or library to this library.

<br /> <hr />

Questions And Answers

What would I use this library for?

Any smart contract where you need to maintain a sorted list of unsigned integers. One major use case is for this RBT library to maintain a decentralised exchange orderbook, sorted by price.

<br />

Why does this library only store unsigned integers and not any additional data?

This library was designed to be a simple component to be used within your smart contract project.

Store any additional data, e.g., key/value pairs, by adding the functionality into your smart contract. Sample code from contracts/TestBokkyPooBahsRedBlackTree.sol follows:

contract TestBokkyPooBahsRedBlackTree {
    using BokkyPooBahsRedBlackTreeLibrary for BokkyPooBahsRedBlackTreeLibrary.Tree;

    BokkyPooBahsRedBlackTreeLibrary.Tree tree;
    mapping(uint => uint) values;

    event Log(string where, uint key, uint value);

    ...

    function getNode(uint _key) public view returns (uint key, uint parent, uint left, uint right, bool red, uint value) {
        if (tree.exists(_key)) {
            BokkyPooBahsRedBlackTreeLibrary.Node memory node = tree.getNode(_key);
            (key, parent, left, right, red) = (_key, node.parent, node.left, node.right, node.red);
            value = values[_key];
        }
    }

    function insert(uint _key, uint _value) public {
        tree.insert(_key);
        values[_key] = _value;
        emit Log("insert", _key, _value);
    }
    function remove(uint _key) public {
        tree.remove(_key);
        emit Log("remove", _key, values[_key]);
        delete values[_key];
    }
}
<br />

Why can't I use 0 as a key?

This library has been configured with the EMPTY marker set to '0'. This can be set to non-0, but you will have to add some additional functionality - you can get an idea of the functionality you will need to add back from an older untested version of the library. Search for init(...) and the last line of getNode(...). Please test carefully!

<br />

Can duplicate keys be inserted?

No

<br /> <hr />

Functions

See contracts/TestBokkyPooBahsRedBlackTree.sol (or the flattened version) for an example contract that uses this library.

Notes:

<br />

root

function root() internal view returns (uint _key);

Returns the root of the tree, or EMPTY is the tree is empty.

<br />

first

function first() internal view returns (uint _key);

Returns the smallest key in the tree.

Return ValueCondition
{first key}Tree has at least one key
EMPTYTree empty
<br />

last

function last() internal view returns (uint _key);

Returns the largest key in the tree.

Return ValueCondition
{last key}Tree has at least one key
EMPTYTree empty
<br />

next

function next(uint x) internal view returns (uint y);

Returns the next key in the tree with a value larger than x.

Return ValueCondition
{next key}There exists a key with a value larger than the x key
EMPTYTree empty
EMPTYx is not an existing key in the tree
EMPTYx is the only key in the tree
EMPTYx is the last key in the tree
<br />

prev

function prev(uint x) internal view returns (uint y);

Returns the previous key in the tree with a value smaller than x.

Return ValueCondition
{prev key}There exists a key with a value smaller than the x key
EMPTYTree empty
EMPTYx is not an existing key in the tree
EMPTYx is the only element in the tree
EMPTYx is the last element in the tree
<br />

exists

function exists(uint key) internal view returns (bool _exists);

Returns true if the key exists in the tree, false otherwise.

Return ValueCondition
truekey is an existing key in the tree
falseTree empty
falsekey is not an existing key in the tree
<br />

isEmpty

function isEmpty(uint key) internal pure returns (bool);

Returns true if the key exists in the tree, false otherwise.

Return ValueCondition
truekey is an existing key in the tree
falseTree empty
falsekey is not an existing key in the tree
<br />

getEmpty

function getEmpty() internal pure returns (uint);

Returns the value of the EMPTY variable

<br />

getNode

function getNode(uint key) internal view returns (uint _returnKey, uint _parent, uint _left, uint _right, bool _red);

Returns the node information if key exists in the tree. All uint values will be set to EMPTY if key does not exist in the tree.

<br />

insert

function insert(uint key) internal;

Insert the key key into the tree.

TransactionCondition
successkey has been successfully inserted into the tree
failurekey already exists in the tree
<br />

remove

function remove(uint key) internal;

Remove the key key from the tree.

TransactionCondition
successkey has been successfully removed from the tree
failurekey does not exist in the tree
<br /> <hr />

Algorithm

The main Red-Black binary search tree algorithm is listed in Algorithms for Red Black Tree Operations (from CLRS text).

Note that this algorithm is designed to work with memory pointers to the node data. The rebalancing process after the removal of an item from the tree may result in a swapping of data values between nodes.

As the nodes are stored as elements in a Solidity mapping data structure, Iterative Algorithm for Red-Black Tree provides an alternative algorithm to perform this swapping. In particular, the function RB-Delete in the main Red-Black algorithm will need the line then key[z] := key[y] replaced with the alternative swapping algorithm.

<br /> <hr />

Testing

<br /> <hr />

References

<br /> <br />

Thanks to James Zaki and Solidified for the 3 minor issues they picked up at the Web3 Summit.

And thanks to Rob Hitchens for the suggestions.

Enjoy!

(c) BokkyPooBah / Bok Consulting Pty Ltd - Jan 18 2020. The MIT Licence.