{"eip":8002,"title":"Simplified Payment Verification Gateway","description":"Trustless singleton contract for on-chain verification of Bitcoin transactions through block headers","authors":["Artem Chystiakov (@arvolear)","Oleh Komendant (@Hrom131)"],"status":"Draft","type":"Standards Track","category":"ERC","created":"2025-08-07","discussionsTo":"https://ethereum-magicians.org/t/eip-8002-simplified-payment-verification-gateway/25038","repo":"ERCs","label":"ERC-8002","officialUrl":"https://eips.ethereum.org/EIPS/eip-8002","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-8002.md","url":"https://eips.huatuo.xyz/eip-8002/","tldr":{"en":"A draft singleton contract that acts as a permissionless Bitcoin light client on Ethereum: anyone submits Bitcoin block headers, the contract tracks the most-work chain, and dApps verify that a Bitcoin transaction was confirmed using a Merkle proof.","ja":"Ethereum 上でパーミッションレスな Bitcoin ライトクライアントとして動作する、ドラフト段階のシングルトンコントラクト。誰でも Bitcoin のブロックヘッダーを提出でき、コントラクトが最大ワークのチェーンを追跡し、dApp は Merkle proof で Bitcoin トランザクションが承認されたことを検証できる。","ko":"이더리움에서 허가 없이 쓸 수 있는 비트코인 라이트 클라이언트로 동작하는 초안 단계의 싱글톤 컨트랙트. 누구나 비트코인 블록 헤더를 제출하고, 컨트랙트는 작업량이 가장 큰 체인을 추적하며, dApp은 Merkle 증명으로 비트코인 트랜잭션이 확정되었는지 검증한다.","zh":"一个处于草案阶段的单例合约，在以太坊上充当无需许可的比特币轻客户端：任何人都可以提交比特币区块头，合约追踪累计工作量最大的链，dApp 则通过 Merkle 证明验证某笔比特币交易已被确认。"},"tags":["bitcoin","spv","light-client","bridge","interop"],"explainers":{"en":{"lang":"en","tldr":"A draft singleton contract that acts as a permissionless Bitcoin light client on Ethereum: anyone submits Bitcoin block headers, the contract tracks the most-work chain, and dApps verify that a Bitcoin transaction was confirmed using a Merkle proof.","tags":["bitcoin","spv","light-client","bridge","interop"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-8002/","markdown":"## What problem does it solve?\n\nBitcoin has very limited programmability, so native BTC cannot easily take part in Ethereum DeFi. Most \"BTC on Ethereum\" today relies on a wrapped token issued by a custodian or a federation that you must trust.\n\nERC-8002 proposes a shared, trustless building block: a single on-chain **Simplified Payment Verification (SPV) gateway**. It lets any Ethereum contract ask, \"Was this Bitcoin transaction included in the Bitcoin main chain with at least N confirmations?\" without trusting an oracle. That is enough for one-way use cases such as accepting native BTC as loan collateral, and the authors see it as a foundation for future trust-minimized two-way bridges.\n\n## How it works\n\n- **Header relay**: anyone calls `addBlockHeader(raw)` (or the optional `addBlockHeaderBatch`) with an 80-byte Bitcoin block header. The contract checks that:\n  - the previous-block hash points to a known header;\n  - the timestamp is greater than the median of the previous 11 blocks;\n  - the double-SHA256 of the header is at or below the target implied by Bitcoin's difficulty adjustment (every 2016 blocks, clamped to 4x / 1/4x).\n- **Main chain**: each header's work is `(2**256 - 1) / (target + 1)`. The contract tracks cumulative work and treats the chain with the most work as the main chain, handling reorganizations. It emits `BlockHeaderAdded` and, when the tip changes, `MainchainHeadUpdated`.\n- **Transaction proof**: `checkTxInclusion(merkleProof, blockHash, txId, txIndex, minConfirmations)` returns true only if the block is on the main chain with enough confirmations and the Merkle path rebuilds the block's Merkle root.\n- **Bootstrapping**: rather than replaying all of Bitcoin from genesis (estimated by the authors at around 100 ETH of gas at 1 gwei), the gateway is initialized permissionlessly from a chosen header, height and cumulative work. That starting point is trusted.\n- Getters expose the main-chain head and height, header data, block status and confirmations, and hash-by-height lookups.\n\n## Sample code\n\nA contract that releases a loan only after a Bitcoin payment has 6 confirmations:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ISPVGateway {\n    function checkTxInclusion(\n        bytes32[] memory merkleProof,\n        bytes32 blockHash,\n        bytes32 txId,\n        uint256 txIndex,\n        uint256 minConfirmationsCount\n    ) external view returns (bool);\n    function getMainchainHeight() external view returns (uint64);\n}\n\ncontract BtcCollateralDesk {\n    ISPVGateway public immutable spv;\n    mapping(bytes32 =\u003e bool) public used;   // prevent reusing the same BTC tx\n\n    constructor(ISPVGateway _spv) { spv = _spv; }\n\n    function claim(bytes32[] calldata proof, bytes32 blockHash, bytes32 txId, uint256 txIndex) external {\n        require(!used[txId], \"already used\");\n        require(spv.checkTxInclusion(proof, blockHash, txId, txIndex, 6), \"not confirmed\");\n        used[txId] = true;\n        // A real protocol must also parse the raw BTC tx to check outputs and amounts.\n        // ... release funds\n    }\n}\n```\n\n## Things to know\n\n- **Status: Draft.** No canonical deployment address is defined yet (the spec still says \"TODO\"), and deployment method and test cases are unfinished.\n- Inclusion alone does not tell you *what* the transaction did. Protocols must also verify the raw transaction's outputs (recipient script and amount) against `txId`.\n- There is no built-in finality. Each consumer chooses its own confirmation threshold, and deep Bitcoin reorgs remain possible.\n- Security rests on Bitcoin's proof-of-work: an attacker with majority hash power could feed the contract a fraudulent chain. The initial checkpoint is also a trust point that users of a given deployment should verify.\n- The \"no more than 2 hours in the future\" timestamp rule cannot be enforced on-chain and is omitted.\n- Bitcoin serializes integers little-endian, while the gateway stores header fields big-endian; mind byte order when preparing `txId` and proofs.\n"},"ja":{"lang":"ja","tldr":"Ethereum 上でパーミッションレスな Bitcoin ライトクライアントとして動作する、ドラフト段階のシングルトンコントラクト。誰でも Bitcoin のブロックヘッダーを提出でき、コントラクトが最大ワークのチェーンを追跡し、dApp は Merkle proof で Bitcoin トランザクションが承認されたことを検証できる。","tags":["bitcoin","spv","light-client","bridge","interop"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-8002/","markdown":"## 何を解決するのか\n\nBitcoin のプログラマビリティは非常に限られているため、ネイティブな BTC を Ethereum の DeFi に簡単に参加させることはできません。現在の「Ethereum 上の BTC」の多くは、カストディアンやフェデレーションが発行するラップドトークンに依存しており、その発行者を信頼する必要があります。\n\nERC-8002 は、共有可能でトラストレスな構成要素として、オンチェーンの単一の **Simplified Payment Verification（SPV）ゲートウェイ**を提案します。これにより、任意の Ethereum コントラクトが、オラクルを信頼することなく「この Bitcoin トランザクションは、少なくとも N 承認以上で Bitcoin のメインチェーンに含まれているか？」と問い合わせられます。ネイティブ BTC をローンの担保として受け入れるといった一方向のユースケースにはこれで十分であり、著者は将来の信頼最小化された双方向ブリッジの基盤になると見ています。\n\n## 仕組み\n\n- **ヘッダーリレー**: 誰でも 80 バイトの Bitcoin ブロックヘッダーを指定して `addBlockHeader(raw)`（または任意の `addBlockHeaderBatch`）を呼び出せます。コントラクトは次の点を検証します。\n  - 前ブロックのハッシュが既知のヘッダーを指していること\n  - タイムスタンプが直前 11 ブロックの中央値より大きいこと\n  - ヘッダーの二重 SHA256 が、Bitcoin の難易度調整（2016 ブロックごと、4 倍 / 1/4 倍に制限）で決まるターゲット以下であること\n- **メインチェーン**: 各ヘッダーのワークは `(2**256 - 1) / (target + 1)` です。コントラクトは累積ワークを追跡し、最もワークの大きいチェーンをメインチェーンとして扱い、リオーグも処理します。`BlockHeaderAdded` を発行し、チップが変わったときは `MainchainHeadUpdated` も発行します。\n- **トランザクションの証明**: `checkTxInclusion(merkleProof, blockHash, txId, txIndex, minConfirmations)` は、そのブロックがメインチェーン上にあり十分な承認数があり、かつ Merkle パスがブロックの Merkle root を再構築できる場合にのみ true を返します。\n- **ブートストラップ**: ジェネシスから Bitcoin 全体を再生する代わりに（著者の見積もりでは 1 gwei で約 100 ETH 分のガス）、ゲートウェイは選択したヘッダー、高さ、累積ワークからパーミッションレスに初期化されます。この出発点は信頼されます。\n- ゲッターにより、メインチェーンのヘッド、高さ、ヘッダーデータ、ブロックのステータスと承認数、高さからのハッシュ検索を参照できます。\n\n## サンプルコード\n\nBitcoin の支払いが 6 承認に達して初めてローンを実行するコントラクト:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ISPVGateway {\n    function checkTxInclusion(\n        bytes32[] memory merkleProof,\n        bytes32 blockHash,\n        bytes32 txId,\n        uint256 txIndex,\n        uint256 minConfirmationsCount\n    ) external view returns (bool);\n    function getMainchainHeight() external view returns (uint64);\n}\n\ncontract BtcCollateralDesk {\n    ISPVGateway public immutable spv;\n    mapping(bytes32 =\u003e bool) public used;   // prevent reusing the same BTC tx\n\n    constructor(ISPVGateway _spv) { spv = _spv; }\n\n    function claim(bytes32[] calldata proof, bytes32 blockHash, bytes32 txId, uint256 txIndex) external {\n        require(!used[txId], \"already used\");\n        require(spv.checkTxInclusion(proof, blockHash, txId, txIndex, 6), \"not confirmed\");\n        used[txId] = true;\n        // A real protocol must also parse the raw BTC tx to check outputs and amounts.\n        // ... release funds\n    }\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Draft。** 正式なデプロイ先アドレスはまだ定義されておらず（仕様には依然として \"TODO\" とあります）、デプロイ方法とテストケースも未完成です。\n- 含まれていることを確認できても、そのトランザクションが*何をしたか*は分かりません。プロトコルは、`txId` に対応する生のトランザクションの出力（宛先スクリプトと金額）も検証する必要があります。\n- ファイナリティは組み込まれていません。各利用者が独自の承認数のしきい値を選び、深い Bitcoin のリオーグも起こり得ます。\n- セキュリティは Bitcoin のプルーフ・オブ・ワークに依存します。過半数のハッシュパワーを持つ攻撃者は、不正なチェーンをコントラクトに与えられます。初期チェックポイントも信頼点であり、各デプロイの利用者は確認すべきです。\n- 「未来 2 時間以内」というタイムスタンプのルールはオンチェーンでは強制できないため、省かれています。\n- Bitcoin は整数をリトルエンディアンでシリアライズしますが、ゲートウェイはヘッダーフィールドをビッグエンディアンで保存します。`txId` や proof を準備するときはバイト順に注意してください。\n"},"ko":{"lang":"ko","tldr":"이더리움에서 허가 없이 쓸 수 있는 비트코인 라이트 클라이언트로 동작하는 초안 단계의 싱글톤 컨트랙트. 누구나 비트코인 블록 헤더를 제출하고, 컨트랙트는 작업량이 가장 큰 체인을 추적하며, dApp은 Merkle 증명으로 비트코인 트랜잭션이 확정되었는지 검증한다.","tags":["bitcoin","spv","light-client","bridge","interop"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-8002/","markdown":"## 어떤 문제를 해결하나요?\n\n비트코인은 프로그래밍 가능성이 매우 제한적이어서 네이티브 BTC가 이더리움 DeFi에 참여하기 어렵습니다. 오늘날 \"이더리움 위의 BTC\"는 대부분 수탁 기관이나 연합체가 발행하는 래핑 토큰에 의존하며, 이들을 신뢰해야 합니다.\n\nERC-8002는 공유 가능하고 신뢰가 필요 없는 구성 요소로서 온체인 단일 **Simplified Payment Verification(SPV) 게이트웨이**를 제안합니다. 이를 통해 어떤 이더리움 컨트랙트든 오라클을 신뢰하지 않고 \"이 비트코인 트랜잭션이 최소 N번의 컨펌과 함께 비트코인 메인 체인에 포함되었는가?\"를 물을 수 있습니다. 네이티브 BTC를 대출 담보로 받는 것과 같은 단방향 사용 사례에는 이것으로 충분하며, 저자들은 이를 향후 신뢰 최소화 양방향 브리지의 기반으로 봅니다.\n\n## 어떻게 동작하나요?\n\n- **헤더 릴레이**: 누구나 80바이트 비트코인 블록 헤더로 `addBlockHeader(raw)`(또는 선택적인 `addBlockHeaderBatch`)를 호출할 수 있습니다. 컨트랙트는 다음을 확인합니다.\n  - 이전 블록 해시가 알려진 헤더를 가리킨다.\n  - 타임스탬프가 직전 11개 블록의 중앙값보다 크다.\n  - 헤더의 이중 SHA256이 비트코인의 난이도 조정(2016블록마다, 4배 / 1/4배로 제한)에서 정해지는 타깃 이하이다.\n- **메인 체인**: 각 헤더의 작업량은 `(2**256 - 1) / (target + 1)`입니다. 컨트랙트는 누적 작업량을 추적하고 작업량이 가장 큰 체인을 메인 체인으로 간주하며 리오그를 처리합니다. `BlockHeaderAdded`를 발생시키고, 팁이 바뀌면 `MainchainHeadUpdated`도 발생시킵니다.\n- **트랜잭션 증명**: `checkTxInclusion(merkleProof, blockHash, txId, txIndex, minConfirmations)`는 해당 블록이 메인 체인에 있고 컨펌이 충분하며 Merkle 경로가 블록의 Merkle 루트를 재구성할 때만 true를 반환합니다.\n- **부트스트랩**: 제네시스부터 비트코인 전체를 재생하는 대신(저자들은 1 gwei 기준 약 100 ETH 상당의 가스로 추정), 게이트웨이는 선택한 헤더, 높이, 누적 작업량으로 허가 없이 초기화됩니다. 이 시작점은 신뢰의 대상입니다.\n- 게터를 통해 메인 체인의 헤드와 높이, 헤더 데이터, 블록 상태와 컨펌 수, 높이로 해시를 조회하는 기능을 제공합니다.\n\n## 샘플 코드\n\n비트코인 결제가 6번 컨펌된 뒤에야 대출을 실행하는 컨트랙트:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ISPVGateway {\n    function checkTxInclusion(\n        bytes32[] memory merkleProof,\n        bytes32 blockHash,\n        bytes32 txId,\n        uint256 txIndex,\n        uint256 minConfirmationsCount\n    ) external view returns (bool);\n    function getMainchainHeight() external view returns (uint64);\n}\n\ncontract BtcCollateralDesk {\n    ISPVGateway public immutable spv;\n    mapping(bytes32 =\u003e bool) public used;   // prevent reusing the same BTC tx\n\n    constructor(ISPVGateway _spv) { spv = _spv; }\n\n    function claim(bytes32[] calldata proof, bytes32 blockHash, bytes32 txId, uint256 txIndex) external {\n        require(!used[txId], \"already used\");\n        require(spv.checkTxInclusion(proof, blockHash, txId, txIndex, 6), \"not confirmed\");\n        used[txId] = true;\n        // A real protocol must also parse the raw BTC tx to check outputs and amounts.\n        // ... release funds\n    }\n}\n```\n\n## 알아둘 점\n\n- **상태: Draft.** 표준 배포 주소가 아직 정의되지 않았고(스펙에 여전히 \"TODO\"라고 되어 있습니다), 배포 방법과 테스트 케이스도 미완성입니다.\n- 포함되었다는 사실만으로는 그 트랜잭션이 *무엇을 했는지* 알 수 없습니다. 프로토콜은 `txId`에 해당하는 원본 트랜잭션의 출력(수신 스크립트와 금액)도 함께 검증해야 합니다.\n- 내장된 파이널리티는 없습니다. 각 사용처가 자체 컨펌 임계값을 정하며, 비트코인의 깊은 리오그도 여전히 가능합니다.\n- 보안은 비트코인의 작업 증명에 의존합니다. 과반 해시 파워를 가진 공격자는 컨트랙트에 사기성 체인을 제공할 수 있습니다. 초기 체크포인트 역시 신뢰 지점이므로 각 배포의 사용자는 이를 확인해야 합니다.\n- \"미래 2시간을 넘지 않아야 한다\"는 타임스탬프 규칙은 온체인에서 강제할 수 없어 생략되었습니다.\n- 비트코인은 정수를 리틀 엔디언으로 직렬화하지만 게이트웨이는 헤더 필드를 빅 엔디언으로 저장합니다. `txId`와 증명을 준비할 때 바이트 순서에 주의하세요.\n"},"zh":{"lang":"zh","tldr":"一个处于草案阶段的单例合约，在以太坊上充当无需许可的比特币轻客户端：任何人都可以提交比特币区块头，合约追踪累计工作量最大的链，dApp 则通过 Merkle 证明验证某笔比特币交易已被确认。","tags":["bitcoin","spv","light-client","bridge","interop"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-8002/","markdown":"## 它解决什么问题？\n\n比特币的可编程性非常有限，因此原生 BTC 很难参与以太坊 DeFi。如今大多数\"以太坊上的 BTC\"都依赖由托管方或联盟发行的包装代币，你必须信任这些发行方。\n\nERC-8002 提出了一个共享的、无需信任的构建模块：链上唯一的**简化支付验证（SPV）网关**。它让任何以太坊合约都能在不信任预言机的情况下询问：\"这笔比特币交易是否已被包含在比特币主链中，并且至少有 N 个确认？\"这足以支持单向的用例，例如接受原生 BTC 作为贷款抵押品，作者也把它视为未来信任最小化双向桥的基础。\n\n## 它如何运作\n\n- **区块头中继**：任何人都可以用 80 字节的比特币区块头调用 `addBlockHeader(raw)`（或可选的 `addBlockHeaderBatch`）。合约会检查：\n  - 前一区块哈希指向一个已知的区块头；\n  - 时间戳大于前 11 个区块的中位数；\n  - 区块头的双重 SHA256 不高于由比特币难度调整（每 2016 个区块一次，限制在 4 倍 / 1/4 倍之内）所确定的目标值。\n- **主链**：每个区块头的工作量为 `(2**256 - 1) / (target + 1)`。合约追踪累计工作量，把工作量最大的链视为主链，并处理链重组。它会触发 `BlockHeaderAdded`，当链尖变化时还会触发 `MainchainHeadUpdated`。\n- **交易证明**：`checkTxInclusion(merkleProof, blockHash, txId, txIndex, minConfirmations)` 只有在该区块位于主链上且确认数足够、并且 Merkle 路径能够重建出区块的 Merkle 根时才返回 true。\n- **引导启动**：不必从创世区块开始重放整个比特币链（作者估计在 1 gwei 下需要约 100 ETH 的 gas），网关可以从选定的区块头、高度和累计工作量无需许可地初始化。这个起点是被信任的。\n- 读取函数提供主链链头和高度、区块头数据、区块状态和确认数，以及按高度查询哈希。\n\n## 示例代码\n\n一个只有在比特币支付获得 6 个确认后才发放贷款的合约：\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ISPVGateway {\n    function checkTxInclusion(\n        bytes32[] memory merkleProof,\n        bytes32 blockHash,\n        bytes32 txId,\n        uint256 txIndex,\n        uint256 minConfirmationsCount\n    ) external view returns (bool);\n    function getMainchainHeight() external view returns (uint64);\n}\n\ncontract BtcCollateralDesk {\n    ISPVGateway public immutable spv;\n    mapping(bytes32 =\u003e bool) public used;   // prevent reusing the same BTC tx\n\n    constructor(ISPVGateway _spv) { spv = _spv; }\n\n    function claim(bytes32[] calldata proof, bytes32 blockHash, bytes32 txId, uint256 txIndex) external {\n        require(!used[txId], \"already used\");\n        require(spv.checkTxInclusion(proof, blockHash, txId, txIndex, 6), \"not confirmed\");\n        used[txId] = true;\n        // A real protocol must also parse the raw BTC tx to check outputs and amounts.\n        // ... release funds\n    }\n}\n```\n\n## 需要注意\n\n- **状态：Draft。** 尚未定义规范的部署地址（规范中仍写着 \"TODO\"），部署方式和测试用例也未完成。\n- 仅凭\"被包含\"并不能说明这笔交易*做了什么*。协议还必须根据 `txId` 验证原始交易的输出（接收脚本和金额）。\n- 没有内置的最终性。每个使用方自行选择确认数阈值，比特币仍有可能发生深度重组。\n- 安全性依赖于比特币的工作量证明：掌握多数算力的攻击者可以向合约提供一条欺诈性的链。初始检查点也是一个信任点，特定部署的用户应当自行验证。\n- \"不得晚于未来 2 小时\"的时间戳规则无法在链上强制执行，因此被省略。\n- 比特币以小端序列化整数，而网关以大端存储区块头字段；准备 `txId` 和证明时要注意字节序。\n"}}}
