Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2011 The LevelDB Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file. See the AUTHORS file for names of contributors.5#ifndef STORAGE_LEVELDB_DB_SKIPLIST_H_6#define STORAGE_LEVELDB_DB_SKIPLIST_H_8// Thread safety9// -------------10//11// Writes require external synchronization, most likely a mutex.12// Reads require a guarantee that the SkipList will not be destroyed13// while the read is in progress. Apart from that, reads progress14// without any internal locking or synchronization.15//16// Invariants:17//18// (1) Allocated nodes are never deleted until the SkipList is19// destroyed. This is trivially guaranteed by the code since we20// never delete any skip list nodes.21//22// (2) The contents of a Node except for the next/prev pointers are23// immutable after the Node has been linked into the SkipList.24// Only Insert() modifies the list, and it is careful to initialize25// a node and use release-stores to publish the nodes in one or26// more lists.27//28// ... prev vs. next pointer ordering ...30#include <atomic>31#include <cassert>32#include <cstdlib>34#include "util/arena.h"35#include "util/random.h"37namespace leveldb {39class Arena;41template <typename Key, class Comparator>42class SkipList {43private:44struct Node;46public:47// Create a new SkipList object that will use "cmp" for comparing keys,48// and will allocate memory using "*arena". Objects allocated in the arena49// must remain allocated for the lifetime of the skiplist object.50explicit SkipList(Comparator cmp, Arena* arena);52SkipList(const SkipList&) = delete;53SkipList& operator=(const SkipList&) = delete;55// Insert key into the list.56// REQUIRES: nothing that compares equal to key is currently in the list.57void Insert(const Key& key);59// Returns true iff an entry that compares equal to key is in the list.60bool Contains(const Key& key) const;62// Iteration over the contents of a skip list63class Iterator {64public:65// Initialize an iterator over the specified list.66// The returned iterator is not valid.67explicit Iterator(const SkipList* list);69// Returns true iff the iterator is positioned at a valid node.70bool Valid() const;72// Returns the key at the current position.73// REQUIRES: Valid()74const Key& key() const;76// Advances to the next position.77// REQUIRES: Valid()78void Next();80// Advances to the previous position.81// REQUIRES: Valid()82void Prev();84// Advance to the first entry with a key >= target85void Seek(const Key& target);87// Position at the first entry in list.88// Final state of iterator is Valid() iff list is not empty.89void SeekToFirst();91// Position at the last entry in list.92// Final state of iterator is Valid() iff list is not empty.93void SeekToLast();95private:96const SkipList* list_;97Node* node_;98// Intentionally copyable99};101private:102enum { kMaxHeight = 12 };104inline int GetMaxHeight() const {105return max_height_.load(std::memory_order_relaxed);106}108Node* NewNode(const Key& key, int height);109int RandomHeight();110bool Equal(const Key& a, const Key& b) const { return (compare_(a, b) == 0); }112// Return true if key is greater than the data stored in "n"113bool KeyIsAfterNode(const Key& key, Node* n) const;115// Return the earliest node that comes at or after key.116// Return nullptr if there is no such node.117//118// If prev is non-null, fills prev[level] with pointer to previous119// node at "level" for every level in [0..max_height_-1].120Node* FindGreaterOrEqual(const Key& key, Node** prev) const;122// Return the latest node with a key < key.123// Return head_ if there is no such node.124Node* FindLessThan(const Key& key) const;126// Return the last node in the list.127// Return head_ if list is empty.128Node* FindLast() const;130// Immutable after construction131Comparator const compare_;132Arena* const arena_; // Arena used for allocations of nodes134Node* const head_;136// Modified only by Insert(). Read racily by readers, but stale137// values are ok.138std::atomic<int> max_height_; // Height of the entire list140// Read/written only by Insert().141Random rnd_;142};144// Implementation details follow145template <typename Key, class Comparator>146struct SkipList<Key, Comparator>::Node {147explicit Node(const Key& k) : key(k) {}149Key const key;151// Accessors/mutators for links. Wrapped in methods so we can152// add the appropriate barriers as necessary.153Node* Next(int n) {154assert(n >= 0);155// Use an 'acquire load' so that we observe a fully initialized156// version of the returned Node.157return next_[n].load(std::memory_order_acquire);158}159void SetNext(int n, Node* x) {160assert(n >= 0);161// Use a 'release store' so that anybody who reads through this162// pointer observes a fully initialized version of the inserted node.163next_[n].store(x, std::memory_order_release);164}166// No-barrier variants that can be safely used in a few locations.167Node* NoBarrier_Next(int n) {168assert(n >= 0);169return next_[n].load(std::memory_order_relaxed);170}171void NoBarrier_SetNext(int n, Node* x) {172assert(n >= 0);173next_[n].store(x, std::memory_order_relaxed);174}176private:177// Array of length equal to the node height. next_[0] is lowest level link.178std::atomic<Node*> next_[1];179};181template <typename Key, class Comparator>182typename SkipList<Key, Comparator>::Node* SkipList<Key, Comparator>::NewNode(183const Key& key, int height) {184char* const node_memory = arena_->AllocateAligned(185sizeof(Node) + sizeof(std::atomic<Node*>) * (height - 1));186return new (node_memory) Node(key);187}189template <typename Key, class Comparator>190inline SkipList<Key, Comparator>::Iterator::Iterator(const SkipList* list) {191list_ = list;192node_ = nullptr;193}195template <typename Key, class Comparator>196inline bool SkipList<Key, Comparator>::Iterator::Valid() const {197return node_ != nullptr;198}200template <typename Key, class Comparator>201inline const Key& SkipList<Key, Comparator>::Iterator::key() const {202assert(Valid());203return node_->key;204}206template <typename Key, class Comparator>207inline void SkipList<Key, Comparator>::Iterator::Next() {208assert(Valid());209node_ = node_->Next(0);210}212template <typename Key, class Comparator>213inline void SkipList<Key, Comparator>::Iterator::Prev() {214// Instead of using explicit "prev" links, we just search for the215// last node that falls before key.216assert(Valid());217node_ = list_->FindLessThan(node_->key);218if (node_ == list_->head_) {219node_ = nullptr;220}221}223template <typename Key, class Comparator>224inline void SkipList<Key, Comparator>::Iterator::Seek(const Key& target) {225node_ = list_->FindGreaterOrEqual(target, nullptr);226}228template <typename Key, class Comparator>229inline void SkipList<Key, Comparator>::Iterator::SeekToFirst() {230node_ = list_->head_->Next(0);231}233template <typename Key, class Comparator>234inline void SkipList<Key, Comparator>::Iterator::SeekToLast() {235node_ = list_->FindLast();236if (node_ == list_->head_) {237node_ = nullptr;238}239}241template <typename Key, class Comparator>242int SkipList<Key, Comparator>::RandomHeight() {243// Increase height with probability 1 in kBranching244static const unsigned int kBranching = 4;245int height = 1;246while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) {247height++;248}249assert(height > 0);250assert(height <= kMaxHeight);
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.