Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4

[*.{md,yml,yaml,toml}]
indent_size = 2

[Makefile]
indent_style = tab
28 changes: 28 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
test:
name: Test (Python ${{ matrix.python }} on ${{ matrix.os }})
strategy:
fail-fast: false
matrix:
python: ["3.11", "3.12", "3.13"]
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- name: Install package
run: pip install -e .
- name: Run unittest
run: python -m unittest discover -s tests -v
22 changes: 22 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
dist/
*.egg-info/
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
.tox/
.venv/
venv/
env/
*.log
.idea/
.vscode/
.DS_Store
Thumbs.db
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Changelog

Все значимые изменения проекта отражены здесь.

Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.1.0/),
проект придерживается [Semantic Versioning](https://semver.org/lang/ru/).

## [Unreleased]

## [0.1.0] — 2026-04-30

### Добавлено
- Stratum V1 клиент к `solo.ckpool.org:3333` (TCP + JSON-RPC).
- Цикл хеширования SHA-256 на чистом stdlib.
- Обработка `mining.set_difficulty`, `mining.notify`, `mining.set_extranonce`.
- Reconnect с экспоненциальным backoff (1→60с).
- Общий `stop_event` для чистого shutdown по Ctrl+C.
- Логирование через `logging` со стандартными уровнями.
- 15 юнит-тестов на криптографические функции (`unittest`).
- Реструктуризация в `src/`-layout с пакетом `hope_hash`.

[Unreleased]: https://github.com/KruglikovskiiPA/Hope-Hash/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/KruglikovskiiPA/Hope-Hash/releases/tag/v0.1.0
113 changes: 113 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Hope-Hash — solo Bitcoin miner на чистом Python

Учебный соло-майнер биткоина. Подключается к `solo.ckpool.org:3333`,
реализует Stratum V1 с нуля, перебирает SHA-256 в pure-Python, отправляет
шары. Цель — **разобраться, как работает Bitcoin mining изнутри**, а не
зарабатывать. Реальный шанс найти блок ≈ 1 к 10¹⁵ в день.

См. README.md для деталей и ROADMAP.md для плана развития.

## Tech stack

- Python ≥3.11, **только стандартная библиотека** (socket, hashlib, json,
struct, threading, logging, argparse). Runtime-зависимостей нет.
- Layout: `src/`-style, пакет `hope_hash` под `src/hope_hash/`.
- Build backend: `hatchling`. Установка: `python -m pip install -e .`
(на Windows: `py -3.11 -m pip install -e .`).
- Тесты: stdlib `unittest`, в `tests/`. Запуск: `python -m unittest discover -s tests`.
- Запуск: `python -m hope_hash <BTC_адрес> [имя_воркера]` или после
install — `hope-hash <BTC_адрес> [имя_воркера]`.
- Протокол: Stratum V1 поверх TCP, JSON line-delimited.

## Структура пакета

- `src/hope_hash/block.py` — чистые функции: `double_sha256`, `swap_words`,
`difficulty_to_target`, `build_merkle_root`. Без сайд-эффектов.
- `src/hope_hash/stratum.py` — класс `StratumClient` (TCP + JSON-RPC).
- `src/hope_hash/miner.py` — `mine()`, `run_session()`, `supervisor_loop()`.
- `src/hope_hash/cli.py` — argparse-точка входа `main()`, константы пула.
- `src/hope_hash/_logging.py` — приватная настройка логгера `hope_hash`.
- `src/hope_hash/__init__.py` — публичный API + `__version__`.
- `src/hope_hash/__main__.py` — для `python -m hope_hash`.
- `tests/test_block.py` — 15 тестов на чистые функции.

## Архитектура (не менять без обсуждения)

- Один процесс, две нити: `mine()` крутит хеши в main thread,
`reader_loop` слушает пул в отдельной нити (НЕ daemon — для clean
shutdown).
- `current_job` защищён `threading.Lock`. `mine()` проверяет смену
`job_id` каждые ~16k хешей (`hashes & 0x3FFF == 0`).
- Общий `stop_event` связывает все нити: при ошибке в `reader_loop`
он ставит флаг → `mine()` корректно выходит.
- `supervisor_loop` обеспечивает reconnect с backoff 1→2→4→…→60с.
- Endianness: version/ntime/nbits — LE через `[::-1]`, prevhash —
word-swap (`swap_words`), merkle_root — as-is из `double_sha256`.
Это корректно, не трогать.

## Conventions

- Комментарии и docstrings — на русском, как в существующем коде.
- Имена логов: `[net]`, `[stratum]`, `[mine]`, `[stats]`, `[main]` —
держать единый стиль при добавлении нового.
- Объяснять «зачем», а не «что» (см. word-swap в коде как образец).
- Файлы документации: README.md (что есть), ROADMAP.md (что будет),
CLAUDE.md (правила для агента).

## Patterns to avoid

- ❌ Не добавлять зависимости (`pip install ...`) без явной просьбы.
Pure-Python — ключевое свойство проекта.
- ❌ Не переписывать endianness/word-swap «для красоты» — это
работает и протестировано вручную против реальных блоков.
- ❌ Не добавлять `try/except` вокруг каждой строки. Отказы сети
и парсинга — точечная обработка в `reader_loop`, `subscribe` и
`supervisor_loop`.
- ❌ Не трогать структуру `header_base` в `mine()` — это hot path,
любая «оптимизация» проверяется бенчмарком до и после.
- ❌ Не возвращать `print` вместо `logger.*` — переход уже сделан,
держать единый канал вывода.
- ❌ Не складывать новый код в корень репо. Всё runtime — под
`src/hope_hash/`, всё тестовое — под `tests/`.

## Workflow preferences

- Перед изменениями кода — сверяться с ROADMAP.md: если фича уже
там описана, использовать формулировки и приоритеты оттуда, а не
придумывать свои.
- Перед рефакторингом — спросить пользователя. Учебный код ценен
читаемостью; «улучшение архитектуры ради архитектуры» вредно.
- Английский — для технических терминов (`nonce`, `merkle root`),
русский — для прозы. Не смешивать в пределах одного предложения.

## Запуск (для справки)

```bash
# Установка один раз:
py -3.11 -m pip install -e .

# Запуск (любой из вариантов):
hope-hash <BTC_адрес> [имя_воркера]
python -m hope_hash <BTC_адрес> [имя_воркера]

# Тесты:
python -m unittest discover -s tests -v
```

## Self-learning loop (на будущее)

Когда накопится опыт работы агента над проектом — создать `learnings.md`
с разделами **What Has Worked / What Has Failed / Patterns and Preferences
/ Open Questions**. Формат записи:

```
**[YYYY-MM-DD] — [тип задачи]**
- Observation: что замечено
- Action: что делать / чего избегать дальше
- Confidence: high / medium / low
```

Правила: архивировать при превышении 80–100 строк, удалять устаревшее,
не добавлять записи без конкретики (vague entries едят контекст).

Сейчас файла нет — создать при первом реальном уроке.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Pavel Kruglikovskii

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.PHONY: install test lint typecheck run clean

install:
pip install -e .

test:
python -m unittest discover -s tests -v

lint:
ruff check src tests

typecheck:
mypy src

run:
python -m hope_hash $(ARGS)

clean:
rm -rf build dist *.egg-info .pytest_cache .mypy_cache .ruff_cache
find . -type d -name __pycache__ -exec rm -rf {} +
Loading
Loading