You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Smart contract for verifying Bitcoin block headers on EVM-compatible chains using the **Simple Payment Verification (SPV)** method.
4
-
5
-
This contract behaves like an SPV node: it builds a valid chain of Bitcoin block headers, verifies them according to Bitcoin consensus rules, and enables Merkle Proof-based verification of Bitcoin transactions.
6
-
7
-
## Features
8
-
9
-
- Stores and verifies Bitcoin block headers
10
-
- Validates headers using:
11
-
- Proof of Work (`bits` → `target`)
12
-
- Median time rule
13
-
- Chain continuity
14
-
- Handles difficulty adjustment every 2016 blocks
15
-
- Supports pending difficulty epochs before finalization
16
-
- Stores historical targets and supports reorg handling
17
-
18
-
## Contract: `SPVContract.sol`
1
+
# 🛡️ SPV Contract: Bitcoin Light Client on EVM
2
+
Welcome to the **SPV Contract**, a robust and efficient Solidity implementation for verifying Bitcoin block headers directly on an EVM-compatible blockchain. This contract empowers dApps to act as a **Simplified Payment Verification (SPV)** client, allowing them to validate the existence and inclusion of Bitcoin transactions without needing to run a full Bitcoin node.
3
+
4
+
# ✨ Why this SPV Contract?
5
+
In the decentralized world, connecting different blockchain ecosystems securely is paramount. This SPV contract provides a trust-minimized bridge, enabling smart contracts on EVM chains to cryptographically verify the state of the Bitcoin blockchain. This opens doors for exciting use cases like:
6
+
-**Cross-chain bridges** for Bitcoin-backed assets
7
+
-**Light clients** for dApps that need to confirm Bitcoin transaction finality
8
+
-**Decentralized custodianship** solutions
9
+
-**Oracle services** for Bitcoin data on EVM
10
+
11
+
# 🚀 Key Features
12
+
-**Block Header Submission:** Efficiently add individual or batches of Bitcoin block headers to the contract.
13
+
-**Mainchain Tracking:** Automatically identifies and updates the "main" Bitcoin chain based on accumulated work.
14
+
-**Block Validation:** Verifies block headers against Bitcoin's consensus rules, including:
15
+
- Proof-of-Work (target difficulty)
16
+
- Block time validity (median time past)
17
+
- Chain continuity (previous block hash)
18
+
-**Block Information Retrieval:** Query detailed information about any stored block, such as:
19
+
- Its Merkle root
20
+
- Its height
21
+
- Its inclusion status in the mainchain
22
+
- Its cumulative work (difficulty)
23
+
- Its confirmation count relative to the mainchain head
24
+
-**Difficulty Adjustment:** Integrates Bitcoin's precise difficulty adjustment algorithm to accurately calculate current and future targets.
25
+
26
+
# ⚙️ How it Works (Under the Hood)
27
+
The contract operates by receiving raw Bitcoin block headers, which are then parsed and validated against Bitcoin's strict consensus rules.
28
+
29
+
1.**Header Parsing:** Raw 80-byte Bitcoin block headers are parsed into a structured *BlockHeaderData* format. This involves handling Bitcoin's unique little-endian byte ordering.
30
+
2.**Double SHA256 Hashing:** Each block header is double SHA256 hashed to derive its unique block hash, which is then byte-reversed for standard representation.
31
+
3.**Proof-of-Work Verification:** The calculated block hash is checked against the current network difficulty target (derived from the *bits* field in the header).
32
+
4.**Chain Extension & Reorganization:** New blocks are added to a data structure that allows for tracking multiple chains. When a new block extends a chain with higher cumulative work, the *mainchainHead* is updated, reflecting potential chain reorganizations.
33
+
5.**Difficulty Adjustment:** Every 2016 blocks, the contract calculates a new difficulty target based on the time taken to mine the preceding epoch. This ensures the 10-minute average block time is maintained.
34
+
35
+
# 📊 Flow Diagrams
36
+
These diagrams outline the step-by-step process for adding block headers to the SPV Contract.
Adds and validates a new block header, updates internal state, and emits an event.
24
189
25
-
### Validation Rules
26
-
-`prevBlockHash` must point to a known block
27
-
- New `blockHash` must not exist
28
-
- Header `bits` must match the expected network target
29
-
- Header `time` must be > median of last 11 blocks
30
-
-`blockHash` must be less than or equal to the target (valid PoW)
190
+
# 📦 Contract Components
191
+
The solution is primarily composed of the main SPV contract and two essential helper libraries that manage the intricacies of Bitcoin's block structure and difficulty adjustments.
31
192
32
-
## Storage Structure
193
+
## SPVContract
194
+
This is the central contract that users will interact with. It serves as the primary interface for managing Bitcoin block headers on the EVM. It handles the core logic for adding and validating blocks, tracking the main Bitcoin chain, and providing querying functionalities. All custom errors and events related to the SPV operations are defined here, ensuring clear feedback and transparency during contract execution.
33
195
34
-
-`BlocksData` – stores block headers, timestamps, and chain height
35
-
-`TargetsData` – handles target values and difficulty epochs
36
-
-`pendingTargetHeightCount` – controls target finalization after N blocks
196
+
## BlockHeader Library
197
+
This is a pure utility library specifically designed to handle the low-level details of Bitcoin block headers. It's responsible for the precise parsing of raw 80-byte Bitcoin block header data into a structured format that Solidity can easily work with. Crucially, it manages the byte order conversions, translating Bitcoin's little-endian format to Solidity's big-endian, and vice-versa. It also provides the essential function for calculating the double SHA256 hash of a block header, which is fundamental for verifying Proof-of-Work.
37
198
38
-
## Dev Info
39
-
### Compilation
199
+
## TargetsHelper Library
200
+
This library encapsulates all the complex mathematical and logical operations related to Bitcoin's difficulty targets. It provides functions to accurately calculate new difficulty targets based on elapsed time between blocks, ensuring the contract adheres to Bitcoin's dynamic difficulty adjustment rules. Additionally, it offers utilities for converting between the compact "bits" format (as found in Bitcoin block headers) and the full 256-bit target value, and it calculates the cumulative work associated with a given block or epoch, which is vital for determining the most valid chain.
40
201
202
+
# 💻 Dev Info
203
+
## Compilation
41
204
To compile the contracts, use the next script:
42
205
43
206
```bash
44
207
npm run compile
45
208
```
46
209
47
-
### Test
48
-
210
+
## Test
49
211
To run the tests, execute the following command:
50
212
51
213
```bash
@@ -58,19 +220,17 @@ Or to see the coverage, run:
58
220
npm run coverage
59
221
```
60
222
61
-
### Local deployment
62
-
223
+
## Local deployment
63
224
To deploy the contracts locally, run the following commands (in the different terminals):
64
225
65
226
```bash
66
227
npm run private-network
67
228
npm run deploy-localhost
68
229
```
69
230
70
-
### Bindings
71
-
231
+
## Bindings
72
232
The command to generate the bindings is as follows:
0 commit comments