diff --git a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/ChangeLog.md b/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/ChangeLog.md deleted file mode 100644 index a1b8321df..000000000 --- a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/ChangeLog.md +++ /dev/null @@ -1,1577 +0,0 @@ -ChangeLog ---------- - -English version [by Google](https://gitflic-ru.translate.goog/project/erthink/libmdbx/blob?file=ChangeLog.md&_x_tr_sl=ru&_x_tr_tl=en) -and [by Yandex](https://translated.turbopages.org/proxy_u/ru-en.en/https/gitflic.ru/project/erthink/libmdbx/blob?file=ChangeLog.md). - - -## v0.12.6 "ЦСКА" от 2023-04-29 - -Стабилизирующий выпуск с исправлением обнаруженных ошибок и устранением -недочетов, в день 100-летнего юбилея спортивного клуба [«ЦСКА»](https://ru.wikipedia.org/wiki/Центральный_спортивный_клуб_Армии). - -``` -14 files changed, 117 insertions(+), 83 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Мелочи: - - - Обновление патча для старых версий buildroot. - - Использование clang-format-16. - - Использование `enum`-типов вместо `int` для устранения предупреждений GCC 13, - что могло ломать сборку в Fedora 38. - - --------------------------------------------------------------------------------- - - -## v0.12.5 "Динамо" от 2023-04-18 - -Стабилизирующий выпуск с исправлением обнаруженных ошибок и устранением -недочетов, в день 100-летнего юбилея спортивного общества [«Динамо»](https://ru.wikipedia.org/wiki/Динамо_(спортивное_общество)). - -``` -16 files changed, 686 insertions(+), 247 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Благодарности: - - - Max за сообщение о проблеме экспорта из DSO/DLL - устаревших функций API. - - [`@calvin3721`](https://t.me/calvin3721) за сообщение о проблеме работы - `MainDB` с флагами не по-умолчанию. - -Исправления: - - - Поправлен экспорт из DSO/DLL устаревших функций, - которые заменены на inline в текущем API. - - Устранено использование неверного компаратора при создании или пересоздании - `MainDB` с флагами/опциями предполагающим использование специфического - компаратора (не по-умолчанию). - -Мелочи: - - - Удалена дублирующая диагностика внутри `node_read_bigdata()`. - - Исправлены ссылки в описании `mdbx_env_set_geometry()`. - - Добавлен отдельный тест `extra/upsert_alldups` для специфического - сценария замены/перезаписи одним значением всех multi-значений - соответствующих ключу, т.е. замена всех «дубликатов» одним значением. - - В C++ API добавлены варианты `buffer::key_from()` с явным именованием по типу данных. - - Добавлен отдельный тест `extra/maindb_ordinal` для специфического - сценария создания `MainDB` с флагами требующими использования - компаратора не по-умолчанию. - - Рефакторинг проверки "когерентности" мета-страниц. - - Корректировка `osal_vasprintf()` для устранения предупреждений статических анализаторов. - - --------------------------------------------------------------------------------- - - -## v0.12.4 "Арта-333" от 2023-03-03 - -Стабилизирующий выпуск с исправлением обнаруженных ошибок, устранением -недочетов и технических долгов. Ветка 0.12 считается готовой к -продуктовому использованию, получает статус стабильной и далее будет -получать только исправление ошибок. Разработка будет продолжена в ветке -0.13, а ветка 0.11 становится архивной. - -``` -63 files changed, 1161 insertions(+), 569 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Благодарности: - - - Max за сообщение о проблеме ERROR_SHARING_VIOLATION - в режиме MDBX_EXCLUSIVE на Windows. - - Alisher Ashyrov за сообщение о проблеме - с assert-проверкой и содействие в отладке. - - Masatoshi Fukunaga за сообщение о проблеме - `put(MDBX_UPSERT+MDBX_ALLDUPS)` для случая замены всех значений в subDb. - -Исправления: - - - Устранен регресс после коммита 474391c83c5f81def6fdf3b0b6f5716a87b78fbf, - приводящий к возврату ERROR_SHARING_VIOLATION в Windows при открытии БД - в режиме MDBX_EXCLUSIVE для чтения-записи. - - - Добавлено ограничение размера отображения при коротком read-only файле, для - предотвращения ошибки ERROR_NOT_ENOUGH_MEMORY в Windows, которая возникает - в этом случае и совсем не информативна для пользователя. - - - Произведен рефакторинг `dxb_resize()`, в том числе, для устранения срабатывания - assert-проверки `size_bytes == env->me_dxb_mmap.current` в специфических - многопоточных сценариях использования. Проверка срабатывала только в - отладочных сборках, при специфическом наложении во времени читающей и - пишущей транзакции в разных потоках, одновременно с изменением размера БД. - Кроме срабатывание проверки, каких-либо других последствий не возникало. - - - Устранена проблема в `put(MDBX_UPSERT+MDBX_ALLDUPS)` для случая замены - всех значений единственного ключа в subDb. В ходе этой операции subDb - становится полностью пустой, без каких-либо страниц и именно эта - ситуация не была учтена в коде, что приводило к повреждению БД - при фиксации такой транзакции. - - - Устранена излишняя assert-проверка внутри `override_meta()`. - Что в отладочных сборках могло приводить к ложным срабатываниям - при восстановлении БД, в том числе при автоматическом откате слабых - мета-страниц. - - - Скорректированы макросы `__cold`/`__hot`, в том числе для устранения проблемы - `error: inlining failed in call to ‘always_inline FOO(...)’: target specific option mismatch` - при сборке посредством GCC >10.x для SH4. - -Ликвидация технических долгов и мелочи: - - - Исправлены многочисленные опечатки в документации. - - Доработан тест для полной стохастической проверки `MDBX_EKEYMISMATCH` в режиме `MDBX_APPEND`. - - Расширены сценарии запуска `mdbx_chk` из CMake-тестов для проверки как в обычном, - так и эксклюзивном режимах чтения-записи. - - Уточнены спецификаторы `const` и `noexcept` для нескольких методов в C++ API. - - Устранено использование стека под буферы для `wchar`-преобразования путей. - - Для Windows добавлена функция `mdbx_env_get_path()` для получения пути к БД - в формате многобайтных символов. - - Добавлены doxygen-описания для API с широкими символами. - - Устранены предупреждения статического анализатора MSVC, - все они были несущественные, либо ложные. - - Устранено ложное предупреждение GCC при сборке для SH4. - - Добавлена поддержка ASAN (Address Sanitizer) при сборке посредством MSVC. - - Расширен набор перебираемых режимов в скрипте `test/long_stochastic.sh`, - добавлена опция `--extra`. - - В C++ API добавлена поддержка расширенных опций времени выполнения `mdbx::extra_runtime_option`, - аналогично `enum MDBX_option_t` из C API. - - Вывод всех счетчиков page-operations в `mdbx_stat`. - - --------------------------------------------------------------------------------- - - -## v0.12.3 "Акула" от 2023-01-07 - -Выпуск с существенными доработками и новой функциональностью в память о закрытом open-source -[проекте "Акула"](https://erigon.substack.com/p/winding-down-support-for-akula-project). - -Добавлена prefault-запись, переделан контроль “некогерентности” unified page/buffer cache, изменена тактика слияния страниц и т.д. -Стало ещё быстрее, в некоторых сценариях вдвое. - -``` -20 files changed, 4508 insertions(+), 2928 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Благодарности: - - - [Alex Sharov](https://t.me/AskAlexSharov) и команде [Erigon](https://github.com/ledgerwatch/erigon) за тестирование. - - [Simon Leier](https://t.me/leisim) за сообщение о сбоях и тестирование. - -Новое: - - - Использование адреса [https://libmdbx.dqdkfa.ru/dead-github](https://libmdbx.dqdkfa.ru/dead-github) - для отсылки к сохранённым в web.archive.org копиям ресурсов, уничтоженных администрацией Github. - - - Реализована prefault-запись при выделении страниц для read-write отображений. - Это приводит к кратному снижению системных издержек и существенному увеличению - производительности в соответствующих сценариях использования, когда: - - размер БД и объём данных существенно больше ОЗУ; - - используется режим `MDBX_WRITEMAP`; - - не-мелкие транзакции (по ходу транзакции выделяется многие сотни или тысячи страниц). - - В режиме `MDBX_WRITEMAP` выделение/переиспользование страниц приводит - к page-fault и чтению страницы с диска, даже если содержимое страницы - не нужно (будет перезаписано). Это является следствием работы подсистемы - виртуальной памяти, а штатный способ лечения через `MADV_REMOVE` - работает не на всех ФС и обычно дороже получаемой экономии. - - Теперь в libmdbx используется "упреждающая запись" таких страниц, - которая на системах с [unified page cache](https://www.opennet.ru/base/dev/ubc.txt.html) - приводит к "вталкиванию" данных, устраняя необходимость чтения с диска при - обращении к такой странице памяти. - - Новый функционал работает в согласованности с автоматическим управлением read-ahead - и кэшем статуса присутствия страниц в ОЗУ, посредством [mincore()](https://man7.org/linux/man-pages/man2/mincore.2.html). - - - Добавлена опция `MDBX_opt_prefault_write_enable` для возможности принудительного - включения/выключения prefault-записи. - - - Реализован динамический выбор между сквозной записью на диск и обычной записью - с последующим [fdatasync()](https://man7.org/linux/man-pages/man3/fdatasync.3p.html) - управляемый опцией `MDBX_opt_writethrough_threshold`. - - В долговечных (durable) режимах данные на диск могут быть сброшены двумя способами: - - сквозной записью через файловый дескриптор открытый с `O_DSYNC`; - - обычной записью с последующим вызовом `fdatasync()`. - - Первый способ выгоднее при записи малого количества страниц и/или если - канал взаимодействия с диском/носителем имеет близкую к нулю задержку. - Второй способ выгоднее если требуется записать много страниц и/или канал - взаимодействия имеет весомую задержку (датацентры, облака). Добавленная - опция `MDBX_opt_writethrough_threshold` позволяет во время выполнения - задать порог для динамического выбора способа записи в зависимости от - объема и конкретных условия использования. - - - Автоматическая установка `MDBX_opt_rp_augment_limit` в зависимости от размера БД. - - - Запрещение разного режима `MDBX_WRITEMAP` между процессами в режимах - с отложенной/ленивой записью, так как в этом случае невозможно - обеспечить сброс данных на диск во всех случаях на всех поддерживаемых платформах. - - - Добавлена опция сборки `MDBX_MMAP_USE_MS_ASYNC` позволяющая отключить - использование системного вызова `msync(MS_ASYNC)`, в использовании - которого нет необходимости на подавляющем большинстве актуальных ОС. - По-умолчанию `MDBX_MMAP_USE_MS_ASYNC=0` (выключено) на Linux и других - системах с unified page cache. Такое поведение (без использования - `msync(MS_ASYNC)`) соответствует неизменяемой (hardcoded) логике LMDB. В - результате, в простых/наивных бенчмарках, libmdbx опережает LMDB - примерно также как при реальном применении. - - На всякий случай стоит еще раз отметить/напомнить, что на Windows - предположительно libmdbx будет отставать от LMDB в сценариях с - множеством мелких транзакций, так как libmdbx осознанно использует на - Windows файловые блокировки, которые медленные (плохо реализованы в ядре - ОС), но позволяют застраховать пользователей от массы неверных действий - приводящих к повреждению БД. - - - Поддержка не-печатных имен для subDb. - - - Добавлен явный выбор `tls_model("local-dynamic")` для обхода проблемы - `relocation R_X86_64_TPOFF32 against FOO cannot be used with -shared` - из-за ошибки в CLANG приводящей к использованию неверного режима `ls_model`. - - - Изменение тактики слияния страниц при удалении. - Теперь слияние выполняется преимущественно с уже измененной/грязной страницей. - Если же справа и слева обе страницы с одинаковым статусом, - то с наименее заполненной, как прежде. В сценариях с массивным удалением - это позволяет увеличить производительность до 50%. - - - Добавлен контроль отсутствия LCK-файлов с альтернативным именованием. - -Исправления (без корректировок новых функций): - - - Изменение размера отображения если это требуется для сброса данных на - диск при вызове `mdbx_env_sync()` из параллельного потока выполнения вне - работающей транзакции. - - - Исправление регресса после коммита db72763de049d6e4546f838277fe83b9081ad1de от 2022-10-08 - в логике возврата грязных страниц в режиме `MDBX_WRITEMAP`, из-за чего - освободившиеся страницы использовались не немедленно, а попадали в - retired-список совершаемой транзакции и происходил необоснованный рост - размера транзакции. - - - Устранение SIGSEGV или ошибочного вызова `free()` в ситуациях - повторного открытия среды посредством `mdbx_env_open()`. - - - Устранение ошибки совершенной в коммите fe20de136c22ed3bc4c6d3f673e79c106e824f60 от 2022-09-18, - в результате чего на Linux в режиме `MDBX_WRITEMAP` никогда не вызывался `msync()`. - Проблема существует только в релизе 0.12.2. - - - Добавление подсчета грязных страниц в `MDBX_WRITEMAP` для предоставления посредством `mdbx_txn_info()` - актуальной информации об объеме изменений в процессе транзакций чтения-записи. - - - Исправление несущественной опечатки в условиях `#if` определения порядка байт. - - - Исправление сборки для случая `MDBX_PNL_ASCENDING=1`. - -Ликвидация технических долгов и мелочи: - - - Доработка поддержки авто-слияния записей GC внутри `page_alloc_slowpath()`. - - Устранение несущественных предупреждений Coverity. - - Использование единого курсора для поиска в GC. - - Переработка внутренних флагов связанных с выделением страниц из GC. - - Доработка подготовки резерва перед обновлением GC при включенном BigFoot. - - Оптимизация `pnl_merge()` для случаев неперекрывающихся объединяемых списков. - - Оптимизация поддержки отсортированного списка страниц в `dpl_append()`. - - Ускорение работы `mdbx_chk` при обработке пользовательских записей в `@MAIN`. - - Переработка LRU-отметок для спиллинга. - - Переработка контроля "некогерентности" Unified page cache для уменьшения накладных расходов. - - Рефакторинг и микрооптимизация. - - --------------------------------------------------------------------------------- - - -## v0.12.2 "Иван Ярыгин" от 2022-11-11 - -Выпуск с существенными доработками и новой функциональностью -в память о российском борце [Иване Сергеевиче Ярыгине](https://ru.wikipedia.org/wiki/Ярыгин,_Иван_Сергеевич). - -На Олимпийских играх в Мюнхене в 1972 году Иван Ярыгин уложил всех соперников на лопатки, -суммарно затратив менее 9 минут. Этот рекорд никем не побит до сих пор. - -``` -64 files changed, 5573 insertions(+), 2510 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Новое: - - - Поддержка всех основных опций при сборке посредством CMake. - - - Требования к CMake понижены до версии 3.0.2 для возможности сборки для устаревших платформ. - - - Добавлена возможность профилирования работы GC в сложных и/или нагруженных - сценариях (например Ethereum/Erigon). По-умолчанию соответствующий код отключен, - а для его активации необходимо указать опцию сборки `MDBX_ENABLE_PROFGC=1`. - - - Добавлена функция `mdbx_env_warmup()` для "прогрева" БД с возможностью - закрепления страниц в памяти. - В утилиты `mdbx_chk`, `mdbx_copy` и `mdbx_dump` добавлены опции `-u` и `-U` - для активации соответствующего функционала. - - - Отключение учета «грязных» страниц в не требующих этого режимах - (`MDBX_WRITEMAP` при `MDBX_AVOID_MSYNC=0`). Доработка позволяет снизить - накладные расходы и была запланирована давно, но откладывалась так как - требовала других изменений. - - - Вытеснение из памяти (спиллинг) «грязных» страниц с учетом размера - large/overflow-страниц. Доработка позволяет корректно соблюдать политику - задаваемую опциями `MDBX_opt_txn_dp_limit`, - `MDBX_opt_spill_max_denominator`, `MDBX_opt_spill_min_denominator` и - была запланирована давно, но откладывалась так как требовала других - изменений. - - - Для Windows в API добавлены UNICODE-зависимые определения макросов - `MDBX_DATANAME`, `MDBX_LOCKNAME` и `MDBX_LOCK_SUFFIX`. - - - Переход на преимущественное использование типа `size_t` для - уменьшения накладных расходов на платформе Эльбрус. - - - В API добавлены функции `mdbx_limits_valsize4page_max()` и - `mdbx_env_get_valsize4page_max()` возвращающие максимальный размер в - байтах значения, которое может быть размещена в одной - large/overflow-странице, а не последовательности из двух или более таких - страниц. Для таблиц с поддержкой дубликатов вынос значений на - large/overflow-страницы не поддерживается, поэтому результат совпадает с - `mdbx_limits_valsize_max()`. - - - В API добавлены функции `mdbx_limits_pairsize4page_max()`и - `mdbx_env_get_pairsize4page_max()` возвращающие в байтах максимальный - суммарный размер пары ключ-значение для их размещения на одной листовой - страницы, без выноса значения на отдельную large/overflow-страницу. Для - таблиц с поддержкой дубликатов вынос значений на large/overflow-страницы - не поддерживается, поэтому результат определяет максимальный/допустимый - суммарный размер пары ключ-значение. - - - Реализовано использование асинхронной (overlapped) записи в Windows, - включая использования небуфферизированного ввода-вывода и `WriteGather()`. - Это позволяет сократить накладные расходы и частично обойти проблемы - Windows с низкой производительностью ввода-вывода, включая большие - задержки `FlushFileBuffers()`. Новый код также обеспечивает консолидацию - записываемых регионов на всех платформах, а на Windows использование - событий (events) сведено к минимум, одновременно с автоматических - использованием `WriteGather()`. Поэтому ожидается существенное снижение - накладных расходов взаимодействия с ОС, а в Windows это ускорение, в - некоторых сценариях, может быть кратным в сравнении с LMDB. - - - Добавлена опция сборки `MDBX_AVOID_MSYNC`, которая определяет - поведение libmdbx в режиме `MDBX_WRITE_MAP` (когда данные изменяются - непосредственно в отображенных в ОЗУ страницах БД): - - * Если `MDBX_AVOID_MSYNC=0` (по умолчанию на всех системах кроме Windows), - то (как прежде) сохранение данных выполняется посредством `msync()`, - либо `FlushViewOfFile()` на Windows. На платформах с полноценной - подсистемой виртуальной памяти и адекватным файловым вводом-выводом - это обеспечивает минимум накладных расходов (один системный вызов) - и максимальную производительность. Однако, на Windows приводит - к значительной деградации, в том числе из-за того что после - `FlushViewOfFile()` требуется также вызов `FlushFileBuffers()` - с массой проблем и суеты внутри ядра ОС. - - * Если `MDBX_AVOID_MSYNC=1` (по умолчанию только на Windows), то - сохранение данных выполняется явной записью в файл каждой измененной - страницы БД. Это требует дополнительных накладных расходов, как - на отслеживание измененных страниц (ведение списков "грязных" - страниц), так и на системные вызовы для их записи. - Кроме этого, с точки зрения подсистемы виртуальной памяти ядра ОС, - страницы БД измененные в ОЗУ и явно записанные в файл, могут либо - оставаться "грязными" и быть повторно записаны ядром ОС позже, - либо требовать дополнительных накладных расходов для отслеживания - PTE (Page Table Entries), их модификации и дополнительного копирования - данных. Тем не менее, по имеющейся информации, на Windows такой путь - записи данных в целом обеспечивает более высокую производительность. - - - Улучшение эвристики включения авто-слияния записей GC. - - - Изменение формата LCK и семантики некоторых внутренних полей. Версии - libmdbx использующие разный формат не смогут работать с одной БД - одновременно, а только поочередно (LCK-файл переписывается при открытии - первым открывающим БД процессом). - - - В `C++` API добавлены методы фиксации транзакции с получением информации - о задержках. - - - Added `MDBX_HAVE_BUILT IN_CPU_SUPPORTS` build option to control use GCC's - `__builtin_cpu_supports()` function, which could be unavailable on a fake - OSes (macos, ios, android, etc). - -Исправления (без корректировок вышеперечисленных новых функций): - - - Устранения ряда предупреждений при сборке посредством MinGW. - - Устранение ложно-положительных сообщений от Valgrind об использовании - не инициализированных данных из-за выравнивающих зазоров в `struct troika`. - - Исправлен возврат неожиданной ошибки `MDBX_BUSY` из функций `mdbx_env_set_option()`, - `mdbx_env_set_syncbytes()` и `mdbx_env_set_syncperiod()`. - - Небольшие исправления для совместимости с CMake 3.8 - - Больше контроля и осторожности (паранойи) для страховки от дефектов `mremap()`. - - Костыль для починки сборки со старыми версиями `stdatomic.h` из GNU Lib C, - где макросы `ATOMIC_*_LOCK_FREE` ошибочно переопределяются через функции. - - Использование `fcntl64(F_GETLK64/F_SETLK64/F_SETLKW64)` при наличии. - Это решает проблему срабатывания проверочного утверждения при сборке для - платформ где тип `off_t` шире соответствующих полей `структуры flock`, - используемой для блокировки файлов. - - Доработан сбор информации о задержках при фиксации транзакций: - * Устранено искажение замеров длительности обновления GC - при включении отладочного внутреннего аудита; - * Защита от undeflow-нуля только общей задержки в метриках, - чтобы исключить ситуации, когда сумма отдельных стадий - больше общей длительности. - - Ряд исправлений для устранения срабатываний проверочных утверждения в - отладочных сборках. - - Более осторожное преобразование к типу `mdbx_tid_t` для устранения - предупреждений. - - Исправление лишнего сброса данных на диск в режиме `MDBX_SAFE_NOSYNC` - при обновлении GC. - - Fixed an extra check for `MDBX_APPENDDUP` inside `mdbx_cursor_put()` - which could result in returning `MDBX_EKEYMISMATCH` for valid cases. - - Fixed nasty `clz()` bug (by using `_BitScanReverse()`, only MSVC builds affected). - -Мелочи: - - - Исторические ссылки cвязанные с удалённым на ~~github~~ проектом перенаправлены на [web.archive.org](https://web.archive.org/web/https://github.com/erthink/libmdbx). - - Синхронизированы конструкции CMake между проектами. - - Добавлено предупреждение о небезопасности RISC-V. - - Добавлено описание параметров `MDBX_debug_func` и `MDBX_debug_func`. - - Добавлено обходное решение для минимизации ложно-положительных - конфликтов при использовании файловых блокировок в Windows. - - Проверка атомарности C11-операций c 32/64-битными данными. - - Уменьшение в 42 раза значения по-умолчанию для `me_options.dp_limit` - в отладочных сборках. - - Добавление платформы `gcc-riscv64-linux-gnu` в список для цели `cross-gcc`. - - Небольшие правки скрипта `long_stochastic.sh` для работы в Windows. - - Удаление ненужного вызова `LockFileEx()` внутри `mdbx_env_copy()`. - - Добавлено описание использования файловых дескрипторов в различных режимах. - - Добавлено использование `_CrtDbgReport()` в отладочных сборках. - - Fixed an extra ensure/assertion check of `oldest_reader` inside `txn_end()`. - - Removed description of deprecated usage of `MDBX_NODUPDATA`. - - Fixed regression ASAN/Valgring-enabled builds. - - Fixed minor MingGW warning. - - --------------------------------------------------------------------------------- - - -## v0.12.1 "Positive Proxima" at 2022-08-24 - -The planned frontward release with new superior features on the day of 20 anniversary of [Positive Technologies](https://ptsecurty.com). - -``` -37 files changed, 7604 insertions(+), 7417 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -New: - - - The `Big Foot` feature which significantly reduces GC overhead for processing large lists of retired pages from huge transactions. - Now _libmdbx_ avoid creating large chunks of PNLs (page number lists) which required a long sequences of free pages, aka large/overflow pages. - Thus avoiding searching, allocating and storing such sequences inside GC. - - Improved hot/online validation and checking of database pages both for more robustness and performance. - - New solid and fast method to latch meta-pages called `Troika`. - The minimum of memory barriers, reads, comparisons and conditional transitions are used. - - New `MDBX_VALIDATION` environment options to extra validation of DB structure and pages content for carefully/safe handling damaged or untrusted DB. - - Accelerated ×16/×8/×4 by AVX512/AVX2/SSE2/Neon implementations of search page sequences. - - Added the `gcrtime_seconds16dot16` counter to the "Page Operation Statistics" that accumulates time spent for GC searching and reclaiming. - - Copy-with-compactification now clears/zeroes unused gaps inside database pages. - - The `C` and `C++` APIs has been extended and/or refined to simplify using `wchar_t` pathnames. - On Windows the `mdbx_env_openW()`, ``mdbx_env_get_pathW()`()`, `mdbx_env_copyW()`, `mdbx_env_open_for_recoveryW()` are available for now, - but the `mdbx_env_get_path()` has been replaced in favor of `mdbx_env_get_pathW()`. - - Added explicit error message for Buildroot's Microblaze toolchain maintainers. - - Added `MDBX_MANAGE_BUILD_FLAGS` build options for CMake. - - Speed-up internal `bsearch`/`lower_bound` implementation using branchless tactic, including workaround for CLANG x86 optimiser bug. - - A lot internal refinement and micro-optimisations. - - Internally counted volume of dirty pages (unused for now but for coming features). - -Fixes: - - - Never use modern `__cxa_thread_atexit()` on Apple's OSes. - - Don't check owner for finished transactions. - - Fixed typo in `MDBX_EINVAL` which breaks MingGW builds with CLANG. - - -## v0.12.0 at 2022-06-19 - -Not a release but preparation for changing feature set and API. - - -******************************************************************************** - - -## v0.11.14 "Sergey Kapitsa" at 2023-02-14 - -The stable bugfix release in memory of [Sergey Kapitsa](https://en.wikipedia.org/wiki/Sergey_Kapitsa) on his 95th birthday. - -``` -22 files changed, 250 insertions(+), 174 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Fixes: - - backport: Fixed insignificant typo of `||` inside `#if` byte-order condition. - - backport: Fixed `SIGSEGV` or an erroneous call to `free()` in situations where - errors occur when reopening by `mdbx_env_open()` of a previously used - environment. - - backport: Fixed `cursor_put_nochecklen()` internals for case when dupsort'ed named subDb - contains a single key with multiple values (aka duplicates), which are replaced - with a single value by put-operation with the `MDBX_UPSERT+MDBX_ALLDUPS` flags. - In this case, the database becomes completely empty, without any pages. - However exactly this condition was not considered and thus wasn't handled correctly. - See [issue#8](https://gitflic.ru/project/erthink/libmdbx/issue/8) for more information. - - backport: Fixed extra assertion inside `override_meta()`, which could - lead to false-positive failing of the assertion in a debug builds during - DB recovery and auto-rollback. - - backport: Refined the `__cold`/`__hot` macros to avoid the - `error: inlining failed in call to ‘always_inline FOO(...)’: target specific option mismatch` - issue during build using GCC >10.x for SH4 arch. - -Minors: - - - backport: Using the https://libmdbx.dqdkfa.ru/dead-github - for resources deleted by the Github' administration. - - backport: Fixed English typos. - - backport: Fixed proto of `__asan_default_options()`. - - backport: Fixed doxygen-description of C++ API, especially of C++20 concepts. - - backport: Refined `const` and `noexcept` for few C++ API methods. - - backport: Fixed copy&paste typo of "Getting started". - - backport: Update MithrilDB status. - - backport: Resolve false-posirive `used uninitialized` warning from GCC >10.x - while build for SH4 arch. - - --------------------------------------------------------------------------------- - - -## v0.11.13 at "Swashplate" 2022-11-10 - -The stable bugfix release in memory of [Boris Yuryev](https://ru.wikipedia.org/wiki/Юрьев,_Борис_Николаевич) on his 133rd birthday. - -``` -30 files changed, 405 insertions(+), 136 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Fixes: - - - Fixed builds with older libc versions after using `fcntl64()` (backport). - - Fixed builds with older `stdatomic.h` versions, - where the `ATOMIC_*_LOCK_FREE` macros mistakenly redefined using functions (backport). - - Added workaround for `mremap()` defect to avoid assertion failure (backport). - - Workaround for `encryptfs` bug(s) in the `copy_file_range` implementation (backport). - - Fixed unexpected `MDBX_BUSY` from `mdbx_env_set_option()`, `mdbx_env_set_syncbytes()` - and `mdbx_env_set_syncperiod()` (backport). - - CMake requirements lowered to version 3.0.2 (backport). - -Minors: - - - Minor clarification output of `--help` for `mdbx_test` (backport). - - Added admonition of insecure for RISC-V (backport). - - Stochastic scripts and CMake files synchronized with the `devel` branch. - - Use `--dont-check-ram-size` for small-tests make-targets (backport). - - --------------------------------------------------------------------------------- - - -## v0.11.12 "Эребуни" at 2022-10-12 - -The stable bugfix release. - -``` -11 files changed, 96 insertions(+), 49 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Fixes: - - - Fixed static assertion failure on platforms where the `off_t` type is wider - than corresponding fields of `struct flock` used for file locking (backport). - Now _libmdbx_ will use `fcntl64(F_GETLK64/F_SETLK64/F_SETLKW64)` if available. - - Fixed assertion check inside `page_retire_ex()` (backport). - -Minors: - - - Fixed `-Wint-to-pointer-cast` warnings while casting to `mdbx_tid_t` (backport). - - Removed needless `LockFileEx()` inside `mdbx_env_copy()` (backport). - - --------------------------------------------------------------------------------- - - -## v0.11.11 "Тендра-1790" at 2022-09-11 - -The stable bugfix release. - -``` -10 files changed, 38 insertions(+), 21 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Fixes: - - - Fixed an extra check for `MDBX_APPENDDUP` inside `mdbx_cursor_put()` which could result in returning `MDBX_EKEYMISMATCH` for valid cases. - - Fixed an extra ensure/assertion check of `oldest_reader` inside `mdbx_txn_end()`. - - Fixed derived C++ builds by removing `MDBX_INTERNAL_FUNC` for `mdbx_w2mb()` and `mdbx_mb2w()`. - - --------------------------------------------------------------------------------- - - -## v0.11.10 "the TriColor" at 2022-08-22 - -The stable bugfix release. - -``` -14 files changed, 263 insertions(+), 252 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -New: - - - The C++ API has been refined to simplify support for `wchar_t` in path names. - - Added explicit error message for Buildroot's Microblaze toolchain maintainers. - -Fixes: - - - Never use modern `__cxa_thread_atexit()` on Apple's OSes. - - Use `MultiByteToWideChar(CP_THREAD_ACP)` instead of `mbstowcs()`. - - Don't check owner for finished transactions. - - Fixed typo in `MDBX_EINVAL` which breaks MingGW builds with CLANG. - -Minors: - - - Fixed variable name typo. - - Using `ldd` to check used dso. - - Added `MDBX_WEAK_IMPORT_ATTRIBUTE` macro. - - Use current transaction geometry for untouched parameters when `env_set_geometry()` called within a write transaction. - - Minor clarified `iov_page()` failure case. - - --------------------------------------------------------------------------------- - - -## v0.11.9 "Чирчик-1992" at 2022-08-02 - -The stable bugfix release. - -``` -18 files changed, 318 insertions(+), 178 deletions(-) -Signed-off-by: Леонид Юрьев (Leonid Yuriev) -``` - -Acknowledgments: - - - [Alex Sharov](https://github.com/AskAlexSharov) and Erigon team for reporting and testing. - - [Andrew Ashikhmin](https://gitflic.ru/user/yperbasis) for contributing. - -New: - - - Ability to customise `MDBX_LOCK_SUFFIX`, `MDBX_DATANAME`, `MDBX_LOCKNAME` just by predefine ones during build. - - Added to [`mdbx::env_managed`](https://libmdbx.dqdkfa.ru/group__cxx__api.html#classmdbx_1_1env__managed)'s methods a few overloads with `const char* pathname` parameter (C++ API). - -Fixes: - - - Fixed hang copy-with-compactification of a corrupted DB - or in case the volume of output pages is a multiple of `MDBX_ENVCOPY_WRITEBUF`. - - Fixed standalone non-CMake build on MacOS (`#include AvailabilityMacros.h>`). - - Fixed unexpected `MDBX_PAGE_FULL` error in rare cases with large database page sizes. - -Minors: - - - Minor fixes Doxygen references, comments, descriptions, etc. - - Fixed copy&paste typo inside `meta_checktxnid()`. - - Minor fix `meta_checktxnid()` to avoid assertion in debug mode. - - Minor fix `mdbx_env_set_geometry()` to avoid returning `EINVAL` in particular rare cases. - - Minor refine/fix batch-get testcase for large page size. - - Added `--pagesize NN` option to long-stotastic test script. - - Updated Valgrind-suppressions file for modern GCC. - - Fixed `has no symbols` warning from Apple's ranlib. - - --------------------------------------------------------------------------------- - - -## v0.11.8 "Baked Apple" at 2022-06-12 - -The stable release with an important fixes and workaround for the critical macOS thread-local-storage issue. - -Acknowledgments: - - - [Masatoshi Fukunaga](https://github.com/mah0x211) for [Lua bindings](https://github.com/mah0x211/lua-libmdbx). - -New: - - - Added most of transactions flags to the public API. - - Added `MDBX_NOSUCCESS_EMPTY_COMMIT` build option to return non-success result (`MDBX_RESULT_TRUE`) on empty commit. - - Reworked validation and import of DBI-handles into a transaction. - Assumes these changes will be invisible to most users, but will cause fewer surprises in complex DBI cases. - - Added ability to open DB in without-LCK (exclusive read-only) mode in case no permissions to create/write LCK-file. - -Fixes: - - - A series of fixes and improvements for automatically generated documentation (Doxygen). - - Fixed copy&paste bug with could lead to `SIGSEGV` (nullptr dereference) in the exclusive/no-lck mode. - - Fixed minor warnings from modern Apple's CLANG 13. - - Fixed minor warnings from CLANG 14 and in-development CLANG 15. - - Fixed `SIGSEGV` regression in without-LCK (exclusive read-only) mode. - - Fixed `mdbx_check_fs_local()` for CDROM case on Windows. - - Fixed nasty typo of typename which caused false `MDBX_CORRUPTED` error in a rare execution path, - when the size of the thread-ID type not equal to 8. - - Fixed Elbrus/E2K LCC 1.26 compiler warnings (memory model for atomic operations, etc). - - Fixed write-after-free memory corruption on latest `macOS` during finalization/cleanup of thread(s) that executed read transaction(s). - > The issue was suddenly discovered by a [CI](https://en.wikipedia.org/wiki/Continuous_integration) - > after adding an iteration with macOS 11 "Big Sur", and then reproduced on recent release of macOS 12 "Monterey". - > The issue was never noticed nor reported on macOS 10 "Catalina" nor others. - > Analysis shown that the problem caused by a change in the behavior of the system library (internals of dyld and pthread) - > during thread finalization/cleanup: now a memory allocated for a `__thread` variable(s) is released - > before execution of the registered Thread-Local-Storage destructor(s), - > thus a TLS-destructor will write-after-free just by legitime dereference any `__thread` variable. - > This is unexpected crazy-like behavior since the order of resources releasing/destroying - > is not the reverse of ones acquiring/construction order. Nonetheless such surprise - > is now workarounded by using atomic compare-and-swap operations on a 64-bit signatures/cookies. - -Minors: - - - Refined `release-assets` GNU Make target. - - Added logging to `mdbx_fetch_sdb()` to help debugging complex DBI-handels use cases. - - Added explicit error message from probe of no-support for `std::filesystem`. - - Added contributors "score" table by `git fame` to generated docs. - - Added `mdbx_assert_fail()` to public API (mostly for backtracing). - - Now C++20 concepts used/enabled only when `__cpp_lib_concepts >= 202002`. - - Don't provide nor report package information if used as a CMake subproject. - - --------------------------------------------------------------------------------- - - -## v0.11.7 "Resurrected Sarmat" at 2022-04-22 - -The stable risen release after the Github's intentional malicious disaster. - -#### We have migrated to a reliable trusted infrastructure -The origin for now is at [GitFlic](https://gitflic.ru/project/erthink/libmdbx) -since on 2022-04-15 the Github administration, without any warning nor -explanation, deleted _libmdbx_ along with a lot of other projects, -simultaneously blocking access for many developers. -For the same reason ~~Github~~ is blacklisted forever. - -GitFlic already support Russian and English languages, plan to support more, -including 和 中文. You are welcome! - -New: - - - Added the `tools-static` make target to build statically linked MDBX tools. - - Support for Microsoft Visual Studio 2022. - - Support build by MinGW' make from command line without CMake. - - Added `mdbx::filesystem` C++ API namespace that corresponds to `std::filesystem` or `std::experimental::filesystem`. - - Created [website](https://libmdbx.dqdkfa.ru/) for online auto-generated documentation. - - Used `https://web.archive.org/web/https://github.com/erthink/libmdbx` for dead (or temporarily lost) resources deleted by ~~Github~~. - - Added `--loglevel=` command-line option to the `mdbx_test` tool. - - Added few fast smoke-like tests into CMake builds. - -Fixes: - - - Fixed a race between starting a transaction and creating a DBI descriptor that could lead to `SIGSEGV` in the cursor tracking code. - - Clarified description of `MDBX_EPERM` error returned from `mdbx_env_set_geometry()`. - - Fixed non-promoting the parent transaction to be dirty in case the undo of the geometry update failed during abortion of a nested transaction. - - Resolved linking issues with `libstdc++fs`/`libc++fs`/`libc++experimental` for C++ `std::filesystem` or `std::experimental::filesystem` for legacy compilers. - - Added workaround for GNU Make 3.81 and earlier. - - Added workaround for Elbrus/LCC 1.25 compiler bug of class inline `static constexpr` member field. - - [Fixed](https://github.com/ledgerwatch/erigon/issues/3874) minor assertion regression (only debug builds were affected). - - Fixed detection of `C++20` concepts accessibility. - - Fixed detection of Clang's LTO availability for Android. - - Fixed extra definition of `_FILE_OFFSET_BITS=64` for Android that is problematic for 32-bit Bionic. - - Fixed build for ARM/ARM64 by MSVC. - - Fixed non-x86 Windows builds with `MDBX_WITHOUT_MSVC_CRT=ON` and `MDBX_BUILD_SHARED_LIBRARY=ON`. - -Minors: - - - Resolve minor MSVC warnings: avoid `/INCREMENTAL[:YES]` with `/LTCG`, `/W4` with `/W3`, the `C5105` warning. - - Switched to using `MDBX_EPERM` instead of `MDBX_RESULT_TRUE` to indicate that the geometry cannot be updated. - - Added `NULL` checking during memory allocation inside `mdbx_chk`. - - Resolved all warnings from MinGW while used without CMake. - - Added inheritable `target_include_directories()` to `CMakeLists.txt` for easy integration. - - Added build-time checks and paranoid runtime assertions for the `off_t` arguments of `fcntl()` which are used for locking. - - Added `-Wno-lto-type-mismatch` to avoid false-positive warnings from old GCC during LTO-enabled builds. - - Added checking for TID (system thread id) to avoid hang on 32-bit Bionic/Android within `pthread_mutex_lock()`. - - Reworked `MDBX_BUILD_TARGET` of CMake builds. - - Added `CMAKE_HOST_ARCH` and `CMAKE_HOST_CAN_RUN_EXECUTABLES_BUILT_FOR_TARGET`. - - --------------------------------------------------------------------------------- - - -## v0.11.6 at 2022-03-24 - -The stable release with the complete workaround for an incoherence flaw of Linux unified page/buffer cache. -Nonetheless the cause for this trouble may be an issue of Intel CPU cache/MESI. -See [issue#269](https://libmdbx.dqdkfa.ru/dead-github/issues/269) for more information. - -Acknowledgments: - - - [David Bouyssié](https://github.com/david-bouyssie) for [Scala bindings](https://github.com/david-bouyssie/mdbx4s). - - [Michelangelo Riccobene](https://github.com/mriccobene) for reporting and testing. - -Fixes: - - - [Added complete workaround](https://libmdbx.dqdkfa.ru/dead-github/issues/269) for an incoherence flaw of Linux unified page/buffer cache. - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/272) cursor reusing for read-only transactions. - - Fixed copy&paste typo inside `mdbx::cursor::find_multivalue()`. - -Minors: - - - Minor refine C++ API for convenience. - - Minor internals refines. - - Added `lib-static` and `lib-shared` targets for make. - - Added minor workaround for AppleClang 13.3 bug. - - Clarified error messages of a signature/version mismatch. - - --------------------------------------------------------------------------------- - - -## v0.11.5 at 2022-02-23 - -The release with the temporary hotfix for a flaw of Linux unified page/buffer cache. -See [issue#269](https://libmdbx.dqdkfa.ru/dead-github/issues/269) for more information. - -Acknowledgments: - - - [Simon Leier](https://github.com/leisim) for reporting and testing. - - [Kai Wetlesen](https://github.com/kaiwetlesen) for [RPMs](http://copr.fedorainfracloud.org/coprs/kwetlesen/libmdbx/). - - [Tullio Canepa](https://github.com/canepat) for reporting C++ API issue and contributing. - -Fixes: - - - [Added hotfix](https://libmdbx.dqdkfa.ru/dead-github/issues/269) for a flaw of Linux unified page/buffer cache. - - [Fixed/Reworked](https://libmdbx.dqdkfa.ru/dead-github/pull/270) move-assignment operators for "managed" classes of C++ API. - - Fixed potential `SIGSEGV` while open DB with overrided non-default page size. - - [Made](https://libmdbx.dqdkfa.ru/dead-github/issues/267) `mdbx_env_open()` idempotence in failure cases. - - Refined/Fixed pages reservation inside `mdbx_update_gc()` to avoid non-reclamation in a rare cases. - - Fixed typo in a retained space calculation for the hsr-callback. - -Minors: - - - Reworked functions for meta-pages, split-off non-volatile. - - Disentangled C11-atomic fences/barriers and pure-functions (with `__attribute__((__pure__))`) to avoid compiler misoptimization. - - Fixed hypotetic unaligned access to 64-bit dwords on ARM with `__ARM_FEATURE_UNALIGNED` defined. - - Reasonable paranoia that makes clarity for code readers. - - Minor fixes Doxygen references, comments, descriptions, etc. - - --------------------------------------------------------------------------------- - - -## v0.11.4 at 2022-02-02 - -The stable release with fixes for large and huge databases sized of 4..128 TiB. - -Acknowledgments: - - - [Ledgerwatch](https://github.com/ledgerwatch), [Binance](https://github.com/binance-chain) and [Positive Technologies](https://www.ptsecurity.com/) teams for reporting, assistance in investigation and testing. - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting, testing and provide resources for remote debugging/investigation. - - [Kris Zyp](https://github.com/kriszyp) for [Deno](https://deno.land/) support. - -New features, extensions and improvements: - - - Added treating the `UINT64_MAX` value as maximum for given option inside `mdbx_env_set_option()`. - - Added `to_hex/to_base58/to_base64::output(std::ostream&)` overloads without using temporary string objects as buffers. - - Added `--geometry-jitter=YES|no` option to the test framework. - - Added support for [Deno](https://deno.land/) support by [Kris Zyp](https://github.com/kriszyp). - -Fixes: - - - Fixed handling `MDBX_opt_rp_augment_limit` for GC's records from huge transactions (Erigon/Akula/Ethereum). - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/258) build on Android (avoid including `sys/sem.h`). - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/pull/261) missing copy assignment operator for `mdbx::move_result`. - - Fixed missing `&` for `std::ostream &operator<<()` overloads. - - Fixed unexpected `EXDEV` (Cross-device link) error from `mdbx_env_copy()`. - - Fixed base64 encoding/decoding bugs in auxillary C++ API. - - Fixed overflow of `pgno_t` during checking PNL on 64-bit platforms. - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/260) excessive PNL checking after sort for spilling. - - Reworked checking `MAX_PAGENO` and DB upper-size geometry limit. - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/265) build for some combinations of versions of MSVC and Windows SDK. - -Minors: - - - Added workaround for CLANG bug [D79919/PR42445](https://reviews.llvm.org/D79919). - - Fixed build test on Android (using `pthread_barrier_t` stub). - - Disabled C++20 concepts for CLANG < 14 on Android. - - Fixed minor `unused parameter` warning. - - Added CI for Android. - - Refine/cleanup internal logging. - - Refined line splitting inside hex/base58/base64 encoding to avoid `\n` at the end. - - Added workaround for modern libstdc++ with CLANG < 4.x - - Relaxed txn-check rules for auxiliary functions. - - Clarified a comments and descriptions, etc. - - Using the `-fno-semantic interposition` option to reduce the overhead to calling self own public functions. - - --------------------------------------------------------------------------------- - - -## v0.11.3 at 2021-12-31 - -Acknowledgments: - - - [gcxfd ](https://github.com/gcxfd) for reporting, contributing and testing. - - [장세연 (Чан Се Ен)](https://github.com/sasgas) for reporting and testing. - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting, testing and provide resources for remote debugging/investigation. - -New features, extensions and improvements: - - - [Added](https://libmdbx.dqdkfa.ru/dead-github/issues/236) `mdbx_cursor_get_batch()`. - - [Added](https://libmdbx.dqdkfa.ru/dead-github/issues/250) `MDBX_SET_UPPERBOUND`. - - C++ API is finalized now. - - The GC update stage has been [significantly speeded](https://libmdbx.dqdkfa.ru/dead-github/issues/254) when fixing huge Erigon's transactions (Ethereum ecosystem). - -Fixes: - - - Disabled C++20 concepts for stupid AppleClang 13.x - - Fixed internal collision of `MDBX_SHRINK_ALLOWED` with `MDBX_ACCEDE`. - -Minors: - - - Fixed returning `MDBX_RESULT_TRUE` (unexpected -1) from `mdbx_env_set_option()`. - - Added `mdbx_env_get_syncbytes()` and `mdbx_env_get_syncperiod()`. - - [Clarified](https://libmdbx.dqdkfa.ru/dead-github/pull/249) description of `MDBX_INTEGERKEY`. - - Reworked/simplified `mdbx_env_sync_internal()`. - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/248) extra assertion inside `mdbx_cursor_put()` for `MDBX_DUPFIXED` cases. - - Avoiding extra looping inside `mdbx_env_info_ex()`. - - Explicitly enabled core dumps from stochastic tests scripts on Linux. - - [Fixed](https://libmdbx.dqdkfa.ru/dead-github/issues/253) `mdbx_override_meta()` to avoid false-positive assertions. - - For compatibility reverted returning `MDBX_ENODATA`for some cases. - - --------------------------------------------------------------------------------- - - -## v0.11.2 at 2021-12-02 - -Acknowledgments: - - - [장세연 (Чан Се Ен)](https://github.com/sasgas) for contributing to C++ API. - - [Alain Picard](https://github.com/castortech) for [Java bindings](https://github.com/castortech/mdbxjni). - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting and testing. - - [Kris Zyp](https://github.com/kriszyp) for reporting and testing. - - [Artem Vorotnikov](https://github.com/vorot93) for support [Rust wrapper](https://github.com/vorot93/libmdbx-rs). - -Fixes: - - - [Fixed compilation](https://libmdbx.dqdkfa.ru/dead-github/pull/239) with `devtoolset-9` on CentOS/RHEL 7. - - [Fixed unexpected `MDBX_PROBLEM` error](https://libmdbx.dqdkfa.ru/dead-github/issues/242) because of update an obsolete meta-page. - - [Fixed returning `MDBX_NOTFOUND` error](https://libmdbx.dqdkfa.ru/dead-github/issues/243) in case an inexact value found for `MDBX_GET_BOTH` operation. - - [Fixed compilation](https://libmdbx.dqdkfa.ru/dead-github/issues/245) without kernel/libc-devel headers. - -Minors: - - - Fixed `constexpr`-related macros for legacy compilers. - - Allowed to define 'CMAKE_CXX_STANDARD` using an environment variable. - - Simplified collection statistics of page operation . - - Added `MDBX_FORCE_BUILD_AS_MAIN_PROJECT` cmake option. - - Remove unneeded `#undef P_DIRTY`. - - --------------------------------------------------------------------------------- - - -## v0.11.1 at 2021-10-23 - -### Backward compatibility break: - -The database format signature has been changed to prevent -forward-interoperability with an previous releases, which may lead to a -[false positive diagnosis of database corruption](https://libmdbx.dqdkfa.ru/dead-github/issues/238) -due to flaws of an old library versions. - -This change is mostly invisible: - - - previously versions are unable to read/write a new DBs; - - but the new release is able to handle an old DBs and will silently upgrade ones. - -Acknowledgments: - - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting and testing. - - -******************************************************************************** - - -## v0.10.5 at 2021-10-13 (obsolete, please use v0.11.1) - -Unfortunately, the `v0.10.5` accidentally comes not full-compatible with previous releases: - - - `v0.10.5` can read/processing DBs created by previous releases, i.e. the backward-compatibility is provided; - - however, previous releases may lead to false-corrupted state with DB that was touched by `v0.10.5`, i.e. the forward-compatibility is broken for `v0.10.4` and earlier. - -This cannot be fixed, as it requires fixing past versions, which as a result we will just get a current version. -Therefore, it is recommended to use `v0.11.1` instead of `v0.10.5`. - -Acknowledgments: - - - [Noel Kuntze](https://github.com/Thermi) for immediately bug reporting. - -Fixes: - - - Fixed unaligned access regression after the `#pragma pack` fix for modern compilers. - - Added UBSAN-test to CI to avoid a regression(s) similar to lately fixed. - - Fixed possibility of meta-pages clashing after manually turn to a particular meta-page using `mdbx_chk` utility. - -Minors: - - - Refined handling of weak or invalid meta-pages while a DB opening. - - Refined providing information for the `@MAIN` and `@GC` sub-databases of a last committed modification transaction's ID. - - --------------------------------------------------------------------------------- - - -## v0.10.4 at 2021-10-10 - -Acknowledgments: - - - [Artem Vorotnikov](https://github.com/vorot93) for support [Rust wrapper](https://github.com/vorot93/libmdbx-rs). - - [Andrew Ashikhmin](https://github.com/yperbasis) for contributing to C++ API. - -Fixes: - - - Fixed possibility of looping update GC during transaction commit (no public issue since the problem was discovered inside [Positive Technologies](https://www.ptsecurity.ru)). - - Fixed `#pragma pack` to avoid provoking some compilers to generate code with [unaligned access](https://libmdbx.dqdkfa.ru/dead-github/issues/235). - - Fixed `noexcept` for potentially throwing `txn::put()` of C++ API. - -Minors: - - - Added stochastic test script for checking small transactions cases. - - Removed extra transaction commit/restart inside test framework. - - In debugging builds fixed a too small (single page) by default DB shrink threshold. - - --------------------------------------------------------------------------------- - - -## v0.10.3 at 2021-08-27 - -Acknowledgments: - - - [Francisco Vallarino](https://github.com/fjvallarino) for [Haskell bindings for libmdbx](https://hackage.haskell.org/package/libmdbx). - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting and testing. - - [Andrea Lanfranchi](https://github.com/AndreaLanfranchi) for contributing. - -Extensions and improvements: - - - Added `cursor::erase()` overloads for `key` and for `key-value`. - - Resolve minor Coverity Scan issues (no fixes but some hint/comment were added). - - Resolve minor UndefinedBehaviorSanitizer issues (no fixes but some workaround were added). - -Fixes: - - - Always setup `madvise` while opening DB (fixes https://libmdbx.dqdkfa.ru/dead-github/issues/231). - - Fixed checking legacy `P_DIRTY` flag (`0x10`) for nested/sub-pages. - -Minors: - - - Fixed getting revision number from middle of history during amalgamation (GNU Makefile). - - Fixed search GCC tools for LTO (CMake scripts). - - Fixed/reorder dirs list for search CLANG tools for LTO (CMake scripts). - - Fixed/workarounds for CLANG < 9.x - - Fixed CMake warning about compatibility with 3.8.2 - - --------------------------------------------------------------------------------- - - -## v0.10.2 at 2021-07-26 - -Acknowledgments: - - - [Alex Sharov](https://github.com/AskAlexSharov) for reporting and testing. - - [Andrea Lanfranchi](https://github.com/AndreaLanfranchi) for reporting bugs. - - [Lionel Debroux](https://github.com/debrouxl) for fuzzing tests and reporting bugs. - - [Sergey Fedotov](https://github.com/SergeyFromHell/) for [`node-mdbx` NodeJS bindings](https://www.npmjs.com/package/node-mdbx). - - [Kris Zyp](https://github.com/kriszyp) for [`lmdbx-store` NodeJS bindings](https://github.com/kriszyp/lmdbx-store). - - [Noel Kuntze](https://github.com/Thermi) for [draft Python bindings](https://libmdbx.dqdkfa.ru/dead-github/commits/python-bindings). - -New features, extensions and improvements: - - - [Allow to predefine/override `MDBX_BUILD_TIMESTAMP` for builds reproducibility](https://libmdbx.dqdkfa.ru/dead-github/issues/201). - - Added options support for `long-stochastic` script. - - Avoided `MDBX_TXN_FULL` error for large transactions when possible. - - The `MDBX_READERS_LIMIT` increased to `32767`. - - Raise `MDBX_TOO_LARGE` under Valgrind/ASAN if being opened DB is 100 larger than RAM (to avoid hangs and OOM). - - Minimized the size of poisoned/unpoisoned regions to avoid Valgrind/ASAN stuck. - - Added more workarounds for QEMU for testing builds for 32-bit platforms, Alpha and Sparc architectures. - - `mdbx_chk` now skips iteration & checking of DB' records if corresponding page-tree is corrupted (to avoid `SIGSEGV`, ASAN failures, etc). - - Added more checks for [rare/fuzzing corruption cases](https://libmdbx.dqdkfa.ru/dead-github/issues/217). - -Backward compatibility break: - - - Use file `VERSION.txt` for version information instead of `VERSION` to avoid collision with `#include `. - - Rename `slice::from/to_FOO_bytes()` to `slice::envisage_from/to_FOO_length()'. - - Rename `MDBX_TEST_EXTRA` make's variable to `MDBX_SMOKE_EXTRA`. - - Some details of the C++ API have been changed for subsequent freezing. - -Fixes: - - - Fixed excess meta-pages checks in case `mdbx_chk` is called to check the DB for a specific meta page and thus could prevent switching to the selected meta page, even if the check passed without errors. - - Fixed [recursive use of SRW-lock on Windows cause by `MDBX_NOTLS` option](https://libmdbx.dqdkfa.ru/dead-github/issues/203). - - Fixed [log a warning during a new DB creation](https://libmdbx.dqdkfa.ru/dead-github/issues/205). - - Fixed [false-negative `mdbx_cursor_eof()` result](https://libmdbx.dqdkfa.ru/dead-github/issues/207). - - Fixed [`make install` with non-GNU `install` utility (OSX, BSD)](https://libmdbx.dqdkfa.ru/dead-github/issues/208). - - Fixed [installation by `CMake` in special cases by complete use `GNUInstallDirs`'s variables](https://libmdbx.dqdkfa.ru/dead-github/issues/209). - - Fixed [C++ Buffer issue with `std::string` and alignment](https://libmdbx.dqdkfa.ru/dead-github/issues/191). - - Fixed `safe64_reset()` for platforms without atomic 64-bit compare-and-swap. - - Fixed hang/shutdown on big-endian platforms without `__cxa_thread_atexit()`. - - Fixed [using bad meta-pages if DB was partially/recoverable corrupted](https://libmdbx.dqdkfa.ru/dead-github/issues/217). - - Fixed extra `noexcept` for `buffer::&assign_reference()`. - - Fixed `bootid` generation on Windows for case of change system' time. - - Fixed [test framework keygen-related issue](https://libmdbx.dqdkfa.ru/dead-github/issues/127). - - --------------------------------------------------------------------------------- - - -## v0.10.1 at 2021-06-01 - -Acknowledgments: - - - [Alexey Akhunov](https://github.com/AlexeyAkhunov) and [Alex Sharov](https://github.com/AskAlexSharov) for bug reporting and testing. - - [Andrea Lanfranchi](https://github.com/AndreaLanfranchi) for bug reporting and testing related to WSL2. - -New features: - - - Added `-p` option to `mdbx_stat` utility for printing page operations statistic. - - Added explicit checking for and warning about using unfit github's archives. - - Added fallback from [OFD locking](https://bit.ly/3yFRtYC) to legacy non-OFD POSIX file locks on an `EINVAL` error. - - Added [Plan 9](https://en.wikipedia.org/wiki/9P_(protocol)) network file system to the whitelist for an ability to open a DB in exclusive mode. - - Support for opening from WSL2 environment a DB hosted on Windows drive and mounted via [DrvFs](https://docs.microsoft.com/it-it/archive/blogs/wsl/wsl-file-system-support#drvfs) (i.e by Plan 9 noted above). - -Fixes: - - - Fixed minor "foo not used" warnings from modern C++ compilers when building the C++ part of the library. - - Fixed confusing/messy errors when build library from unfit github's archives (https://libmdbx.dqdkfa.ru/dead-github/issues/197). - - Fixed `#​e​l​s​i​f` typo. - - Fixed rare unexpected `MDBX_PROBLEM` error during altering data in huge transactions due to wrong spilling/oust of dirty pages (https://libmdbx.dqdkfa.ru/dead-github/issues/195). - - Re-Fixed WSL1/WSL2 detection with distinguishing (https://libmdbx.dqdkfa.ru/dead-github/issues/97). - - --------------------------------------------------------------------------------- - - -## v0.10.0 at 2021-05-09 - -Acknowledgments: - - - [Mahlon E. Smith](https://github.com/mahlonsmith) for [Ruby bindings](https://rubygems.org/gems/mdbx/). - - [Alex Sharov](https://github.com/AskAlexSharov) for [mdbx-go](https://github.com/torquem-ch/mdbx-go), bug reporting and testing. - - [Artem Vorotnikov](https://github.com/vorot93) for bug reporting and PR. - - [Paolo Rebuffo](https://www.linkedin.com/in/paolo-rebuffo-8255766/), [Alexey Akhunov](https://github.com/AlexeyAkhunov) and Mark Grosberg for donations. - - [Noel Kuntze](https://github.com/Thermi) for preliminary [Python bindings](https://github.com/Thermi/libmdbx/tree/python-bindings) - -New features: - - - Added `mdbx_env_set_option()` and `mdbx_env_get_option()` for controls - various runtime options for an environment (announce of this feature was missed in a previous news). - - Added `MDBX_DISABLE_PAGECHECKS` build option to disable some checks to reduce an overhead - and detection probability of database corruption to a values closer to the LMDB. - The `MDBX_DISABLE_PAGECHECKS=1` provides a performance boost of about 10% in CRUD scenarios, - and conjointly with the `MDBX_ENV_CHECKPID=0` and `MDBX_TXN_CHECKOWNER=0` options can yield - up to 30% more performance compared to LMDB. - - Using float point (exponential quantized) representation for internal 16-bit values - of grow step and shrink threshold when huge ones (https://libmdbx.dqdkfa.ru/dead-github/issues/166). - To minimize the impact on compatibility, only the odd values inside the upper half - of the range (i.e. 32769..65533) are used for the new representation. - - Added the `mdbx_drop` similar to LMDB command-line tool to purge or delete (sub)database(s). - - [Ruby bindings](https://rubygems.org/gems/mdbx/) is available now by [Mahlon E. Smith](https://github.com/mahlonsmith). - - Added `MDBX_ENABLE_MADVISE` build option which controls the use of POSIX `madvise()` hints and friends. - - The internal node sizes were refined, resulting in a reduction in large/overflow pages in some use cases - and a slight increase in limits for a keys size to ≈½ of page size. - - Added to `mdbx_chk` output number of keys/items on pages. - - Added explicit `install-strip` and `install-no-strip` targets to the `Makefile` (https://libmdbx.dqdkfa.ru/dead-github/pull/180). - - Major rework page splitting (af9b7b560505684249b76730997f9e00614b8113) for - - An "auto-appending" feature upon insertion for both ascending and - descending key sequences. As a result, the optimality of page filling - increases significantly (more densely, less slackness) while - inserting ordered sequences of keys, - - A "splitting at middle" to make page tree more balanced on average. - - Added `mdbx_get_sysraminfo()` to the API. - - Added guessing a reasonable maximum DB size for the default upper limit of geometry (https://libmdbx.dqdkfa.ru/dead-github/issues/183). - - Major rework internal labeling of a dirty pages (958fd5b9479f52f2124ab7e83c6b18b04b0e7dda) for - a "transparent spilling" feature with the gist to make a dirty pages - be ready to spilling (writing to a disk) without further altering ones. - Thus in the `MDBX_WRITEMAP` mode the OS kernel able to oust dirty pages - to DB file without further penalty during transaction commit. - As a result, page swapping and I/O could be significantly reduced during extra large transactions and/or lack of memory. - - Minimized reading leaf-pages during dropping subDB(s) and nested trees. - - Major rework a spilling of dirty pages to support [LRU](https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)) - policy and prioritization for a large/overflow pages. - - Statistics of page operations (split, merge, copy, spill, etc) now available through `mdbx_env_info_ex()`. - - Auto-setup limit for length of dirty pages list (`MDBX_opt_txn_dp_limit` option). - - Support `make options` to list available build options. - - Support `make help` to list available make targets. - - Silently `make`'s build by default. - - Preliminary [Python bindings](https://github.com/Thermi/libmdbx/tree/python-bindings) is available now - by [Noel Kuntze](https://github.com/Thermi) (https://libmdbx.dqdkfa.ru/dead-github/issues/147). - -Backward compatibility break: - - - The `MDBX_AVOID_CRT` build option was renamed to `MDBX_WITHOUT_MSVC_CRT`. - This option is only relevant when building for Windows. - - The `mdbx_env_stat()` always, and `mdbx_env_stat_ex()` when called with the zeroed transaction parameter, - now internally start temporary read transaction and thus may returns `MDBX_BAD_RSLOT` error. - So, just never use deprecated `mdbx_env_stat()' and call `mdbx_env_stat_ex()` with transaction parameter. - - The build option `MDBX_CONFIG_MANUAL_TLS_CALLBACK` was removed and now just a non-zero value of - the `MDBX_MANUAL_MODULE_HANDLER` macro indicates the requirement to manually call `mdbx_module_handler()` - when loading libraries and applications uses statically linked libmdbx on an obsolete Windows versions. - -Fixes: - - - Fixed performance regression due non-optimal C11 atomics usage (https://libmdbx.dqdkfa.ru/dead-github/issues/160). - - Fixed "reincarnation" of subDB after it deletion (https://libmdbx.dqdkfa.ru/dead-github/issues/168). - - Fixed (disallowing) implicit subDB deletion via operations on `@MAIN`'s DBI-handle. - - Fixed a crash of `mdbx_env_info_ex()` in case of a call for a non-open environment (https://libmdbx.dqdkfa.ru/dead-github/issues/171). - - Fixed the selecting/adjustment values inside `mdbx_env_set_geometry()` for implicit out-of-range cases (https://libmdbx.dqdkfa.ru/dead-github/issues/170). - - Fixed `mdbx_env_set_option()` for set initial and limit size of dirty page list ((https://libmdbx.dqdkfa.ru/dead-github/issues/179). - - Fixed an unreasonably huge default upper limit for DB geometry (https://libmdbx.dqdkfa.ru/dead-github/issues/183). - - Fixed `constexpr` specifier for the `slice::invalid()`. - - Fixed (no)readahead auto-handling (https://libmdbx.dqdkfa.ru/dead-github/issues/164). - - Fixed non-alloy build for Windows. - - Switched to using Heap-functions instead of LocalAlloc/LocalFree on Windows. - - Fixed `mdbx_env_stat_ex()` to returning statistics of the whole environment instead of MainDB only (https://libmdbx.dqdkfa.ru/dead-github/issues/190). - - Fixed building by GCC 4.8.5 (added workaround for a preprocessor's bug). - - Fixed building C++ part for iOS <= 13.0 (unavailability of `std::filesystem::path`). - - Fixed building for Windows target versions prior to Windows Vista (`WIN32_WINNT < 0x0600`). - - Fixed building by MinGW for Windows (https://libmdbx.dqdkfa.ru/dead-github/issues/155). - - -******************************************************************************** - - -## v0.9.3 at 2021-02-02 - -Acknowledgments: - - - [Mahlon E. Smith](http://www.martini.nu/) for [FreeBSD port of libmdbx](https://svnweb.freebsd.org/ports/head/databases/mdbx/). - - [장세연](http://www.castis.com) for bug fixing and PR. - - [Clément Renault](https://github.com/Kerollmops/heed) for [Heed](https://github.com/Kerollmops/heed) fully typed Rust wrapper. - - [Alex Sharov](https://github.com/AskAlexSharov) for bug reporting. - - [Noel Kuntze](https://github.com/Thermi) for bug reporting. - -Removed options and features: - - - Drop `MDBX_HUGE_TRANSACTIONS` build-option (now no longer required). - -New features: - - - Package for FreeBSD is available now by Mahlon E. Smith. - - New API functions to get/set various options (https://libmdbx.dqdkfa.ru/dead-github/issues/128): - - the maximum number of named databases for the environment; - - the maximum number of threads/reader slots; - - threshold (since the last unsteady commit) to force flush the data buffers to disk; - - relative period (since the last unsteady commit) to force flush the data buffers to disk; - - limit to grow a list of reclaimed/recycled page's numbers for finding a sequence of contiguous pages for large data items; - - limit to grow a cache of dirty pages for reuse in the current transaction; - - limit of a pre-allocated memory items for dirty pages; - - limit of dirty pages for a write transaction; - - initial allocation size for dirty pages list of a write transaction; - - maximal part of the dirty pages may be spilled when necessary; - - minimal part of the dirty pages should be spilled when necessary; - - how much of the parent transaction dirty pages will be spilled while start each child transaction; - - Unlimited/Dynamic size of retired and dirty page lists (https://libmdbx.dqdkfa.ru/dead-github/issues/123). - - Added `-p` option (purge subDB before loading) to `mdbx_load` tool. - - Reworked spilling of large transaction and committing of nested transactions: - - page spilling code reworked to avoid the flaws and bugs inherited from LMDB; - - limit for number of dirty pages now is controllable at runtime; - - a spilled pages, including overflow/large pages, now can be reused and refunded/compactified in nested transactions; - - more effective refunding/compactification especially for the loosed page cache. - - Added `MDBX_ENABLE_REFUND` and `MDBX_PNL_ASCENDING` internal/advanced build options. - - Added `mdbx_default_pagesize()` function. - - Better support architectures with a weak/relaxed memory consistency model (ARM, AARCH64, PPC, MIPS, RISC-V, etc) by means [C11 atomics](https://en.cppreference.com/w/c/atomic). - - Speed up page number lists and dirty page lists (https://libmdbx.dqdkfa.ru/dead-github/issues/132). - - Added `LIBMDBX_NO_EXPORTS_LEGACY_API` build option. - -Fixes: - - - Fixed missing cleanup (null assigned) in the C++ commit/abort (https://libmdbx.dqdkfa.ru/dead-github/pull/143). - - Fixed `mdbx_realloc()` for case of nullptr and `MDBX_WITHOUT_MSVC_CRT=ON` for Windows. - - Fixed the possibility to use invalid and renewed (closed & re-opened, dropped & re-created) DBI-handles (https://libmdbx.dqdkfa.ru/dead-github/issues/146). - - Fixed 4-byte aligned access to 64-bit integers, including access to the `bootid` meta-page's field (https://libmdbx.dqdkfa.ru/dead-github/issues/153). - - Fixed minor/potential memory leak during page flushing and unspilling. - - Fixed handling states of cursors's and subDBs's for nested transactions. - - Fixed page leak in extra rare case the list of retired pages changed during update GC on transaction commit. - - Fixed assertions to avoid false-positive UB detection by CLANG/LLVM (https://libmdbx.dqdkfa.ru/dead-github/issues/153). - - Fixed `MDBX_TXN_FULL` and regressive `MDBX_KEYEXIST` during large transaction commit with `MDBX_LIFORECLAIM` (https://libmdbx.dqdkfa.ru/dead-github/issues/123). - - Fixed auto-recovery (`weak->steady` with the same boot-id) when Database size at last weak checkpoint is large than at last steady checkpoint. - - Fixed operation on systems with unusual small/large page size, including PowerPC (https://libmdbx.dqdkfa.ru/dead-github/issues/157). - - --------------------------------------------------------------------------------- - - -## v0.9.2 at 2020-11-27 - -Acknowledgments: - - - Jens Alfke (Mobile Architect at [Couchbase](https://www.couchbase.com/)) for [NimDBX](https://github.com/snej/nimdbx). - - Clément Renault (CTO at [MeiliSearch](https://www.meilisearch.com/)) for [mdbx-rs](https://github.com/Kerollmops/mdbx-rs). - - Alex Sharov (Go-Lang Teach Lead at [TurboGeth/Ethereum](https://ethereum.org/)) for an extreme test cases and bug reporting. - - George Hazan (CTO at [Miranda NG](https://www.miranda-ng.org/)) for bug reporting. - - [Positive Technologies](https://www.ptsecurity.com/) for funding and [The Standoff](https://standoff365.com/). - -Added features: - - - Provided package for [buildroot](https://buildroot.org/). - - Binding for Nim is [available](https://github.com/snej/nimdbx) now by Jens Alfke. - - Added `mdbx_env_delete()` for deletion an environment files in a proper and multiprocess-safe way. - - Added `mdbx_txn_commit_ex()` with collecting latency information. - - Fast completion pure nested transactions. - - Added `LIBMDBX_INLINE_API` macro and inline versions of some API functions. - - Added `mdbx_cursor_copy()` function. - - Extended tests for checking cursor tracking. - - Added `MDBX_SET_LOWERBOUND` operation for `mdbx_cursor_get()`. - -Fixes: - - - Fixed missing installation of `mdbx.h++`. - - Fixed use of obsolete `__noreturn`. - - Fixed use of `yield` instruction on ARM if unsupported. - - Added pthread workaround for buggy toolchain/cmake/buildroot. - - Fixed use of `pthread_yield()` for non-GLIBC. - - Fixed use of `RegGetValueA()` on Windows 2000/XP. - - Fixed use of `GetTickCount64()` on Windows 2000/XP. - - Fixed opening DB on a network shares (in the exclusive mode). - - Fixed copy&paste typos. - - Fixed minor false-positive GCC warning. - - Added workaround for broken `DEFINE_ENUM_FLAG_OPERATORS` from Windows SDK. - - Fixed cursor state after multimap/dupsort repeated deletes (https://libmdbx.dqdkfa.ru/dead-github/issues/121). - - Added `SIGPIPE` suppression for internal thread during `mdbx_env_copy()`. - - Fixed extra-rare `MDBX_KEY_EXIST` error during `mdbx_commit()` (https://libmdbx.dqdkfa.ru/dead-github/issues/131). - - Fixed spilled pages checking (https://libmdbx.dqdkfa.ru/dead-github/issues/126). - - Fixed `mdbx_load` for 'plain text' and without `-s name` cases (https://libmdbx.dqdkfa.ru/dead-github/issues/136). - - Fixed save/restore/commit of cursors for nested transactions. - - Fixed cursors state in rare/special cases (move next beyond end-of-data, after deletion and so on). - - Added workaround for MSVC 19.28 (Visual Studio 16.8) (but may still hang during compilation). - - Fixed paranoidal Clang C++ UB for bitwise operations with flags defined by enums. - - Fixed large pages checking (for compatibility and to avoid false-positive errors from `mdbx_chk`). - - Added workaround for Wine (https://github.com/miranda-ng/miranda-ng/issues/1209). - - Fixed `ERROR_NOT_SUPPORTED` while opening DB by UNC pathnames (https://github.com/miranda-ng/miranda-ng/issues/2627). - - Added handling `EXCEPTION_POSSIBLE_DEADLOCK` condition for Windows. - - --------------------------------------------------------------------------------- - - -## v0.9.1 2020-09-30 - -Added features: - - - Preliminary C++ API with support for C++17 polymorphic allocators. - - [Online C++ API reference](https://libmdbx.dqdkfa.ru/) by Doxygen. - - Quick reference for Insert/Update/Delete operations. - - Explicit `MDBX_SYNC_DURABLE` to sync modes for API clarity. - - Explicit `MDBX_ALLDUPS` and `MDBX_UPSERT` for API clarity. - - Support for read transactions preparation (`MDBX_TXN_RDONLY_PREPARE` flag). - - Support for cursor preparation/(pre)allocation and reusing (`mdbx_cursor_create()` and `mdbx_cursor_bind()` functions). - - Support for checking database using specified meta-page (see `mdbx_chk -h`). - - Support for turn to the specific meta-page after checking (see `mdbx_chk -h`). - - Support for explicit reader threads (de)registration. - - The `mdbx_txn_break()` function to explicitly mark a transaction as broken. - - Improved handling of corrupted databases by `mdbx_chk` utility and `mdbx_walk_tree()` function. - - Improved DB corruption detection by checking parent-page-txnid. - - Improved opening large DB (> 4Gb) from 32-bit code. - - Provided `pure-function` and `const-function` attributes to C API. - - Support for user-settable context for transactions & cursors. - - Revised API and documentation related to Handle-Slow-Readers callback feature. - -Deprecated functions and flags: - - - For clarity and API simplification the `MDBX_MAPASYNC` flag is deprecated. - Just use `MDBX_SAFE_NOSYNC` or `MDBX_UTTERLY_NOSYNC` instead of it. - - `MDBX_oom_func`, `mdbx_env_set_oomfunc()` and `mdbx_env_get_oomfunc()` - replaced with `MDBX_hsr_func`, `mdbx_env_get_hsr` and `mdbx_env_get_hsr()`. - -Fixes: - - - Fix `mdbx_strerror()` for `MDBX_BUSY` error (no error description is returned). - - Fix update internal meta-geo information in read-only mode (`EACCESS` or `EBADFD` error). - - Fix `mdbx_page_get()` null-defer when DB corrupted (crash by `SIGSEGV`). - - Fix `mdbx_env_open()` for re-opening after non-fatal errors (`mdbx_chk` unexpected failures). - - Workaround for MSVC 19.27 `static_assert()` bug. - - Doxygen descriptions and refinement. - - Update Valgrind's suppressions. - - Workaround to avoid infinite loop of 'nested' testcase on MIPS under QEMU. - - Fix a lot of typos & spelling (Thanks to Josh Soref for PR). - - Fix `getopt()` messages for Windows (Thanks to Andrey Sporaw for reporting). - - Fix MSVC compiler version requirements (Thanks to Andrey Sporaw for reporting). - - Workarounds for QEMU's bugs to run tests for cross-built[A library under QEMU. - - Now C++ compiler optional for building by CMake. - - --------------------------------------------------------------------------------- - - -## v0.9.0 2020-07-31 (not a release, but API changes) - -Added features: - - - [Online C API reference](https://libmdbx.dqdkfa.ru/) by Doxygen. - - Separated enums for environment, sub-databases, transactions, copying and data-update flags. - -Deprecated functions and flags: - - - Usage of custom comparators and the `mdbx_dbi_open_ex()` are deprecated, since such databases couldn't be checked by the `mdbx_chk` utility. - Please use the value-to-key functions to provide keys that are compatible with the built-in libmdbx comparators. - - -******************************************************************************** - - -## 2020-07-06 - - - Added support multi-opening the same DB in a process with SysV locking (BSD). - - Fixed warnings & minors for LCC compiler (E2K). - - Enabled to simultaneously open the same database from processes with and without the `MDBX_WRITEMAP` option. - - Added key-to-value, `mdbx_get_keycmp()` and `mdbx_get_datacmp()` functions (helpful to avoid using custom comparators). - - Added `ENABLE_UBSAN` CMake option to enabling the UndefinedBehaviorSanitizer from GCC/CLANG. - - Workaround for [CLANG bug](https://bugs.llvm.org/show_bug.cgi?id=43275). - - Returning `MDBX_CORRUPTED` in case all meta-pages are weak and no other error. - - Refined mode bits while auto-creating LCK-file. - - Avoids unnecessary database file re-mapping in case geometry changed by another process(es). - From the user's point of view, the `MDBX_UNABLE_EXTEND_MAPSIZE` error will now be returned less frequently and only when using the DB in the current process really requires it to be reopened. - - Remapping on-the-fly and of the database file was implemented. - Now remapping with a change of address is performed automatically if there are no dependent readers in the current process. - - -## 2020-06-12 - - - Minor change versioning. The last number in the version now means the number of commits since last release/tag. - - Provide ChangeLog file. - - Fix for using libmdbx as a C-only sub-project with CMake. - - Fix `mdbx_env_set_geometry()` for case it is called from an opened environment outside of a write transaction. - - Add support for huge transactions and `MDBX_HUGE_TRANSACTIONS` build-option (default `OFF`). - - Refine LTO (link time optimization) for clang. - - Force enabling exceptions handling for MSVC (`/EHsc` option). - - -## 2020-06-05 - - - Support for Android/Bionic. - - Support for iOS. - - Auto-handling `MDBX_NOSUBDIR` while opening for any existing database. - - Engage github-actions to make release-assets. - - Clarify API description. - - Extended keygen-cases in stochastic test. - - Fix fetching of first/lower key from LEAF2-page during page merge. - - Fix missing comma in array of error messages. - - Fix div-by-zero while copy-with-compaction for non-resizable environments. - - Fixes & enhancements for custom-comparators. - - Fix `MDBX_WITHOUT_MSVC_CRT` option and missing `ntdll.def`. - - Fix `mdbx_env_close()` to work correctly called concurrently from several threads. - - Fix null-deref in an ASAN-enabled builds while opening the environment with error and/or read-only. - - Fix AddressSanitizer errors after closing the environment. - - Fix/workaround to avoid GCC 10.x pedantic warnings. - - Fix using `ENODATA` for FreeBSD. - - Avoid invalidation of DBI-handle(s) when it just closes. - - Avoid using `pwritev()` for single-writes (up to 10% speedup for some kernels & scenarios). - - Avoiding `MDBX_UTTERLY_NOSYNC` as result of flags merge. - - Add `mdbx_dbi_dupsort_depthmask()` function. - - Add `MDBX_CP_FORCE_RESIZABLE` option. - - Add deprecated `MDBX_MAP_RESIZED` for compatibility. - - Add `MDBX_BUILD_TOOLS` option (default `ON`). - - Refine `mdbx_dbi_open_ex()` to safe concurrently opening the same handle from different threads. - - Truncate clk-file during environment closing. So a zero-length lck-file indicates that the environment was closed properly. - - Refine `mdbx_update_gc()` for huge transactions with small sizes of database page. - - Extends dump/load to support all MDBX attributes. - - Avoid upsertion the same key-value data, fix related assertions. - - Rework min/max length checking for keys & values. - - Checking the order of keys on all pages during checking. - - Support `CFLAGS_EXTRA` make-option for convenience. - - Preserve the last txnid while copying with compactification. - - Auto-reset running transaction in mdbx_txn_renew(). - - Automatically abort errored transaction in mdbx_txn_commit(). - - Auto-choose page size for large databases. - - Rearrange source files, rework build, options-support by CMake. - - Crutch for WSL1 (Windows subsystem for Linux). - - Refine install/uninstall targets. - - Support for Valgrind 3.14 and later. - - Add check-analyzer check-ubsan check-asan check-leak targets to Makefile. - - Minor fix/workaround to avoid UBSAN traps for `memcpy(ptr, NULL, 0)`. - - Avoid some GCC-analyzer false-positive warnings. - - -## 2020-03-18 - - - Workarounds for Wine (Windows compatibility layer for Linux). - - `MDBX_MAP_RESIZED` renamed to `MDBX_UNABLE_EXTEND_MAPSIZE`. - - Clarify API description, fix typos. - - Speedup runtime checks in debug/checked builds. - - Added checking for read/write transactions overlapping for the same thread, added `MDBX_TXN_OVERLAPPING` error and `MDBX_DBG_LEGACY_OVERLAP` option. - - Added `mdbx_key_from_jsonInteger()`, `mdbx_key_from_double()`, `mdbx_key_from_float()`, `mdbx_key_from_int64()` and `mdbx_key_from_int32()` functions. See `mdbx.h` for description. - - Fix compatibility (use zero for invalid DBI). - - Refine/clarify error messages. - - Avoids extra error messages "bad txn" from mdbx_chk when DB is corrupted. - - -## 2020-01-21 - - - Fix `mdbx_load` utility for custom comparators. - - Fix checks related to `MDBX_APPEND` flag inside `mdbx_cursor_put()`. - - Refine/fix dbi_bind() internals. - - Refine/fix handling `STATUS_CONFLICTING_ADDRESSES`. - - Rework `MDBX_DBG_DUMP` option to avoid disk I/O performance degradation. - - Add built-in help to test tool. - - Fix `mdbx_env_set_geometry()` for large page size. - - Fix env_set_geometry() for large pagesize. - - Clarify API description & comments, fix typos. - - -## 2019-12-31 - - - Fix returning MDBX_RESULT_TRUE from page_alloc(). - - Fix false-positive ASAN issue. - - Fix assertion for `MDBX_NOTLS` option. - - Rework `MADV_DONTNEED` threshold. - - Fix `mdbx_chk` utility for don't checking some numbers if walking on the B-tree was disabled. - - Use page's mp_txnid for basic integrity checking. - - Add `MDBX_FORCE_ASSERTIONS` built-time option. - - Rework `MDBX_DBG_DUMP` to avoid performance degradation. - - Rename `MDBX_NOSYNC` to `MDBX_SAFE_NOSYNC` for clarity. - - Interpret `ERROR_ACCESS_DENIED` from `OpenProcess()` as 'process exists'. - - Avoid using `FILE_FLAG_NO_BUFFERING` for compatibility with small database pages. - - Added install section for CMake. - - -## 2019-12-02 - - - Support for Mac OSX, FreeBSD, NetBSD, OpenBSD, DragonFly BSD, OpenSolaris, OpenIndiana (AIX and HP-UX pending). - - Use bootid for decisions of rollback. - - Counting retired pages and extended transaction info. - - Add `MDBX_ACCEDE` flag for database opening. - - Using OFD-locks and tracking for in-process multi-opening. - - Hot backup into pipe. - - Support for cmake & amalgamated sources. - - Fastest internal sort implementation. - - New internal dirty-list implementation with lazy sorting. - - Support for lazy-sync-to-disk with polling. - - Extended key length. - - Last update transaction number for each sub-database. - - Automatic read ahead enabling/disabling. - - More auto-compactification. - - Using -fsanitize=undefined and -Wpedantic options. - - Rework page merging. - - Nested transactions. - - API description. - - Checking for non-local filesystems to avoid DB corruption. - - -******************************************************************************** - - -For early changes see the git commit history. diff --git a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/README.md b/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/README.md deleted file mode 100644 index 46e1c5492..000000000 --- a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/README.md +++ /dev/null @@ -1,797 +0,0 @@ - - -### The origin has been migrated to [GitFlic](https://gitflic.ru/project/erthink/libmdbx) -since on 2022-04-15 the Github administration, without any warning -nor explanation, deleted _libmdbx_ along with a lot of other projects, -simultaneously blocking access for many developers. -For the same reason ~~Github~~ is blacklisted forever. - -GitFlic's developers plan to support other languages, -including English 和 中文, in the near future. - -### Основной репозиторий перемещен на [GitFlic](https://gitflic.ru/project/erthink/libmdbx) -так как 15 апреля 2022 администрация Github без предупреждения и -объяснения причин удалила _libmdbx_ вместе с массой других проектов, -одновременно заблокировав доступ многим разработчикам. -По этой же причине ~~Github~~ навсегда занесен в черный список. - --------------------------------------------------------------------------------- - -*The Future will (be) [Positive](https://www.ptsecurity.com). Всё будет хорошо.* - -> Please refer to the online [documentation](https://libmdbx.dqdkfa.ru) -> with [`C` API description](https://libmdbx.dqdkfa.ru/group__c__api.html) -> and pay attention to the [`C++` API](https://gitflic.ru/project/erthink/libmdbx/blob?file=mdbx.h%2B%2B#line-num-1). - -> Questions, feedback and suggestions are welcome to the [Telegram' group](https://t.me/libmdbx). - -> For NEWS take a look to the [ChangeLog](https://gitflic.ru/project/erthink/libmdbx/blob?file=ChangeLog.md) -> or the [TODO](https://gitflic.ru/project/erthink/libmdbx/blob?file=TODO.md). - - -libmdbx -======== - - - -_libmdbx_ is an extremely fast, compact, powerful, embedded, transactional -[key-value database](https://en.wikipedia.org/wiki/Key-value_database), -with [permissive license](https://gitflic.ru/project/erthink/libmdbx/blob?file=LICENSE). -_libmdbx_ has a specific set of properties and capabilities, -focused on creating unique lightweight solutions. - -1. Allows **a swarm of multi-threaded processes to -[ACID](https://en.wikipedia.org/wiki/ACID)ly read and update** several -key-value [maps](https://en.wikipedia.org/wiki/Associative_array) and -[multimaps](https://en.wikipedia.org/wiki/Multimap) in a locally-shared -database. - -2. Provides **extraordinary performance**, minimal overhead through -[Memory-Mapping](https://en.wikipedia.org/wiki/Memory-mapped_file) and -`Olog(N)` operations costs by virtue of [B+ -tree](https://en.wikipedia.org/wiki/B%2B_tree). - -3. Requires **no maintenance and no crash recovery** since it doesn't use -[WAL](https://en.wikipedia.org/wiki/Write-ahead_logging), but that might -be a caveat for write-intensive workloads with durability requirements. - -4. **Compact and friendly for fully embedding**. Only ≈25KLOC of `C11`, -≈64K x86 binary code of core, no internal threads neither server process(es), -but implements a simplified variant of the [Berkeley -DB](https://en.wikipedia.org/wiki/Berkeley_DB) and -[dbm](https://en.wikipedia.org/wiki/DBM_(computing)) API. - -5. Enforces [serializability](https://en.wikipedia.org/wiki/Serializability) for -writers just by single -[mutex](https://en.wikipedia.org/wiki/Mutual_exclusion) and affords -[wait-free](https://en.wikipedia.org/wiki/Non-blocking_algorithm#Wait-freedom) -for parallel readers without atomic/interlocked operations, while -**writing and reading transactions do not block each other**. - -6. **Guarantee data integrity** after crash unless this was explicitly -neglected in favour of write performance. - -7. Supports Linux, Windows, MacOS, Android, iOS, FreeBSD, DragonFly, Solaris, -OpenSolaris, OpenIndiana, NetBSD, OpenBSD and other systems compliant with -**POSIX.1-2008**. - - - -Historically, _libmdbx_ is a deeply revised and extended descendant of the amazing -[Lightning Memory-Mapped Database](https://en.wikipedia.org/wiki/Lightning_Memory-Mapped_Database). -_libmdbx_ inherits all benefits from _LMDB_, but resolves some issues and adds [a set of improvements](#improvements-beyond-lmdb). - -### MithrilDB and Future - - - -The next version is under non-public development from scratch and will be -released as **MithrilDB** and `libmithrildb` for libraries & packages. -Admittedly mythical [Mithril](https://en.wikipedia.org/wiki/Mithril) is -resembling silver but being stronger and lighter than steel. Therefore -_MithrilDB_ is a rightly relevant name. - -_MithrilDB_ is radically different from _libmdbx_ by the new database -format and API based on C++20. The goal of this revolution is to provide -a clearer and robust API, add more features and new valuable properties -of the database. All fundamental architectural problems of libmdbx/LMDB -have been solved there, but now the active development has been -suspended for top-three reasons: - -1. For now _libmdbx_ «mostly» enough for all [our products](https://www.ptsecurity.com/ww-en/products/), -and I’m busy in development of replication for scalability. -2. Waiting for fresh [Elbrus CPU](https://wiki.elbrus.ru/) of [e2k architecture](https://en.wikipedia.org/wiki/Elbrus_2000), -especially with hardware acceleration of [Streebog](https://en.wikipedia.org/wiki/Streebog) and -[Kuznyechik](https://en.wikipedia.org/wiki/Kuznyechik), which are required for Merkle tree, etc. -3. The expectation of needs and opportunities due to the wide use of NVDIMM (aka persistent memory), -modern NVMe and [Ангара](https://ru.wikipedia.org/wiki/Ангара_(интерконнект)). - -However, _MithrilDB_ will not be available for countries unfriendly to -Russia (i.e. acceded the sanctions, devil adepts and/or NATO). But it is -not yet known whether such restriction will be implemented only through -a license and support, either the source code will not be open at all. -Basically we are not inclined to allow our work to contribute to the -profit that goes to weapons that kill our relatives and friends. -NO OPTIONS. - -Nonetheless, I try not to make any promises regarding _MithrilDB_ until release. - -Contrary to _MithrilDB_, _libmdbx_ will forever free and open source. -Moreover with high-quality support whenever possible. Tu deviens -responsable pour toujours de ce que tu as apprivois. So we will continue -to comply with the original open license and the principles of -constructive cooperation, in spite of outright Github sabotage and -sanctions. I will also try to keep (not drop) Windows support, despite -it is an unused obsolete technology for us. - - - -``` -$ objdump -f -h -j .text libmdbx.so - - libmdbx.so: формат файла elf64-e2k - архитектура: elbrus-v6:64, флаги 0x00000150: - HAS_SYMS, DYNAMIC, D_PAGED - начальный адрес 0x0000000000021680 - - Разделы: - Idx Name Разм VMA LMA Фа смещ. Выр. - 10 .text 000ddd28 0000000000021680 0000000000021680 00021680 2**3 - CONTENTS, ALLOC, LOAD, READONLY, CODE - -$ cc --version - lcc:1.26.12:Jun-05-2022:e2k-v6-linux - gcc (GCC) 9.3.0 compatible -``` - ------ - -## Table of Contents -- [Characteristics](#characteristics) - - [Features](#features) - - [Limitations](#limitations) - - [Gotchas](#gotchas) - - [Comparison with other databases](#comparison-with-other-databases) - - [Improvements beyond LMDB](#improvements-beyond-lmdb) - - [History & Acknowledgments](#history) -- [Usage](#usage) - - [Building and Testing](#building-and-testing) - - [API description](#api-description) - - [Bindings](#bindings) -- [Performance comparison](#performance-comparison) - - [Integral performance](#integral-performance) - - [Read scalability](#read-scalability) - - [Sync-write mode](#sync-write-mode) - - [Lazy-write mode](#lazy-write-mode) - - [Async-write mode](#async-write-mode) - - [Cost comparison](#cost-comparison) - -# Characteristics - - - -## Features - -- Key-value data model, keys are always sorted. - -- Fully [ACID](https://en.wikipedia.org/wiki/ACID)-compliant, through to -[MVCC](https://en.wikipedia.org/wiki/Multiversion_concurrency_control) -and [CoW](https://en.wikipedia.org/wiki/Copy-on-write). - -- Multiple key-value sub-databases within a single datafile. - -- Range lookups, including range query estimation. - -- Efficient support for short fixed length keys, including native 32/64-bit integers. - -- Ultra-efficient support for [multimaps](https://en.wikipedia.org/wiki/Multimap). Multi-values sorted, searchable and iterable. Keys stored without duplication. - -- Data is [memory-mapped](https://en.wikipedia.org/wiki/Memory-mapped_file) and accessible directly/zero-copy. Traversal of database records is extremely-fast. - -- Transactions for readers and writers, ones do not block others. - -- Writes are strongly serialized. No transaction conflicts nor deadlocks. - -- Readers are [non-blocking](https://en.wikipedia.org/wiki/Non-blocking_algorithm), notwithstanding [snapshot isolation](https://en.wikipedia.org/wiki/Snapshot_isolation). - -- Nested write transactions. - -- Reads scale linearly across CPUs. - -- Continuous zero-overhead database compactification. - -- Automatic on-the-fly database size adjustment. - -- Customizable database page size. - -- `Olog(N)` cost of lookup, insert, update, and delete operations by virtue of [B+ tree characteristics](https://en.wikipedia.org/wiki/B%2B_tree#Characteristics). - -- Online hot backup. - -- Append operation for efficient bulk insertion of pre-sorted data. - -- No [WAL](https://en.wikipedia.org/wiki/Write-ahead_logging) nor any -transaction journal. No crash recovery needed. No maintenance is required. - -- No internal cache and/or memory management, all done by basic OS services. - -## Limitations - -- **Page size**: a power of 2, minimum `256` (mostly for testing), maximum `65536` bytes, default `4096` bytes. -- **Key size**: minimum `0`, maximum ≈½ pagesize (`2022` bytes for default 4K pagesize, `32742` bytes for 64K pagesize). -- **Value size**: minimum `0`, maximum `2146435072` (`0x7FF00000`) bytes for maps, ≈½ pagesize for multimaps (`2022` bytes for default 4K pagesize, `32742` bytes for 64K pagesize). -- **Write transaction size**: up to `1327217884` pages (`4.944272` TiB for default 4K pagesize, `79.108351` TiB for 64K pagesize). -- **Database size**: up to `2147483648` pages (≈`8.0` TiB for default 4K pagesize, ≈`128.0` TiB for 64K pagesize). -- **Maximum sub-databases**: `32765`. - -## Gotchas - -1. There cannot be more than one writer at a time, i.e. no more than one write transaction at a time. - -2. _libmdbx_ is based on [B+ tree](https://en.wikipedia.org/wiki/B%2B_tree), so access to database pages is mostly random. -Thus SSDs provide a significant performance boost over spinning disks for large databases. - -3. _libmdbx_ uses [shadow paging](https://en.wikipedia.org/wiki/Shadow_paging) instead of [WAL](https://en.wikipedia.org/wiki/Write-ahead_logging). -Thus syncing data to disk might be a bottleneck for write intensive workload. - -4. _libmdbx_ uses [copy-on-write](https://en.wikipedia.org/wiki/Copy-on-write) for [snapshot isolation](https://en.wikipedia.org/wiki/Snapshot_isolation) during updates, -but read transactions prevents recycling an old retired/freed pages, since it read ones. Thus altering of data during a parallel -long-lived read operation will increase the process work set, may exhaust entire free database space, -the database can grow quickly, and result in performance degradation. -Try to avoid long running read transactions. - -5. _libmdbx_ is extraordinarily fast and provides minimal overhead for data access, -so you should reconsider using brute force techniques and double check your code. -On the one hand, in the case of _libmdbx_, a simple linear search may be more profitable than complex indexes. -On the other hand, if you make something suboptimally, you can notice detrimentally only on sufficiently large data. - -## Comparison with other databases -For now please refer to [chapter of "BoltDB comparison with other -databases"](https://github.com/coreos/bbolt#comparison-with-other-databases) -which is also (mostly) applicable to _libmdbx_. - - - - - -Improvements beyond LMDB -======================== - -_libmdbx_ is superior to legendary _[LMDB](https://symas.com/lmdb/)_ in -terms of features and reliability, not inferior in performance. In -comparison to _LMDB_, _libmdbx_ make things "just work" perfectly and -out-of-the-box, not silently and catastrophically break down. The list -below is pruned down to the improvements most notable and obvious from -the user's point of view. - -## Added Features - -1. Keys could be more than 2 times longer than _LMDB_. - > For DB with default page size _libmdbx_ support keys up to 2022 bytes - > and up to 32742 bytes for 64K page size. _LMDB_ allows key size up to - > 511 bytes and may silently loses data with large values. - -2. Up to 30% faster than _LMDB_ in [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) benchmarks. - > Benchmarks of the in-[tmpfs](https://en.wikipedia.org/wiki/Tmpfs) scenarios, - > that tests the speed of the engine itself, showned that _libmdbx_ 10-20% faster than _LMDB_, - > and up to 30% faster when _libmdbx_ compiled with specific build options - > which downgrades several runtime checks to be match with LMDB behaviour. - > - > These and other results could be easily reproduced with [ioArena](https://abf.io/erthink/ioarena.git) just by `make bench-quartet` command, - > including comparisons with [RockDB](https://en.wikipedia.org/wiki/RocksDB) - > and [WiredTiger](https://en.wikipedia.org/wiki/WiredTiger). - -3. Automatic on-the-fly database size adjustment, both increment and reduction. - > _libmdbx_ manages the database size according to parameters specified - > by `mdbx_env_set_geometry()` function, - > ones include the growth step and the truncation threshold. - > - > Unfortunately, on-the-fly database size adjustment doesn't work under [Wine](https://en.wikipedia.org/wiki/Wine_(software)) - > due to its internal limitations and unimplemented functions, i.e. the `MDBX_UNABLE_EXTEND_MAPSIZE` error will be returned. - -4. Automatic continuous zero-overhead database compactification. - > During each commit _libmdbx_ merges a freeing pages which adjacent with the unallocated area - > at the end of file, and then truncates unused space when a lot enough of. - -5. The same database format for 32- and 64-bit builds. - > _libmdbx_ database format depends only on the [endianness](https://en.wikipedia.org/wiki/Endianness) but not on the [bitness](https://en.wiktionary.org/wiki/bitness). - -6. LIFO policy for Garbage Collection recycling. This can significantly increase write performance due write-back disk cache up to several times in a best case scenario. - > LIFO means that for reuse will be taken the latest becomes unused pages. - > Therefore the loop of database pages circulation becomes as short as possible. - > In other words, the set of pages, that are (over)written in memory and on disk during a series of write transactions, will be as small as possible. - > Thus creates ideal conditions for the battery-backed or flash-backed disk cache efficiency. - -7. Fast estimation of range query result volume, i.e. how many items can -be found between a `KEY1` and a `KEY2`. This is a prerequisite for build -and/or optimize query execution plans. - > _libmdbx_ performs a rough estimate based on common B-tree pages of the paths from root to corresponding keys. - -8. `mdbx_chk` utility for database integrity check. -Since version 0.9.1, the utility supports checking the database using any of the three meta pages and the ability to switch to it. - -9. Support for opening databases in the exclusive mode, including on a network share. - -10. Zero-length for keys and values. - -11. Ability to determine whether the particular data is on a dirty page -or not, that allows to avoid copy-out before updates. - -12. Extended information of whole-database, sub-databases, transactions, readers enumeration. - > _libmdbx_ provides a lot of information, including dirty and leftover pages - > for a write transaction, reading lag and holdover space for read transactions. - -13. Extended update and delete operations. - > _libmdbx_ allows one _at once_ with getting previous value - > and addressing the particular item from multi-value with the same key. - -14. Useful runtime options for tuning engine to application's requirements and use cases specific. - -15. Automated steady sync-to-disk upon several thresholds and/or timeout via cheap polling. - -16. Sequence generation and three persistent 64-bit markers. - -17. Handle-Slow-Readers callback to resolve a database full/overflow issues due to long-lived read transaction(s). - -18. Ability to determine whether the cursor is pointed to a key-value -pair, to the first, to the last, or not set to anything. - - -## Other fixes and specifics - -1. Fixed more than 10 significant errors, in particular: page leaks, -wrong sub-database statistics, segfault in several conditions, -nonoptimal page merge strategy, updating an existing record with -a change in data size (including for multimap), etc. - -2. All cursors can be reused and should be closed explicitly, -regardless ones were opened within a write or read transaction. - -3. Opening database handles are spared from race conditions and -pre-opening is not needed. - -4. Returning `MDBX_EMULTIVAL` error in case of ambiguous update or delete. - -5. Guarantee of database integrity even in asynchronous unordered write-to-disk mode. - > _libmdbx_ propose additional trade-off by `MDBX_SAFE_NOSYNC` with append-like manner for updates, - > that avoids database corruption after a system crash contrary to LMDB. - > Nevertheless, the `MDBX_UTTERLY_NOSYNC` mode is available to match LMDB's behaviour for `MDB_NOSYNC`. - -6. On **MacOS & iOS** the `fcntl(F_FULLFSYNC)` syscall is used _by -default_ to synchronize data with the disk, as this is [the only way to -guarantee data -durability](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html) -in case of power failure. Unfortunately, in scenarios with high write -intensity, the use of `F_FULLFSYNC` significantly degrades performance -compared to LMDB, where the `fsync()` syscall is used. Therefore, -_libmdbx_ allows you to override this behavior by defining the -`MDBX_OSX_SPEED_INSTEADOF_DURABILITY=1` option while build the library. - -7. On **Windows** the `LockFileEx()` syscall is used for locking, since -it allows place the database on network drives, and provides protection -against incompetent user actions (aka -[poka-yoke](https://en.wikipedia.org/wiki/Poka-yoke)). Therefore -_libmdbx_ may be a little lag in performance tests from LMDB where the -named mutexes are used. - - - - -# History - -Historically, _libmdbx_ is a deeply revised and extended descendant of the -[Lightning Memory-Mapped Database](https://en.wikipedia.org/wiki/Lightning_Memory-Mapped_Database). -At first the development was carried out within the -[ReOpenLDAP](https://web.archive.org/web/https://github.com/erthink/ReOpenLDAP) project. About a -year later _libmdbx_ was separated into a standalone project, which was -[presented at Highload++ 2015 -conference](http://www.highload.ru/2015/abstracts/1831.html). - -Since 2017 _libmdbx_ is used in [Fast Positive Tables](https://gitflic.ru/project/erthink/libfpta), -and development is funded by [Positive Technologies](https://www.ptsecurity.com). - -On 2022-04-15 the Github administration, without any warning nor -explanation, deleted _libmdbx_ along with a lot of other projects, -simultaneously blocking access for many developers. Therefore on -2022-04-21 we have migrated to a reliable trusted infrastructure. -The origin for now is at [GitFlic](https://gitflic.ru/project/erthink/libmdbx) -with backup at [ABF by ROSA Лаб](https://abf.rosalinux.ru/erthink/libmdbx). -For the same reason ~~Github~~ is blacklisted forever. - -## Acknowledgments -Howard Chu is the author of LMDB, from which -originated the _libmdbx_ in 2015. - -Martin Hedenfalk is the author of `btree.c` code, which -was used to begin development of LMDB. - - - --------------------------------------------------------------------------------- - -Usage -===== - - - -Currently, libmdbx is only available in a -[source code](https://en.wikipedia.org/wiki/Source_code) form. -Packages support for common Linux distributions is planned in the future, -since release the version 1.0. - -## Source code embedding - -_libmdbx_ provides two official ways for integration in source code form: - -1. Using an amalgamated source code which available in the [releases section](https://gitflic.ru/project/erthink/libmdbx/release) on GitFlic. - > An amalgamated source code includes all files required to build and - > use _libmdbx_, but not for testing _libmdbx_ itself. - > Beside the releases an amalgamated sources could be created any time from the original clone of git - > repository on Linux by executing `make dist`. As a result, the desired - > set of files will be formed in the `dist` subdirectory. - -2. Adding the complete source code as a `git submodule` from the [origin git repository](https://gitflic.ru/project/erthink/libmdbx) on GitFlic. - > This allows you to build as _libmdbx_ and testing tool. - > On the other hand, this way requires you to pull git tags, and use C++11 compiler for test tool. - -_**Please, avoid using any other techniques.**_ Otherwise, at least -don't ask for support and don't name such chimeras `libmdbx`. - - - -## Building and Testing - -Both amalgamated and original source code provides build through the use -[CMake](https://cmake.org/) or [GNU -Make](https://www.gnu.org/software/make/) with -[bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)). All build ways -are completely traditional and have minimal prerequirements like -`build-essential`, i.e. the non-obsolete C/C++ compiler and a -[SDK](https://en.wikipedia.org/wiki/Software_development_kit) for the -target platform. Obviously you need building tools itself, i.e. `git`, -`cmake` or GNU `make` with `bash`. For your convenience, `make help` -and `make options` are also available for listing existing targets -and build options respectively. - -The only significant specificity is that git' tags are required -to build from complete (not amalgamated) source codes. -Executing **`git fetch --tags --force --prune`** is enough to get ones, -and `--unshallow` or `--update-shallow` is required for shallow cloned case. - -So just using CMake or GNU Make in your habitual manner and feel free to -fill an issue or make pull request in the case something will be -unexpected or broken down. - -### Testing -The amalgamated source code does not contain any tests for or several reasons. -Please read [the explanation](https://libmdbx.dqdkfa.ru/dead-github/issues/214#issuecomment-870717981) and don't ask to alter this. -So for testing _libmdbx_ itself you need a full source code, i.e. the clone of a git repository, there is no option. - -The full source code of _libmdbx_ has a [`test` subdirectory](https://gitflic.ru/project/erthink/libmdbx/tree/master/test) with minimalistic test "framework". -Actually yonder is a source code of the `mdbx_test` – console utility which has a set of command-line options that allow construct and run a reasonable enough test scenarios. -This test utility is intended for _libmdbx_'s developers for testing library itself, but not for use by users. -Therefore, only basic information is provided: - - - There are few CRUD-based test cases (hill, TTL, nested, append, jitter, etc), - which can be combined to test the concurrent operations within shared database in a multi-processes environment. - This is the `basic` test scenario. - - The `Makefile` provide several self-described targets for testing: `smoke`, `test`, `check`, `memcheck`, `test-valgrind`, - `test-asan`, `test-leak`, `test-ubsan`, `cross-gcc`, `cross-qemu`, `gcc-analyzer`, `smoke-fault`, `smoke-singleprocess`, - `test-singleprocess`, 'long-test'. Please run `make --help` if doubt. - - In addition to the `mdbx_test` utility, there is the script [`long_stochastic.sh`](https://gitflic.ru/project/erthink/libmdbx/blob/master/test/long_stochastic.sh), - which calls `mdbx_test` by going through set of modes and options, with gradually increasing the number of operations and the size of transactions. - This script is used for mostly of all automatic testing, including `Makefile` targets and Continuous Integration. - - Brief information of available command-line options is available by `--help`. - However, you should dive into source code to get all, there is no option. - -Anyway, no matter how thoroughly the _libmdbx_ is tested, you should rely only on your own tests for a few reasons: - -1. Mostly of all use cases are unique. - So it is no warranty that your use case was properly tested, even the _libmdbx_'s tests engages stochastic approach. -2. If there are problems, then your test on the one hand will help to verify whether you are using _libmdbx_ correctly, - on the other hand it will allow to reproduce the problem and insure against regression in a future. -3. Actually you should rely on than you checked by yourself or take a risk. - - -### Common important details - -#### Build reproducibility -By default _libmdbx_ track build time via `MDBX_BUILD_TIMESTAMP` build option and macro. -So for a [reproducible builds](https://en.wikipedia.org/wiki/Reproducible_builds) you should predefine/override it to known fixed string value. -For instance: - - - for reproducible build with make: `make MDBX_BUILD_TIMESTAMP=unknown ` ... - - or during configure by CMake: `cmake -DMDBX_BUILD_TIMESTAMP:STRING=unknown ` ... - -Of course, in addition to this, your toolchain must ensure the reproducibility of builds. -For more information please refer to [reproducible-builds.org](https://reproducible-builds.org/). - -#### Containers -There are no special traits nor quirks if you use libmdbx ONLY inside the single container. -But in a cross-container cases or with a host-container(s) mix the two major things MUST be -guaranteed: - -1. Coherence of memory mapping content and unified page cache inside OS kernel for host and all container(s) operated with a DB. -Basically this means must be only a single physical copy of each memory mapped DB' page in the system memory. - -2. Uniqueness of [PID](https://en.wikipedia.org/wiki/Process_identifier) values and/or a common space for ones: - - for POSIX systems: PID uniqueness for all processes operated with a DB. - I.e. the `--pid=host` is required for run DB-aware processes inside Docker, - either without host interaction a `--pid=container:` with the same name/id. - - for non-POSIX (i.e. Windows) systems: inter-visibility of processes handles. - I.e. the `OpenProcess(SYNCHRONIZE, ..., PID)` must return reasonable error, - including `ERROR_ACCESS_DENIED`, - but not the `ERROR_INVALID_PARAMETER` as for an invalid/non-existent PID. - -#### DSO/DLL unloading and destructors of Thread-Local-Storage objects -When building _libmdbx_ as a shared library or use static _libmdbx_ as a -part of another dynamic library, it is advisable to make sure that your -system ensures the correctness of the call destructors of -Thread-Local-Storage objects when unloading dynamic libraries. - -If this is not the case, then unloading a dynamic-link library with -_libmdbx_ code inside, can result in either a resource leak or a crash -due to calling destructors from an already unloaded DSO/DLL object. The -problem can only manifest in a multithreaded application, which makes -the unloading of shared dynamic libraries with _libmdbx_ code inside, -after using _libmdbx_. It is known that TLS-destructors are properly -maintained in the following cases: - -- On all modern versions of Windows (Windows 7 and later). - -- On systems with the -[`__cxa_thread_atexit_impl()`](https://sourceware.org/glibc/wiki/Destructor%20support%20for%20thread_local%20variables) -function in the standard C library, including systems with GNU libc -version 2.18 and later. - -- On systems with libpthread/ntpl from GNU libc with bug fixes -[#21031](https://sourceware.org/bugzilla/show_bug.cgi?id=21031) and -[#21032](https://sourceware.org/bugzilla/show_bug.cgi?id=21032), or -where there are no similar bugs in the pthreads implementation. - -### Linux and other platforms with GNU Make -To build the library it is enough to execute `make all` in the directory -of source code, and `make check` to execute the basic tests. - -If the `make` installed on the system is not GNU Make, there will be a -lot of errors from make when trying to build. In this case, perhaps you -should use `gmake` instead of `make`, or even `gnu-make`, etc. - -### FreeBSD and related platforms -As a rule on BSD and it derivatives the default is to use Berkeley Make and -[Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) is not installed. - -So you need to install the required components: GNU Make, Bash, C and C++ -compilers compatible with GCC or CLANG. After that, to build the -library, it is enough to execute `gmake all` (or `make all`) in the -directory with source code, and `gmake check` (or `make check`) to run -the basic tests. - -### Windows -For build _libmdbx_ on Windows the _original_ CMake and [Microsoft Visual -Studio 2019](https://en.wikipedia.org/wiki/Microsoft_Visual_Studio) are -recommended. Please use the recent versions of CMake, Visual Studio and Windows -SDK to avoid troubles with C11 support and `alignas()` feature. - -For build by MinGW the 10.2 or recent version coupled with a modern CMake are required. -So it is recommended to use [chocolatey](https://chocolatey.org/) to install and/or update the ones. - -Another ways to build is potentially possible but not supported and will not. -The `CMakeLists.txt` or `GNUMakefile` scripts will probably need to be modified accordingly. -Using other methods do not forget to add the `ntdll.lib` to linking. - -It should be noted that in _libmdbx_ was efforts to avoid -runtime dependencies from CRT and other MSVC libraries. -For this is enough to pass the `-DMDBX_WITHOUT_MSVC_CRT:BOOL=ON` option -during configure by CMake. - -An example of running a basic test script can be found in the -[CI-script](appveyor.yml) for [AppVeyor](https://www.appveyor.com/). To -run the [long stochastic test scenario](test/long_stochastic.sh), -[bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) is required, and -such testing is recommended with placing the test data on the -[RAM-disk](https://en.wikipedia.org/wiki/RAM_drive). - -### Windows Subsystem for Linux -_libmdbx_ could be used in [WSL2](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux#WSL_2) -but NOT in [WSL1](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux#WSL_1) environment. -This is a consequence of the fundamental shortcomings of _WSL1_ and cannot be fixed. -To avoid data loss, _libmdbx_ returns the `ENOLCK` (37, "No record locks available") -error when opening the database in a _WSL1_ environment. - -### MacOS -Current [native build tools](https://en.wikipedia.org/wiki/Xcode) for -MacOS include GNU Make, CLANG and an outdated version of Bash. -Therefore, to build the library, it is enough to run `make all` in the -directory with source code, and run `make check` to execute the base -tests. If something goes wrong, it is recommended to install -[Homebrew](https://brew.sh/) and try again. - -To run the [long stochastic test scenario](test/long_stochastic.sh), you -will need to install the current (not outdated) version of -[Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)). To do this, we -recommend that you install [Homebrew](https://brew.sh/) and then execute -`brew install bash`. - -### Android -We recommend using CMake to build _libmdbx_ for Android. -Please refer to the [official guide](https://developer.android.com/studio/projects/add-native-code). - -### iOS -To build _libmdbx_ for iOS, we recommend using CMake with the -["toolchain file"](https://cmake.org/cmake/help/latest/variable/CMAKE_TOOLCHAIN_FILE.html) -from the [ios-cmake](https://github.com/leetal/ios-cmake) project. - - - -## API description - -Please refer to the online [_libmdbx_ API reference](https://libmdbx.dqdkfa.ru/docs) -and/or see the [mdbx.h++](mdbx.h%2B%2B) and [mdbx.h](mdbx.h) headers. - - - -Bindings -======== - -| Runtime | Repo | Author | -| ------- | ------ | ------ | -| Scala | [mdbx4s](https://github.com/david-bouyssie/mdbx4s) | [David Bouyssié](https://github.com/david-bouyssie) | -| Haskell | [libmdbx-hs](https://hackage.haskell.org/package/libmdbx) | [Francisco Vallarino](https://github.com/fjvallarino) | -| NodeJS, [Deno](https://deno.land/) | [lmdbx-js](https://github.com/kriszyp/lmdbx-js) | [Kris Zyp](https://github.com/kriszyp/) -| NodeJS | [node-mdbx](https://www.npmjs.com/package/node-mdbx/) | [Сергей Федотов](mailto:sergey.fedotov@corp.mail.ru) | -| Ruby | [ruby-mdbx](https://rubygems.org/gems/mdbx/) | [Mahlon E. Smith](https://github.com/mahlonsmith) | -| Go | [mdbx-go](https://github.com/torquem-ch/mdbx-go) | [Alex Sharov](https://github.com/AskAlexSharov) | -| [Nim](https://en.wikipedia.org/wiki/Nim_(programming_language)) | [NimDBX](https://github.com/snej/nimdbx) | [Jens Alfke](https://github.com/snej) -| Lua | [lua-libmdbx](https://github.com/mah0x211/lua-libmdbx) | [Masatoshi Fukunaga](https://github.com/mah0x211) | -| Rust | [libmdbx-rs](https://github.com/vorot93/libmdbx-rs) | [Artem Vorotnikov](https://github.com/vorot93) | -| Rust | [mdbx](https://crates.io/crates/mdbx) | [gcxfd](https://github.com/gcxfd) | -| Java | [mdbxjni](https://github.com/castortech/mdbxjni) | [Castor Technologies](https://castortech.com/) | -| Python (draft) | [python-bindings](https://libmdbx.dqdkfa.ru/dead-github/commits/python-bindings) branch | [Noel Kuntze](https://github.com/Thermi) -| .NET (obsolete) | [mdbx.NET](https://github.com/wangjia184/mdbx.NET) | [Jerry Wang](https://github.com/wangjia184) | - - - --------------------------------------------------------------------------------- - - - -Performance comparison -====================== - -All benchmarks were done in 2015 by [IOArena](https://abf.io/erthink/ioarena.git) -and multiple [scripts](https://github.com/pmwkaa/ioarena/tree/HL%2B%2B2015) -runs on Lenovo Carbon-2 laptop, i7-4600U 2.1 GHz (2 physical cores, 4 HyperThreading cores), 8 Gb RAM, -SSD SAMSUNG MZNTD512HAGL-000L1 (DXT23L0Q) 512 Gb. - -## Integral performance - -Here showed sum of performance metrics in 3 benchmarks: - - - Read/Search on the machine with 4 logical CPUs in HyperThreading mode (i.e. actually 2 physical CPU cores); - - - Transactions with [CRUD](https://en.wikipedia.org/wiki/CRUD) - operations in sync-write mode (fdatasync is called after each - transaction); - - - Transactions with [CRUD](https://en.wikipedia.org/wiki/CRUD) - operations in lazy-write mode (moment to sync data to persistent storage - is decided by OS). - -*Reasons why asynchronous mode isn't benchmarked here:* - - 1. It doesn't make sense as it has to be done with DB engines, oriented - for keeping data in memory e.g. [Tarantool](https://tarantool.io/), - [Redis](https://redis.io/)), etc. - - 2. Performance gap is too high to compare in any meaningful way. - -![Comparison #1: Integral Performance](https://libmdbx.dqdkfa.ru/img/perf-slide-1.png) - --------------------------------------------------------------------------------- - -## Read Scalability - -Summary performance with concurrent read/search queries in 1-2-4-8 -threads on the machine with 4 logical CPUs in HyperThreading mode (i.e. actually 2 physical CPU cores). - -![Comparison #2: Read Scalability](https://libmdbx.dqdkfa.ru/img/perf-slide-2.png) - --------------------------------------------------------------------------------- - -## Sync-write mode - - - Linear scale on left and dark rectangles mean arithmetic mean - transactions per second; - - - Logarithmic scale on right is in seconds and yellow intervals mean - execution time of transactions. Each interval shows minimal and maximum - execution time, cross marks standard deviation. - -**10,000 transactions in sync-write mode**. In case of a crash all data -is consistent and conforms to the last successful transaction. The -[fdatasync](https://linux.die.net/man/2/fdatasync) syscall is used after -each write transaction in this mode. - -In the benchmark each transaction contains combined CRUD operations (2 -inserts, 1 read, 1 update, 1 delete). Benchmark starts on an empty database -and after full run the database contains 10,000 small key-value records. - -![Comparison #3: Sync-write mode](https://libmdbx.dqdkfa.ru/img/perf-slide-3.png) - --------------------------------------------------------------------------------- - -## Lazy-write mode - - - Linear scale on left and dark rectangles mean arithmetic mean of - thousands transactions per second; - - - Logarithmic scale on right in seconds and yellow intervals mean - execution time of transactions. Each interval shows minimal and maximum - execution time, cross marks standard deviation. - -**100,000 transactions in lazy-write mode**. In case of a crash all data -is consistent and conforms to the one of last successful transactions, but -transactions after it will be lost. Other DB engines use -[WAL](https://en.wikipedia.org/wiki/Write-ahead_logging) or transaction -journal for that, which in turn depends on order of operations in the -journaled filesystem. _libmdbx_ doesn't use WAL and hands I/O operations -to filesystem and OS kernel (mmap). - -In the benchmark each transaction contains combined CRUD operations (2 -inserts, 1 read, 1 update, 1 delete). Benchmark starts on an empty database -and after full run the database contains 100,000 small key-value -records. - - -![Comparison #4: Lazy-write mode](https://libmdbx.dqdkfa.ru/img/perf-slide-4.png) - --------------------------------------------------------------------------------- - -## Async-write mode - - - Linear scale on left and dark rectangles mean arithmetic mean of - thousands transactions per second; - - - Logarithmic scale on right in seconds and yellow intervals mean - execution time of transactions. Each interval shows minimal and maximum - execution time, cross marks standard deviation. - -**1,000,000 transactions in async-write mode**. -In case of a crash all data is consistent and conforms to the one of last successful transactions, -but lost transaction count is much higher than in -lazy-write mode. All DB engines in this mode do as little writes as -possible on persistent storage. _libmdbx_ uses -[msync(MS_ASYNC)](https://linux.die.net/man/2/msync) in this mode. - -In the benchmark each transaction contains combined CRUD operations (2 -inserts, 1 read, 1 update, 1 delete). Benchmark starts on an empty database -and after full run the database contains 10,000 small key-value records. - -![Comparison #5: Async-write mode](https://libmdbx.dqdkfa.ru/img/perf-slide-5.png) - --------------------------------------------------------------------------------- - -## Cost comparison - -Summary of used resources during lazy-write mode benchmarks: - - - Read and write IOPs; - - - Sum of user CPU time and sys CPU time; - - - Used space on persistent storage after the test and closed DB, but not - waiting for the end of all internal housekeeping operations (LSM - compactification, etc). - -_ForestDB_ is excluded because benchmark showed it's resource -consumption for each resource (CPU, IOPs) much higher than other engines -which prevents to meaningfully compare it with them. - -All benchmark data is gathered by -[getrusage()](http://man7.org/linux/man-pages/man2/getrusage.2.html) -syscall and by scanning the data directory. - -![Comparison #6: Cost comparison](https://libmdbx.dqdkfa.ru/img/perf-slide-6.png) - - diff --git a/docs/crates/db.md b/docs/crates/db.md index 79f93b1ef..58729fc14 100644 --- a/docs/crates/db.md +++ b/docs/crates/db.md @@ -8,7 +8,7 @@ The database is a central component to Reth, enabling persistent storage for dat Within Reth, the database is organized via "tables". A table is any struct that implements the `Table` trait. -[File: crates/storage/db/src/abstraction/table.rs](https://github.com/paradigmxyz/reth/blob/main/crates/storage/db/src/abstraction/table.rs#L56-L65) +[File: crates/storage/db/src/abstraction/table.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/storage/db/src/abstraction/table.rs#L55-L82) ```rust ignore pub trait Table: Send + Sync + Debug + 'static { @@ -23,7 +23,7 @@ pub trait Table: Send + Sync + Debug + 'static { } //--snip-- -pub trait Key: Encode + Decode + Ord {} +pub trait Key: Encode + Decode + Ord + Clone + Serialize + for<'a> Deserialize<'a> {} //--snip-- pub trait Value: Compress + Decompress + Serialize {} @@ -32,38 +32,42 @@ pub trait Value: Compress + Decompress + Serialize {} The `Table` trait has two generic values, `Key` and `Value`, which need to implement the `Key` and `Value` traits, respectively. The `Encode` trait is responsible for transforming data into bytes so it can be stored in the database, while the `Decode` trait transforms the bytes back into its original form. Similarly, the `Compress` and `Decompress` traits transform the data to and from a compressed format when storing or reading data from the database. -There are many tables within the node, all used to store different types of data from `Headers` to `Transactions` and more. Below is a list of all of the tables. You can follow [this link](https://github.com/paradigmxyz/reth/blob/main/crates/storage/db/src/tables/mod.rs#L36) if you would like to see the table definitions for any of the tables below. +There are many tables within the node, all used to store different types of data from `Headers` to `Transactions` and more. Below is a list of all of the tables. You can follow [this link](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/storage/db/src/tables/mod.rs#L161-L188) if you would like to see the table definitions for any of the tables below. - CanonicalHeaders - HeaderTD - HeaderNumbers - Headers -- BlockBodies +- BlockBodyIndices - BlockOmmers +- BlockWithdrawals +- TransactionBlock - Transactions - TxHashNumber - Receipts -- Logs - PlainAccountState - PlainStorageState - Bytecodes -- BlockTransitionIndex -- TxTransitionIndex - AccountHistory - StorageHistory - AccountChangeSet - StorageChangeSet +- HashedAccount +- HashedStorage +- AccountsTrie +- StoragesTrie - TxSenders -- Config - SyncStage +- SyncStageProgress +- PruneCheckpoints
## Database -Reth's database design revolves around it's main [Database trait](https://github.com/paradigmxyz/reth/blob/0d9b9a392d4196793736522f3fc2ac804991b45d/crates/interfaces/src/db/mod.rs#L33), which takes advantage of [generic associated types](https://blog.rust-lang.org/2022/10/28/gats-stabilization.html) and [a few design tricks](https://sabrinajewson.org/blog/the-better-alternative-to-lifetime-gats#the-better-gats) to implement the database's functionality across many types. Let's take a quick look at the `Database` trait and how it works. +Reth's database design revolves around it's main [Database trait](https://github.com/paradigmxyz/reth/blob/eaca2a4a7fbbdc2f5cd15eab9a8a18ede1891bda/crates/storage/db/src/abstraction/database.rs#L21), which takes advantage of [generic associated types](https://blog.rust-lang.org/2022/10/28/gats-stabilization.html) and [a few design tricks](https://sabrinajewson.org/blog/the-better-alternative-to-lifetime-gats#the-better-gats) to implement the database's functionality across many types. Let's take a quick look at the `Database` trait and how it works. -[File: crates/storage/db/src/abstraction/database.rs](https://github.com/paradigmxyz/reth/blob/main/crates/storage/db/src/abstraction/database.rs#L19) +[File: crates/storage/db/src/abstraction/database.rs](https://github.com/paradigmxyz/reth/blob/eaca2a4a7fbbdc2f5cd15eab9a8a18ede1891bda/crates/storage/db/src/abstraction/database.rs#L21) ```rust ignore /// Main Database trait that spawns transactions to be executed. diff --git a/docs/crates/discv4.md b/docs/crates/discv4.md index fe37cf463..45ab4a52f 100644 --- a/docs/crates/discv4.md +++ b/docs/crates/discv4.md @@ -5,16 +5,20 @@ The `discv4` crate plays an important role in Reth, enabling discovery of other ## Starting the Node Discovery Protocol As mentioned in the network and stages chapters, when the node is first started up, the `node::Command::execute()` function is called, which initializes the node and starts to run the Reth pipeline. Throughout the initialization of the node, there are many processes that are are started. One of the processes that is initialized is the p2p network which starts the node discovery protocol amongst other tasks. -[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/main/bin/reth/src/node/mod.rs#L95) +[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/bin/reth/src/node/mod.rs#L314-L322) ```rust ignore pub async fn execute(&self) -> eyre::Result<()> { //--snip-- - let network = config - .network_config(db.clone(), chain_id, genesis_hash, self.network.disable_discovery) - .start_network() - .await?; + let network = self + .start_network( + network_config, + &ctx.task_executor, + transaction_pool.clone(), + default_peers_path, + ) + .await?; - info!(peer_id = ?network.peer_id(), local_addr = %network.local_addr(), "Started p2p networking"); + info!(target: "reth::cli", peer_id = %network.peer_id(), local_addr = %network.local_addr(), "Connected to P2P network"); //--snip-- } @@ -22,7 +26,7 @@ As mentioned in the network and stages chapters, when the node is first started During this process, a new `NetworkManager` is created through the `NetworkManager::new()` function, which starts the discovery protocol through a handful of newly spawned tasks. Lets take a look at how this actually works under the hood. -[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/manager.rs#L147) +[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/manager.rs#L89) ```rust ignore impl NetworkManager where @@ -37,6 +41,7 @@ where mut discovery_v4_config, discovery_addr, boot_nodes, + dns_discovery_config, //--snip-- .. } = config; @@ -50,16 +55,18 @@ where disc_config }); - let discovery = Discovery::new(discovery_addr, secret_key, discovery_v4_config).await?; + let discovery = + Discovery::new(discovery_addr, secret_key, discovery_v4_config, dns_discovery_config) + .await?; //--snip-- } } ``` -First, the `NetworkConfig` is deconstructed and the `disc_config` is updated to merge configured [bootstrap nodes](https://github.com/paradigmxyz/reth/blob/main/crates/net/discv4/src/bootnodes.rs#L8) and add the `forkid` to adhere to [EIP 868](https://eips.ethereum.org/EIPS/eip-868). This updated configuration variable is then passed into the `Discovery::new()` function. Note that `Discovery` is a catch all for all discovery services, which include discv4, DNS discovery and others in the future. +First, the `NetworkConfig` is deconstructed and the `disc_config` is updated to merge configured [bootstrap nodes](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/primitives/src/net.rs#L120-L151) and add the `forkid` to adhere to [EIP 868](https://eips.ethereum.org/EIPS/eip-868). This updated configuration variable is then passed into the `Discovery::new()` function. Note that `Discovery` is a catch all for all discovery services, which include discv4, DNS discovery and others in the future. -[File: crates/net/network/src/discovery.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/discovery.rs#L51) +[File: crates/net/network/src/discovery.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/discovery.rs#L53) ```rust ignore impl Discovery { /// Spawns the discovery service. @@ -70,6 +77,7 @@ impl Discovery { discovery_addr: SocketAddr, sk: SecretKey, discv4_config: Option, + dns_discovery_config: Option, ) -> Result { let local_enr = NodeRecord::from_secret_key(discovery_addr, &sk); @@ -86,6 +94,20 @@ impl Discovery { (None, None, None) }; + // setup DNS discovery + let (_dns_discovery, dns_discovery_updates, _dns_disc_service) = + if let Some(dns_config) = dns_discovery_config { + let (mut service, dns_disc) = DnsDiscoveryService::new_pair( + Arc::new(DnsResolver::from_system_conf()?), + dns_config, + ); + let dns_discovery_updates = service.node_record_stream(); + let dns_disc_service = service.spawn(); + (Some(dns_disc), Some(dns_discovery_updates), Some(dns_disc_service)) + } else { + (None, None, None) + }; + Ok(Self { local_enr, discv4, diff --git a/docs/crates/eth-wire.md b/docs/crates/eth-wire.md index 0c216644f..0270668d3 100644 --- a/docs/crates/eth-wire.md +++ b/docs/crates/eth-wire.md @@ -12,7 +12,7 @@ This crate can be thought of as having 2 components: ## Types The most basic Eth-wire type is an `ProtocolMessage`. It describes all messages that reth can send/receive. -[File: crates/net/eth-wire/src/types/message.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/types/message.rs) +[File: crates/net/eth-wire/src/types/message.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/types/message.rs) ```rust, ignore /// An `eth` protocol message, containing a message ID and payload. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -50,7 +50,7 @@ pub enum EthMessageID { Messages can either be broadcast to the network, or can be a request/response message to a single peer. This 2nd type of message is described using a `RequestPair` struct, which is simply a concatenation of the underlying message with a request id. -[File: crates/net/eth-wire/src/types/message.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/types/message.rs) +[File: crates/net/eth-wire/src/types/message.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/types/message.rs) ```rust, ignore #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RequestPair { @@ -62,7 +62,7 @@ pub struct RequestPair { Every `Ethmessage` has a correspoding rust struct which implements the `Encodable` and `Decodable` traits. These traits are defined as follows: -[Crate: crates/common/rlp](https://github.com/paradigmxyz/reth/blob/main/crates/common/rlp) +[Crate: crates/rlp](https://github.com/paradigmxyz/reth/tree/1563506aea09049a85e5cc72c2894f3f7a371581/crates/rlp) ```rust, ignore pub trait Decodable: Sized { fn decode(buf: &mut &[u8]) -> Result; @@ -93,7 +93,7 @@ The items in the list are transactions in the format described in the main Ether In reth, this is represented as: -[File: crates/net/eth-wire/src/types/broadcast.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/types/broadcast.rs) +[File: crates/net/eth-wire/src/types/broadcast.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/types/broadcast.rs) ```rust,ignore pub struct Transactions( /// New transactions for the peer to include in its mempool. @@ -103,7 +103,7 @@ pub struct Transactions( And the corresponding trait implementations are present in the primitives crate. -[File: crates/primitives/src/transaction/mod.rs](https://github.com/paradigmxyz/reth/blob/main/crates/primitives/src/transaction/mod.rs) +[File: crates/primitives/src/transaction/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/primitives/src/transaction/mod.rs) ```rust, ignore #[main_codec] #[derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Deref, Default)] @@ -131,7 +131,7 @@ impl Decodable for TransactionSigned { // Implementation omitted for brevity //... } - +} ``` Now that we know how the types work, let's take a look at how these are utilized in the network. @@ -146,7 +146,7 @@ The lowest level stream to communicate with other peers is the P2P stream. It ta Decompression/Compression of bytes is done with snappy algorithm ([EIP 706](https://eips.ethereum.org/EIPS/eip-706)) using the external `snap` crate. -[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/p2pstream.rs) +[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/p2pstream.rs) ```rust,ignore #[pin_project] pub struct P2PStream { @@ -164,7 +164,7 @@ pub struct P2PStream { To manage pinging, an instance of the `Pinger` struct is used. This is a state machine which keeps track of how many pings we have sent/received and the timeouts associated with them. -[File: crates/net/eth-wire/src/pinger.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/pinger.rs) +[File: crates/net/eth-wire/src/pinger.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/pinger.rs) ```rust,ignore #[derive(Debug)] pub(crate) struct Pinger { @@ -190,7 +190,7 @@ pub(crate) enum PingState { State transitions are then implemented like a future, with the `poll_ping` function advancing the state of the pinger. -[File: crates/net/eth-wire/src/pinger.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/pinger.rs) +[File: crates/net/eth-wire/src/pinger.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/pinger.rs) ```rust, ignore pub(crate) fn poll_ping( &mut self, @@ -218,12 +218,12 @@ pub(crate) fn poll_ping( ``` ### Sending and receiving data -To send and recieve data, the P2PStream itself is a future which implemenents the `Stream` and `Sink` traits from the `futures` crate. +To send and receive data, the P2PStream itself is a future which implements the `Stream` and `Sink` traits from the `futures` crate. For the `Stream` trait, the `inner` stream is polled, decompressed and returned. Most of the code is just error handling and is omitted here for clarity. -[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/p2pstream.rs) +[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/p2pstream.rs) ```rust,ignore impl Stream for P2PStream { @@ -250,7 +250,7 @@ impl Stream for P2PStream { Similarly, for the `Sink` trait, we do the reverse, compressing and sending data out to the `inner` stream. The important functions in this trait are shown below. -[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/p2pstream.rs) +[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/p2pstream.rs) ```rust, ignore impl Sink for P2PStream { fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> { @@ -287,7 +287,7 @@ impl Sink for P2PStream { ## EthStream The EthStream is very simple, it does not keep track of any state, it simply wraps the P2Pstream. -[File: crates/net/eth-wire/src/ethstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/ethstream.rs) +[File: crates/net/eth-wire/src/ethstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/ethstream.rs) ```rust,ignore #[pin_project] pub struct EthStream { @@ -298,7 +298,7 @@ pub struct EthStream { EthStream's only job is to perform the RLP decoding/encoding, using the `ProtocolMessage::decode()` and `ProtocolMessage::encode()` functions we looked at earlier. -[File: crates/net/eth-wire/src/ethstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/ethstream.rs) +[File: crates/net/eth-wire/src/ethstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/ethstream.rs) ```rust,ignore impl Stream for EthStream { // ... @@ -341,7 +341,7 @@ To perform these, reth has special `Unauthed` versions of streams described abov The `UnauthedP2Pstream` does the `Hello` handshake and returns a `P2PStream`. -[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/p2pstream.rs) +[File: crates/net/eth-wire/src/p2pstream.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/p2pstream.rs) ```rust, ignore #[pin_project] pub struct UnauthedP2PStream { @@ -370,6 +370,6 @@ impl UnauthedP2PStream { } ``` -Similary, UnauthedEthStream does the `Status` handshake and returns an `EthStream`. The code is [here](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/ethstream.rs) +Similarly, UnauthedEthStream does the `Status` handshake and returns an `EthStream`. The code is [here](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/ethstream.rs) diff --git a/docs/crates/network.md b/docs/crates/network.md index f78a5f5d3..edfa3515b 100644 --- a/docs/crates/network.md +++ b/docs/crates/network.md @@ -33,7 +33,7 @@ The `"node"` CLI command, used to run the node itself, does the following at a h Steps 5-6 are of interest to us as they consume items from the `network` crate: -[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/main/bin/reth/src/node/mod.rs) +[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/bin/reth/src/node/mod.rs) ```rust,ignore let network = start_network(network_config(db.clone(), chain_id, genesis_hash)).await?; @@ -84,7 +84,7 @@ pipeline.run(db.clone()).await?; Let's begin by taking a look at the line where the network is started, with the call, unsurprisingly, to `start_network`. Sounds important, doesn't it? -[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/main/bin/reth/src/node/mod.rs) +[File: bin/reth/src/node/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/bin/reth/src/node/mod.rs) ```rust,ignore async fn start_network(config: NetworkConfig) -> Result where @@ -107,7 +107,7 @@ It gets the handles for the network management, transactions, and ETH requests t The `NetworkManager::builder` constructor requires a `NetworkConfig` struct to be passed in as a parameter, which can be used as the main entrypoint for setting up the entire network layer: -[File: crates/net/network/src/config.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/config.rs) +[File: crates/net/network/src/config.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/config.rs) ```rust,ignore pub struct NetworkConfig { /// The client type that can interact with the chain. @@ -152,7 +152,7 @@ pub struct NetworkConfig { The discovery task progresses as the network management task is polled, handling events regarding peer management through the `Swarm` struct which is stored as a field on the `NetworkManager`: -[File: crates/net/network/src/swarm.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/swarm.rs) +[File: crates/net/network/src/swarm.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/swarm.rs) ```rust,ignore pub(crate) struct Swarm { /// Listens for new incoming connections. @@ -180,7 +180,7 @@ Let's walk through how each is implemented, and then apply that knowledge to und The `NetworkHandle` struct is a client for the network management task that can be shared across threads. It wraps an `Arc` around the `NetworkInner` struct, defined as follows: -[File: crates/net/network/src/network.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/network.rs) +[File: crates/net/network/src/network.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/network.rs) ```rust,ignore struct NetworkInner { /// Number of active peer sessions the node's currently handling. @@ -200,7 +200,7 @@ struct NetworkInner { The field of note here is `to_manager_tx`, which is a handle that can be used to send messages in a channel to an instance of the `NetworkManager` struct. -[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/manager.rs) +[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/manager.rs) ```rust,ignore pub struct NetworkManager { /// The type that manages the actual network part, which includes connections. @@ -235,7 +235,7 @@ While the `NetworkManager` is meant to be spawned as a standalone [`tokio::task` In the pipeline, the `NetworkHandle` is used to instantiate the `FetchClient` - which we'll get into next - and is used in the `HeaderStage` to update the node's ["status"](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#status-0x00) (record the total difficulty, hash, and height of the last processed block). -[File: crates/stages/src/stages/headers.rs](https://github.com/paradigmxyz/reth/blob/main/crates/stages/src/stages/headers.rs) +[File: crates/stages/src/stages/headers.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/stages/src/stages/headers.rs) ```rust,ignore async fn update_head( &self, @@ -255,7 +255,7 @@ Now that we have some understanding about the internals of the network managemen The `FetchClient` struct, similar to `NetworkHandle`, can be shared across threads, and is a client for fetching data from the network. It's a fairly lightweight struct: -[File: crates/net/network/src/fetch/client.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/fetch/client.rs) +[File: crates/net/network/src/fetch/client.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/fetch/client.rs) ```rust,ignore pub struct FetchClient { /// Sender half of the request channel. @@ -271,7 +271,7 @@ The `request_tx` field is a handle to a channel that can be used to send request The fields `request_tx` and `peers_handle` are cloned off of the `StateFetcher` struct when instantiating the `FetchClient`, which is the lower-level struct responsible for managing data fetching operations over the network: -[File: crates/net/network/src/fetch/mod.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/fetch/mod.rs) +[File: crates/net/network/src/fetch/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/fetch/mod.rs) ```rust,ignore pub struct StateFetcher { /// Currently active [`GetBlockHeaders`] requests @@ -295,7 +295,7 @@ pub struct StateFetcher { This struct itself is nested deeply within the `NetworkManager`: its `Swarm` struct (shown earlier in the chapter) contains a `NetworkState` struct that has the `StateFetcher` as a field: -[File: crates/net/network/src/state.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/state.rs) +[File: crates/net/network/src/state.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/state.rs) ```rust,ignore pub struct NetworkState { /// All active peers and their state. @@ -322,7 +322,7 @@ pub struct NetworkState { The `FetchClient` implements the `HeadersClient` and `BodiesClient` traits, defining the functionality to get headers and block bodies from available peers. -[File: crates/net/network/src/fetch/client.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/fetch/client.rs) +[File: crates/net/network/src/fetch/client.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/fetch/client.rs) ```rust,ignore impl HeadersClient for FetchClient { /// Sends a `GetBlockHeaders` request to an available peer. @@ -346,7 +346,7 @@ This functionality is used in the `HeaderStage` and `BodyStage`, respectively. In the pipeline used by the main Reth binary, the `HeaderStage` uses a `ReverseHeadersDownloader` to stream headers from the network: -[File: crates/net/downloaders/src/headers/linear.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/downloaders/src/headers/linear.rs) +[File: crates/net/downloaders/src/headers/reverse_headers.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/downloaders/src/headers/reverse_headers.rs) ```rust,ignore pub struct ReverseHeadersDownloader { /// The consensus client @@ -362,7 +362,7 @@ pub struct ReverseHeadersDownloader { A `FetchClient` is passed in to the `client` field, and the `get_headers` method it implements gets used when polling the stream created by the `ReverseHeadersDownloader` in the `execute` method of the `HeaderStage`. -[File: crates/net/downloaders/src/headers/linear.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/downloaders/src/headers/linear.rs) +[File: crates/net/downloaders/src/headers/reverse_headers.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/downloaders/src/headers/reverse_headers.rs) ```rust,ignore fn get_or_init_fut(&mut self) -> HeadersRequestFuture { match self.request.take() { @@ -388,7 +388,7 @@ fn get_or_init_fut(&mut self) -> HeadersRequestFuture { In the `BodyStage` configured by the main binary, a `BodiesDownloader` is used: -[File: crates/net/downloaders/src/bodies/concurrent.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/downloaders/src/bodies/concurrent.rs) +[File: crates/net/downloaders/src/bodies/bodies.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/downloaders/src/bodies/bodies.rs) ```rust,ignore pub struct BodiesDownloader { /// The bodies client @@ -406,7 +406,7 @@ pub struct BodiesDownloader { Here, similarly, a `FetchClient` is passed in to the `client` field, and the `get_block_bodies` method it implements is used when constructing the stream created by the `BodiesDownloader` in the `execute` method of the `BodyStage`. -[File: crates/net/downloaders/src/bodies/concurrent.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/downloaders/src/bodies/concurrent.rs) +[File: crates/net/downloaders/src/bodies/bodies.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/downloaders/src/bodies/bodies.rs) ```rust,ignore async fn fetch_bodies( &self, @@ -425,7 +425,7 @@ When `FetchClient.get_headers` or `FetchClient.get_block_bodies` is called, thos Every time the `StateFetcher` is polled, it finds the next idle peer available to service the current request (for either a block header, or a block body). In this context, "idle" means any peer that is not currently handling a request from the node: -[File: crates/net/network/src/fetch/mod.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/fetch/mod.rs) +[File: crates/net/network/src/fetch/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/fetch/mod.rs) ```rust,ignore /// Returns the next action to return fn poll_action(&mut self) -> PollAction { @@ -455,7 +455,7 @@ The ETH requests task serves _incoming_ requests related to blocks in the [`eth` Similar to the network management task, it's implemented as an endless future, but it is meant to run as a background task (on a standalone `tokio::task`) and not to be interacted with directly from the pipeline. It's represented by the following `EthRequestHandler` struct: -[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/eth_requests.rs) +[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/eth_requests.rs) ```rust,ignore pub struct EthRequestHandler { /// The client type that can interact with the chain. @@ -480,7 +480,7 @@ As the `NetworkManager` is polled and listens for events from peers passed throu Being an endless future, the core of the ETH requests task's functionality is in its `poll` method implementation. As the `EthRequestHandler` is polled, it listens for any ETH requests coming through the channel, and handles them accordingly. At the time of writing, the ETH requests task can handle the [`GetBlockHeaders`](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#getblockheaders-0x03) and [`GetBlockBodies`](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#getblockbodies-0x05) requests. -[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/eth_requests.rs) +[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/eth_requests.rs) ```rust,ignore fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); @@ -506,7 +506,7 @@ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { The handling of these requests is fairly straightforward. The `GetBlockHeaders` payload is the following: -[File: crates/net/eth-wire/src/types/blocks.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/types/blocks.rs) +[File: crates/net/eth-wire/src/types/blocks.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/types/blocks.rs) ```rust,ignore pub struct GetBlockHeaders { /// The block number or hash that the peer should start returning headers from. @@ -528,7 +528,7 @@ pub struct GetBlockHeaders { In handling this request, the ETH requests task attempts, starting with `start_block`, to fetch the associated header from the database, increment/decrement the block number to fetch by `skip` depending on the `direction` while checking for overflow/underflow, and checks that bounds specifying the maximum numbers of headers or bytes to send have not been breached. -[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/eth_requests.rs) +[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/eth_requests.rs) ```rust,ignore fn get_headers_response(&self, request: GetBlockHeaders) -> Vec
{ let GetBlockHeaders { start_block, limit, skip, direction } = request; @@ -598,7 +598,7 @@ fn get_headers_response(&self, request: GetBlockHeaders) -> Vec
{ The `GetBlockBodies` payload is simpler, it just contains a vector of requested block hashes: -[File: crates/net/eth-wire/src/types/blocks.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/eth-wire/src/types/blocks.rs) +[File: crates/net/eth-wire/src/types/blocks.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/eth-wire/src/types/blocks.rs) ```rust,ignore pub struct GetBlockBodies( /// The block hashes to request bodies for. @@ -608,7 +608,7 @@ pub struct GetBlockBodies( In handling this request, similarly, the ETH requests task attempts, for each hash in the requested order, to fetch the block body (transactions & ommers), while checking that bounds specifying the maximum numbers of bodies or bytes to send have not been breached. -[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/eth_requests.rs) +[File: crates/net/network/src/eth_requests.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/eth_requests.rs) ```rust,ignore fn on_bodies_request( &mut self, @@ -653,7 +653,7 @@ in the [transaction-pool](../../../ethereum/transaction-pool/README.md) chapter. Again, like the network management and ETH requests tasks, the transactions task is implemented as an endless future that runs as a background task on a standalone `tokio::task`. It's represented by the `TransactionsManager` struct: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore pub struct TransactionsManager { /// Access to the transaction pool. @@ -688,7 +688,7 @@ pub struct TransactionsManager { Unlike the ETH requests task, but like the network management task's `NetworkHandle`, the transactions task can also be accessed via a shareable "handle" struct, the `TransactionsHandle`: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore pub struct TransactionsHandle { /// Command channel to the [`TransactionsManager`] @@ -711,7 +711,7 @@ Let's get a view into the transactions task's operation by walking through the ` The `poll` method lays out an order of operations for the transactions task. It begins by draining the `TransactionsManager.network_events`, `TransactionsManager.command_rx`, and `TransactionsManager.transaction_events` streams, in this order. Then, it checks on all the current `TransactionsManager.inflight_requests`, which are requests sent by the node to its peers for full transaction objects. After this, it checks on the status of completed `TransactionsManager.pool_imports` events, which are transactions that are being imported into the node's transaction pool. Finally, it drains the new `TransactionsManager.pending_transactions` events from the transaction pool. -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); @@ -786,7 +786,7 @@ The `TransactionsManager.network_events` stream is the first to have all of its The events received in this channel are of type `NetworkEvent`: -[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/manager.rs) +[File: crates/net/network/src/manager.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/manager.rs) ```rust,ignore pub enum NetworkEvent { /// Closed the peer session. @@ -822,7 +822,7 @@ Removes the peer given by `NetworkEvent::SessionClosed.peer_id` from the `Transa **`NetworkEvent::SessionEstablished`** Begins by inserting a `Peer` into `TransactionsManager.peers` by `peer_id`, which is a struct of the following form: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore struct Peer { /// Keeps track of transactions that we know the peer has seen. @@ -838,7 +838,7 @@ The `request_tx` field on the `Peer` is used at the sender end of a channel to s After the `Peer` is added to `TransactionsManager.peers`, the hashes of all of the transactions in the node's transaction pool are sent to the peer in a [`NewPooledTransactionHashes` message](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#newpooledtransactionhashes-0x08). -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn on_network_event(&mut self, event: NetworkEvent) { match event { @@ -875,7 +875,7 @@ fn on_network_event(&mut self, event: NetworkEvent) { Next in the `poll` method, `TransactionsCommand`s sent through the `TransactionsManager.command_rx` stream are handled. These are the next to be handled as they are those sent manually via the `TransactionsHandle`, giving them precedence over transactions-related requests picked up from the network. The `TransactionsCommand` enum has the following form: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore enum TransactionsCommand { PropagateHash(H256), @@ -886,7 +886,7 @@ enum TransactionsCommand { `on_new_transactions` propagates the full transaction object, with the signer attached, to a small random sample of peers using the `propagate_transactions` method. Then, it notifies all other peers of the hash of the new transaction, so that they can request the full transaction object if they don't already have it. -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn on_new_transactions(&mut self, hashes: impl IntoIterator) { trace!(target: "net::tx", "Start propagating transactions"); @@ -946,7 +946,7 @@ fn propagate_transactions( After `TransactionsCommand`s, it's time to take care of transactions-related requests sent by peers in the network, so the `poll` method handles `NetworkTransactionEvent`s received through the `TransactionsManager.transaction_events` stream. `NetworkTransactionEvent` has the following form: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore pub enum NetworkTransactionEvent { /// Received list of transactions from the given peer. @@ -976,7 +976,7 @@ To understand this a bit better, let's double back and examine what `Transaction `TransactionsManager.pool_imports` is a set of futures representing the transactions which are currently in the process of being imported to the node's transaction pool. This process is asynchronous due to the validation of the transaction that must occur, thus we need to keep a handle on the generated future. -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn import_transactions(&mut self, peer_id: PeerId, transactions: Vec) { let mut has_bad_transactions = false; @@ -1026,7 +1026,7 @@ This event is generated from the [`NewPooledTransactionHashes` protocol message] Here, it begins by adding the transaction hashes included in the `NewPooledTransactionHashes` payload to the LRU cache for the `Peer` identified by `peer_id` in `TransactionsManager.peers`. Next, it filters the list of hashes to those that are not already present in the transaction pool, and for each such hash, requests its full transaction object from the peer by sending it a [`GetPooledTransactions` protocol message](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#getpooledtransactions-0x09) through the `Peer.request_tx` channel. If the request was successfully sent, a `GetPooledTxRequest` gets added to `TransactionsManager.inflight_requests` vector: -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore struct GetPooledTxRequest { peer_id: PeerId, @@ -1036,7 +1036,7 @@ struct GetPooledTxRequest { As you can see, this struct also contains a `response` channel from which the peer's response can later be polled. -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn on_new_pooled_transactions(&mut self, peer_id: PeerId, msg: NewPooledTransactionHashes) { if let Some(peer) = self.peers.get_mut(&peer_id) { @@ -1072,7 +1072,7 @@ This event is generated from the [`GetPooledTransactions` protocol message](http Here, it collects _all_ the transactions in the node's transaction pool, recovers their signers, adds their hashes to the LRU cache of the requesting peer, and sends them to the peer in a [`PooledTransactions` protocol message](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#pooledtransactions-0x0a). This is sent through the `response` channel that's stored as a field of the `NetworkTransaction::GetPooledTransactions` variant itself. -[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/main/crates/net/network/src/transactions.rs) +[File: crates/net/network/src/transactions.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/net/network/src/transactions.rs) ```rust,ignore fn on_get_pooled_transactions( &mut self, diff --git a/docs/crates/stages.md b/docs/crates/stages.md index 430579d19..f9fcc33cd 100644 --- a/docs/crates/stages.md +++ b/docs/crates/stages.md @@ -2,7 +2,7 @@ The `stages` lib plays a central role in syncing the node, maintaining state, updating the database and more. The stages involved in the Reth pipeline are the `HeaderStage`, `BodyStage`, `SenderRecoveryStage`, and `ExecutionStage` (note that this list is non-exhaustive, and more pipeline stages will be added in the near future). Each of these stages are queued up and stored within the Reth pipeline. -[File: crates/stages/src/pipeline.rs](https://github.com/paradigmxyz/reth/blob/main/crates/stages/src/pipeline.rs) +[File: crates/stages/src/pipeline/mod.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/stages/src/pipeline/mod.rs) ```rust,ignore pub struct Pipeline { stages: Vec>, @@ -19,7 +19,7 @@ When the node is first started, a new `Pipeline` is initialized and all of the s Each stage within the pipeline implements the `Stage` trait which provides function interfaces to get the stage id, execute the stage and unwind the changes to the database if there was an issue during the stage execution. -[File: crates/stages/src/stage.rs](https://github.com/paradigmxyz/reth/blob/main/crates/stages/src/stage.rs) +[File: crates/stages/src/stage.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/stages/src/stage.rs) ```rust,ignore pub trait Stage: Send + Sync { /// Get the ID of the stage. @@ -53,7 +53,7 @@ To get a better idea of what is happening at each part of the pipeline, lets wal The `HeaderStage` is responsible for syncing the block headers, validating the header integrity and writing the headers to the database. When the `execute()` function is called, the local head of the chain is updated to the most recent block height previously executed by the stage. At this point, the node status is also updated with that block's height, hash and total difficulty. These values are used during any new eth/65 handshakes. After updating the head, a stream is established with other peers in the network to sync the missing chain headers between the most recent state stored in the database and the chain tip. The `HeaderStage` contains a `downloader` attribute, which is a type that implements the `HeaderDownloader` trait. A `HeaderDownloader` is a `Stream` that returns batches of headers. -[File: crates/interfaces/src/p2p/headers/downloader.rs](https://github.com/paradigmxyz/reth/blob/main/crates/interfaces/src/p2p/headers/downloader.rs) +[File: crates/interfaces/src/p2p/headers/downloader.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/interfaces/src/p2p/headers/downloader.rs) ```rust,ignore pub trait HeaderDownloader: Send + Sync + Stream> + Unpin { /// Updates the gap to sync which ranges from local head to the sync target @@ -77,7 +77,7 @@ pub trait HeaderDownloader: Send + Sync + Stream> + Unp The `HeaderStage` relies on the downloader stream to return the headers in descending order starting from the chain tip down to the latest block in the database. While other stages in the `Pipeline` start from the most recent block in the database up to the chain tip, the `HeaderStage` works in reverse to avoid [long-range attacks](https://messari.io/report/long-range-attack). When a node downloads headers in ascending order, it will not know if it is being subjected to a long-range attack until it reaches the most recent blocks. To combat this, the `HeaderStage` starts by getting the chain tip from the Consensus Layer, verifies the tip, and then walks backwards by the parent hash. Each value yielded from the stream is a `SealedHeader`. -[File: crates/primitives/src/header.rs](https://github.com/paradigmxyz/reth/blob/main/crates/primitives/src/header.rs) +[File: crates/primitives/src/header.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/primitives/src/header.rs) ```rust,ignore pub struct SealedHeader { /// Locked Header fields. @@ -130,7 +130,7 @@ The new block is then pre-validated, checking that the ommers hash and transacti Following a successful `BodyStage`, the `SenderRecoveryStage` starts to execute. The `SenderRecoveryStage` is responsible for recovering the transaction sender for each of the newly added transactions to the database. At the beginning of the execution function, all of the transactions are first retrieved from the database. Then the `SenderRecoveryStage` goes through each transaction and recovers the signer from the transaction signature and hash. The transaction hash is derived by taking the Keccak 256-bit hash of the RLP encoded transaction bytes. This hash is then passed into the `recover_signer` function. -[File: crates/primitives/src/transaction/signature.rs](https://github.com/paradigmxyz/reth/blob/main/crates/primitives/src/transaction/signature.rs) +[File: crates/primitives/src/transaction/signature.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/primitives/src/transaction/signature.rs) ```rust,ignore pub(crate) fn recover_signer(&self, hash: H256) -> Option
{ let mut sig: [u8; 65] = [0; 65]; @@ -157,7 +157,7 @@ Once the transaction signer has been recovered, the signer is then added to the Finally, after all headers, bodies and senders are added to the database, the `ExecutionStage` starts to execute. This stage is responsible for executing all of the transactions and updating the state stored in the database. For every new block header added to the database, the corresponding transactions have their signers attached to them and `reth_blockchain_tree::executor::execute_and_verify_receipt()` is called, pushing the state changes resulting from the execution to a `Vec`. -[File: crates/stages/src/stages/execution.rs](https://github.com/paradigmxyz/reth/blob/main/crates/stages/src/stages/execution.rs) +[File: crates/stages/src/stages/execution.rs](https://github.com/paradigmxyz/reth/blob/1563506aea09049a85e5cc72c2894f3f7a371581/crates/stages/src/stages/execution.rs) ```rust,ignore pub fn execute_and_verify_receipt( block: &Block, diff --git a/docs/design/database.md b/docs/design/database.md index eae89bf9d..45f9d2a13 100644 --- a/docs/design/database.md +++ b/docs/design/database.md @@ -14,7 +14,7 @@ * We implemented that trait for the following encoding formats: * [Ethereum-specific Compact Encoding](https://github.com/paradigmxyz/reth/blob/0d9b9a392d4196793736522f3fc2ac804991b45d/crates/codecs/derive/src/compact/mod.rs): A lot of Ethereum datatypes have unnecessary zeros when serialized, or optional (e.g. on empty hashes) which would be nice not to pay in storage costs. * [Erigon](https://github.com/ledgerwatch/erigon/blob/12ee33a492f5d240458822d052820d9998653a63/docs/programmers_guide/db_walkthrough.MD) achieves that by having a `bitfield` set on Table "PlainState which adds a bitfield to Accounts. - * Akula expanded it for other tables and datatypes manually. It also saved some more space by storing the length of certain types (U256, u64) using the modular_bitfield crate, which compacts this information. + * Akula expanded it for other tables and datatypes manually. It also saved some more space by storing the length of certain types (U256, u64) using the [`modular_bitfield`](https://docs.rs/modular-bitfield/latest/modular_bitfield/) crate, which compacts this information. * We generalized it for all types, by writing a derive macro that autogenerates code for implementing the trait. It, also generates the interfaces required for fuzzing using ToB/test-fuzz: * [Scale Encoding](https://github.com/paritytech/parity-scale-codec) * [Postcard Encoding](https://github.com/jamesmunns/postcard)