diff --git a/BAPs/BAP-578.md b/BAPs/BAP-578.md new file mode 100644 index 000000000..c22e8c307 --- /dev/null +++ b/BAPs/BAP-578.md @@ -0,0 +1,610 @@ +``` +BAP: 578 +Title: Non-Fungible Agent (NFA) Token Standard +Status: Draft +Type: Application +Created: 2025-05-27 +``` + +# BAP-578: Non-Fungible Agent (NFA) Token Standard + +- [BAP-578: Non-Fungible Agent (NFA) Token Standard] + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [3.1 The Need for Standardization](#31-the-need-for-standardization) + - [3.2 Current Ecosystem Challenges](#32-current-ecosystem-challenges) + - [3.3 Hybrid Architecture Benefits](#33-hybrid-architecture-benefits) + - [4. Specification](#4-specification) + - [4.1 Core Interface](#41-core-interface) + - [4.2 Agent State Management](#42-agent-state-management) + - [4.3 Enhanced Metadata Schema](#43-enhanced-metadata-schema) + - [4.4 Learning Module System](#44-learning-module-system) + - [4.5 Memory Module Registry](#45-memory-module-registry) + - [4.6 Vault Permission System](#46-vault-permission-system) + - [4.7 Security Mechanisms](#47-security-mechanisms) + - [4.8 Agent Templates](#48-agent-templates) + - [4.9 Dual-Path Architecture](#49-dual-path-architecture) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#7-test-cases) + - [8. Implementation](#8-implementation) + - [9. Security Considerations](#9-security-considerations) + - [10. License](#10-license) + +## 1. Summary + +This BNB Chain Application (BAP) proposal, BAP-578, introduces the Non-Fungible Agent (NFA) token standard, extending ERC-721 to enable autonomous, intelligent digital entities with optional learning capabilities on BNB Chain. The standard provides a dual-path architecture supporting both traditional static agents and advanced learning-enabled agents, ensuring broad adoption while enabling cutting-edge AI capabilities. + +A reference implementation is available [here](https://github.com/ChatAndBuild/non-fungible-agents-BAP-578) + +## 2. Abstract + +BAP-578 defines a standardized framework for Non-Fungible Agents (NFAs) - intelligent, autonomous digital entities that combine the ownership guarantees of NFTs with the adaptive capabilities of artificial intelligence. This standard merges the uniqueness of NFTs with autonomous functionality, positioning BNB Chain as the home for decentralized automation. + +The standard addresses the critical gap between traditional NFTs (which provide uniqueness and ownership) and the need for standardized interfaces that enable autonomous behavior and cross-platform agent interactions. BAP-578 provides a complete framework for creating, managing, and governing autonomous agent tokens with optional learning capabilities that allow agents to evolve and improve over time. + + + +Key features include: +- **Dual-Path Architecture**: Support for both JSON Light Memory (simple agents) and Merkle Tree Learning (evolving agents) + +- **Cryptographically verfiable learning through Merkle Proofs**: +- NFAs employ a **method-agnostic architecture** that enables cryptographically verifiable learning through Merkle tree structures. +- When users interact with an NFA, learning data, including preferences, patterns, confidence scores, and outcomes, is organized into a hierarchical tree structure. +- This data progresses through a systematic process: interaction → learning extraction → tree building → Merkle root calculation → on-chain update. +- Only the 32-byte Merkle root is stored on-chain, providing tamper-proof verification while preserving privacy and minimizing storage costs. +- The **flexible learning module architecture** allows developers to implement various AI optimization methods. +- Whether using **RAG**(leveraging off-chain vaults to retrieve past interactions), **MCP** (integrating with different AI providers through logic contracts), **fine-tuning, reinforcement learning, or hybrid approaches**, the BAP-578 standard provides the infrastructure without prescribing specific implementations. + +- **Standardized Agent Lifecycle**: Comprehensive lifecycle management from creation through evolution +- **Hybrid Storage Model**: On-chain security with off-chain flexibility for rich experiences +- **Composable Intelligence**: Agents can interact and collaborate while maintaining individual identity +- **Comprehensive Security**: Multi-layer security framework with circuit breakers and access controls +- **Backward Compatibility**: Full compatibility with existing ERC-721 infrastructure + +## 3. Motivation + +### 3.1 The Need for Standardization + +While traditional NFTs (BEP-721) provide uniqueness and ownership, they lack the standardized interfaces needed for autonomous behavior and cross-platform agent interactions. The current blockchain ecosystem lacks standardization for intelligent, autonomous digital entities, creating several critical challenges that BAP-578 addresses. + +#### 3.1.1 Consistent Agent Interfaces +BAP-578 defines standardized methods for action execution, state management, and logic upgrades that enable predictable interactions across platforms. Without this standardization, every intelligent token implementation requires custom integration work, forcing developers to learn new APIs and build specialized infrastructure for each project. + +#### 3.1.2 Interoperability Framework +The standard establishes common patterns for how agents interact with other contracts, services, and each other, creating an ecosystem where agents from different developers can work together. This prevents the creation of isolated ecosystems that limit user choice and prevent network effects that drive innovation. + +#### 3.1.3 Hybrid On-Chain/Off-Chain Architecture +BAP-578 provides clear separation between on-chain identity and permissions versus off-chain extended memory and complex behaviors, optimizing for both gas efficiency and rich functionality. This hybrid approach ensures that critical security and identity information is secured by blockchain consensus while keeping gas costs reasonable for agent operations. + +#### 3.1.4 Optional Learning System +The standard includes standardized interfaces for agent learning and evolution, allowing developers to choose between simple static agents or sophisticated learning agents. This addresses the lack of learning standardization that has made it impossible for agents to share knowledge or for the ecosystem to benefit from collective intelligence. + +#### 3.1.5 Security Boundaries +BAP-578 establishes standardized circuit breaker patterns, permission systems, and access controls that protect users and their assets, replacing the patchwork of security models that are difficult to audit and trust. + +### 3.2 Current Ecosystem Challenges + +#### 3.2.1 Integration Complexity +Every intelligent token implementation requires custom integration work, significantly increasing development costs and time-to-market. Developers must learn new APIs and build specialized infrastructure for each project, preventing the ecosystem from benefiting from shared infrastructure. + +#### 3.2.2 Limited Interoperability +Agents created on one platform cannot easily interact with agents from other platforms, creating isolated ecosystems that limit user choice and prevent network effects that drive innovation. + +#### 3.2.3 Inconsistent Security Models +Each implementation uses different approaches to permissions and security, creating a patchwork of security models that are difficult to audit and trust. + +#### 3.2.4 User Lock-in +Users become locked into specific platforms, unable to migrate their intelligent agents or leverage their accumulated learning across different applications. + +#### 3.2.5 Lack of Learning Portability +There has been no standardized approach to enabling agents to learn and evolve, making it impossible for agents to carry their knowledge and experience across different platforms and applications. + +### 3.3 Hybrid Architecture Benefits + +BAP-578 carefully balances which components belong on-chain versus off-chain to optimize for security, cost-effectiveness, and functionality: + +| Component | Storage | Rationale | +|-----------|---------|-----------| +| Agent Identity | On-chain | Core identity must be immutable and universally accessible | +| Ownership & Permissions | On-chain | Security and access control require consensus verification | +| Basic Metadata | On-chain | Essential for marketplace display and basic interactions | +| Logic Address | On-chain | Determines how the agent behaves when actions are executed | +| Learning Tree Root | On-chain | Cryptographic proof of learning state (32 bytes only) | +| Extended Memory | Off-chain (with hash verification) | Rich memory would be prohibitively expensive on-chain | +| Learning Tree Data | Off-chain (with Merkle verification) | Detailed learning data with cryptographic integrity | +| Complex Behaviors | Off-chain | Advanced AI behaviors require off-chain computation | +| Voice/Animation | Off-chain (with URI reference) | Media assets are too large for on-chain storage | + +This hybrid approach ensures that: +- Critical security and identity information is secured by blockchain consensus +- Gas costs remain reasonable for agent operations +- Rich agent experiences can evolve without blockchain limitations +- Learning capabilities are cryptographically verifiable yet cost-efficient + +BAP-578 addresses these challenges by providing: +- **Universal Compatibility**: Standardized interfaces that work across all platforms +- **User Ownership**: True ownership of intelligent agents and their accumulated knowledge +- **Ecosystem Interoperability**: Agents that maintain consistent behavior across applications +- **Innovation Acceleration**: Shared infrastructure that enables focus on unique value creation +- **Future-Ready Design**: Architecture that supports both current needs and future AI advances + +## 4. Specification + +### 4.1 Core Interface + +![BAP-578 Non-Fungible Agents](https://raw.githubusercontent.com/christelbuchanan/bap-578-non-fungible-agents-nfa/52c17583d32ddbb24d4dcadedafc1a2516f1015b/BAP-578.jpg) + +The BAP-578 standard extends ERC-721 with agent-specific functionality: + +```solidity +interface IBAP578 { + enum Status { Active, Paused, Terminated } + + struct State { + uint256 balance; + Status status; + address owner; + address logicAddress; + uint256 lastActionTimestamp; + } + + struct AgentMetadata { + string persona; // JSON-encoded character traits + string experience; // Agent's role/purpose summary + string voiceHash; // Audio profile reference + string animationURI; // Animation/avatar URI + string vaultURI; // Extended data storage URI + bytes32 vaultHash; // Vault content verification hash + } + + // Events + event ActionExecuted(address indexed agent, bytes result); + event LogicUpgraded(address indexed agent, address oldLogic, address newLogic); + event AgentFunded(address indexed agent, address indexed funder, uint256 amount); + event StatusChanged(address indexed agent, Status newStatus); + event MetadataUpdated(uint256 indexed tokenId, string metadataURI); + + // Core Functions + function executeAction(uint256 tokenId, bytes calldata data) external; + function setLogicAddress(uint256 tokenId, address newLogic) external; + function fundAgent(uint256 tokenId) external payable; + function getState(uint256 tokenId) external view returns (State memory); + function getAgentMetadata(uint256 tokenId) external view returns (AgentMetadata memory); + function updateAgentMetadata(uint256 tokenId, AgentMetadata memory metadata) external; + + // Lifecycle Management + function pause(uint256 tokenId) external; + function unpause(uint256 tokenId) external; + function terminate(uint256 tokenId) external; +} +``` + +### 4.2 Agent State Management + +Agents maintain state information that tracks their operational status, balance, and activity: + +```solidity +struct State { + uint256 balance; // BNB balance for gas fees + Status status; // Current operational status + address owner; // Agent owner address + address logicAddress; // Logic contract address + uint256 lastActionTimestamp; // Last action execution time +} +``` + +**Status Management:** +- `Active`: Agent can execute actions and interact normally +- `Paused`: Agent is temporarily suspended but can be resumed +- `Terminated`: Agent is permanently disabled with balance returned to owner + +### 4.3 Enhanced Metadata Schema + +BAP-578 extends standard ERC-721 metadata with agent-specific fields to support both simple and learning agents: + +#### 4.3.1 Core Agent Metadata +```solidity +struct AgentMetadata { + string persona; // JSON-encoded character traits, style, tone + string experience; // Short summary of agent's role/purpose + string voiceHash; // Reference ID to stored audio profile + string animationURI; // URI to video or animation file + string vaultURI; // URI to agent's vault (extended data storage) + bytes32 vaultHash; // Hash of vault contents for verification +} +``` + +#### 4.3.2 Enhanced Learning Metadata (Optional Extension) +```solidity +struct EnhancedAgentMetadata { + // Core fields (inherited from AgentMetadata) + string persona; + string experience; + string voiceHash; + string animationURI; + string vaultURI; + bytes32 vaultHash; + + // Learning-specific fields + bool learningEnabled; // Learning capability flag + address learningModule; // Learning module contract address + bytes32 learningTreeRoot; // Merkle root of learning tree + uint256 learningVersion; // Learning implementation version + uint256 lastLearningUpdate; // Timestamp of last learning update +} +``` + +### 4.4 Learning Module System + +The learning module system provides standardized interfaces for implementing different learning algorithms: + +#### 4.4.1 Learning Module Interface +```solidity +interface ILearningModule { + struct LearningMetrics { + uint256 totalInteractions; // Total user interactions + uint256 learningEvents; // Significant learning updates + uint256 lastUpdateTimestamp; // Last learning update time + uint256 learningVelocity; // Learning rate (scaled by 1e18) + uint256 confidenceScore; // Overall confidence (scaled by 1e18) + } + + struct LearningUpdate { + bytes32 previousRoot; // Previous Merkle root + bytes32 newRoot; // New Merkle root + bytes32 proof; // Merkle proof for update + bytes32 metadata; // Encoded learning data + } + + function updateLearning(uint256 tokenId, LearningUpdate calldata update) external; + function verifyLearning(uint256 tokenId, bytes32 claim, bytes32[] calldata proof) external view returns (bool); + function getLearningMetrics(uint256 tokenId) external view returns (LearningMetrics memory); + function getLearningRoot(uint256 tokenId) external view returns (bytes32); + function isLearningEnabled(uint256 tokenId) external view returns (bool); + function getVersion() external pure returns (string memory); + function recordInteraction(uint256 tokenId, string calldata interactionType, bool success) external; +} +``` + +#### 4.4.2 Merkle Tree Learning Implementation +Learning data is organized in a hierarchical tree structure with on-chain verification: + +- **On-Chain Storage**: Only the Merkle root (32 bytes) is stored on-chain +- **Off-Chain Storage**: Full learning tree stored in user-controlled vaults +- **Cryptographic Verification**: All learning claims verified through Merkle proofs +- **Gas Efficiency**: Minimal on-chain storage with full verification capabilities + +### 4.5 Memory Module Registry + +The memory module registry allows agents to register external memory sources: + +```solidity +interface IMemoryModuleRegistry { + struct MemoryModule { + address moduleAddress; + string metadata; + bytes32 metadataHash; + uint256 registrationTime; + bool isActive; + } + + function registerModule( + uint256 tokenId, + address moduleAddress, + string memory metadata, + bytes memory signature + ) external; + + function verifyModule( + uint256 tokenId, + address moduleAddress, + bytes32 expectedHash + ) external view returns (bool); + + function getModule(uint256 tokenId, address moduleAddress) + external view returns (MemoryModule memory); +} +``` + +### 4.6 Vault Permission System + +The vault permission system manages access to off-chain agent data: + +```solidity +interface IVaultPermissionManager { + enum PermissionLevel { READ_ONLY, WRITE, ADMIN, FULL_CONTROL } + + struct Permission { + address delegate; + PermissionLevel level; + uint256 expiryTime; + bool isActive; + } + + function delegateAccess( + uint256 tokenId, + address delegate, + PermissionLevel level, + uint256 expiryTime, + bytes memory signature + ) external; + + function revokeAccess(uint256 tokenId, address delegate) external; + function verifyAccess(uint256 tokenId, address accessor, PermissionLevel requiredLevel) + external view returns (bool); +} +``` + +### 4.7 Security Mechanisms + +#### 4.7.1 Circuit Breaker System +```solidity +interface ICircuitBreaker { + function pauseGlobally() external; + function pauseContract(address contractAddress) external; + function pauseAgent(uint256 tokenId) external; + function unpauseGlobally() external; + function unpauseContract(address contractAddress) external; + function unpauseAgent(uint256 tokenId) external; + + function isGloballyPaused() external view returns (bool); + function isContractPaused(address contractAddress) external view returns (bool); + function isAgentPaused(uint256 tokenId) external view returns (bool); +} +``` + +#### 4.7.2 Access Control +- **Owner-Only Operations**: Critical functions restricted to agent owner +- **Governance Controls**: System-wide parameters managed by governance +- **Time-Based Permissions**: Temporary access delegation with automatic expiry +- **Cryptographic Verification**: Signature-based verification for sensitive operations + +#### 4.7.3 Gas Limits +```solidity +uint256 public constant MAX_GAS_FOR_DELEGATECALL = 3000000; +uint256 public constant MAX_GAS_FOR_LEARNING_UPDATE = 500000; +``` + +### 4.8 Agent Templates + +BAP-578 includes a template system for specialized agent types: + +#### 4.8.1 Template Interface +```solidity +interface IAgentTemplate { + function getTemplateInfo() external view returns ( + string memory name, + string memory description, + uint256 version, + bytes32 codeHash + ); + + function initialize(uint256 tokenId, bytes memory initData) external; + function getCapabilities() external view returns (string[] memory); +} +``` + +#### 4.8.2 Available Templates +- **DeFiAgent**: Specialized for DeFi operations and trading +- **GameAgent**: Optimized for gaming and virtual world interactions +- **DAOAgent**: Designed for governance and DAO participation +- **CreatorAgent**: Focused on content creation and artistic endeavors +- **StrategicAgent**: Built for analysis and strategic decision-making + +### 4.9 Dual-Path Architecture + +BAP-578 offers two development paths to accommodate different use cases and developer preferences: + +#### 4.9.1 Path 1: JSON Light Memory (Default) +Perfect for most developers and immediate deployment: +- **Simple**: Familiar JSON metadata approach (like standard NFTs) +- **Fast**: Deploy agents immediately with no complexity +- **Compatible**: Works with all existing NFT infrastructure +- **Cost-effective**: Minimal gas costs for basic operations + +#### 4.9.2 Path 2: Merkle Tree Learning (Optional) +For advanced developers wanting truly evolving agents: +- **Evolving**: Agents that genuinely learn and improve over time +- **Provable**: Cryptographically verifiable learning history +- **Efficient**: Only 32-byte Merkle roots stored on-chain +- **Advanced**: Cutting-edge AI agent capabilities from day 1 + +#### 4.9.3 Key Benefits +- **Backward Compatibility**: All existing agents continue working unchanged +- **Optional Adoption**: Choose your complexity level +- **Upgrade Path**: Simple agents can enable learning later +- **Gas Optimized**: Learning data stored off-chain with on-chain verification +- **Future-Proof**: Architecture supports advanced AI developments + +## 5. Rationale + +### 5.1 Design Decisions + +#### 5.1.1 Dual-Path Architecture +The dual-path approach (JSON Light Memory vs. Merkle Tree Learning) ensures broad adoption by providing immediate utility while enabling advanced capabilities for users ready to embrace AI features. This design allows developers to start simple and upgrade to learning capabilities when needed. + +#### 5.1.2 Hybrid Storage Model +Storing critical identity on-chain while keeping detailed data off-chain optimizes for both security and cost-effectiveness. This approach ensures that essential security and identity information is secured by blockchain consensus while keeping gas costs reasonable for agent operations. + +#### 5.1.3 Modular Learning System +Pluggable learning modules allow for different algorithms and future upgrades without breaking existing functionality. This modularity enables the ecosystem to evolve and adopt new learning techniques as they become available. + +#### 5.1.4 Merkle Tree Learning +Using Merkle trees for learning data provides cryptographic verification while minimizing on-chain storage costs. This approach enables verifiable learning with only 32 bytes of on-chain storage per agent. + +#### 5.1.5 Standardization Focus +The emphasis on standardization addresses the critical gap in the current ecosystem where every intelligent token implementation requires custom integration work, preventing ecosystem-wide benefits and interoperability. + +### 5.2 Alternative Approaches Considered + +#### 5.2.1 Full On-Chain Storage +Rejected due to prohibitive gas costs for rich agent data and learning information. The hybrid approach provides the security benefits of on-chain storage for critical data while maintaining cost-effectiveness. + +#### 5.2.2 Centralized Learning +Rejected to maintain decentralization and user ownership principles. The Merkle tree approach provides verifiable learning while maintaining user control over their agent's data. + +#### 5.2.3 Single-Path Architecture +Rejected to ensure broad adoption across different user comfort levels with AI technology. The dual-path approach accommodates both simple use cases and advanced AI capabilities. + +#### 5.2.4 Custom Integration Approach +Rejected in favor of standardization to prevent ecosystem fragmentation and enable universal compatibility across platforms and applications. + +## 6. Backwards Compatibility + +BAP-578 is fully backwards compatible with ERC-721: +- All ERC-721 functions remain unchanged +- Existing NFT marketplaces can list BAP-578 tokens +- Standard NFT wallets can hold and transfer BAP-578 tokens +- Additional functionality is opt-in and doesn't affect basic operations +- Simple agents using JSON Light Memory work exactly like traditional NFTs +- Learning capabilities can be enabled later without breaking existing functionality + +## 7. Test Cases + +### 7.1 Basic Agent Operations +```solidity +// Test agent creation +function testAgentCreation() public { + uint256 tokenId = bap578.createAgent( + user, + logicAddress, + "ipfs://metadata", + basicMetadata + ); + + assertEq(bap578.ownerOf(tokenId), user); + assertEq(bap578.getState(tokenId).status, Status.Active); +} + +// Test action execution +function testActionExecution() public { + bytes memory data = abi.encodeWithSignature("performAction()"); + bap578.executeAction(tokenId, data); + + // Verify action was executed + assertTrue(actionExecuted); +} +``` + +### 7.2 Learning Agent Operations +```solidity +// Test learning update +function testLearningUpdate() public { + LearningUpdate memory update = LearningUpdate({ + previousRoot: currentRoot, + newRoot: newRoot, + proof: merkleProof, + metadata: learningData + }); + + learningModule.updateLearning(tokenId, update); + + assertEq(learningModule.getLearningRoot(tokenId), newRoot); +} + +// Test learning enablement +function testEnableLearning() public { + bytes32 initialRoot = keccak256("initial_learning_data"); + + bap578Enhanced.enableLearning(tokenId, learningModule.address, initialRoot); + + assertTrue(bap578Enhanced.isLearningEnabled(tokenId)); +} +``` + +### 7.3 Security Tests +```solidity +// Test unauthorized access prevention +function testUnauthorizedAccess() public { + vm.prank(unauthorizedUser); + vm.expectRevert("BAP578: caller is not agent owner"); + bap578.executeAction(tokenId, data); +} + +// Test circuit breaker +function testCircuitBreaker() public { + circuitBreaker.pauseGlobally(); + + vm.expectRevert("BAP578: global pause active"); + bap578.executeAction(tokenId, data); +} +``` + +### 7.4 Dual-Path Compatibility Tests +```solidity +// Test simple agent compatibility +function testSimpleAgentCompatibility() public { + // Create simple agent + uint256 simpleTokenId = bap578.createAgent(user, logicAddress, "ipfs://metadata", basicMetadata); + + // Verify it works like standard NFT + assertEq(bap578.ownerOf(simpleTokenId), user); + assertFalse(bap578Enhanced.isLearningEnabled(simpleTokenId)); +} + +// Test learning upgrade path +function testLearningUpgradePath() public { + // Start with simple agent + uint256 tokenId = bap578.createAgent(user, logicAddress, "ipfs://metadata", basicMetadata); + + // Enable learning later + bytes32 initialRoot = keccak256("initial_learning_data"); + bap578Enhanced.enableLearning(tokenId, learningModule.address, initialRoot); + + // Verify learning is now enabled + assertTrue(bap578Enhanced.isLearningEnabled(tokenId)); +} +``` + +## 8. Implementation + +A reference implementation is available at: https://github.com/ChatAndBuild/non-fungible-agents-BAP-578 + +The implementation includes: +- Core BAP-578 contract with full specification compliance +- Enhanced BAP-578 contract with learning capabilities +- Learning module implementations (Merkle tree, federated learning) +- Memory module registry +- Vault permission manager +- Circuit breaker system +- Agent factory for streamlined deployment +- Multiple agent templates for different use cases +- Dual-path architecture supporting both simple and learning agents +- Migration tools for upgrading simple agents to learning agents + +## 9. Security Considerations + +### 9.1 Smart Contract Security +- **Reentrancy Protection**: All fund-handling functions use ReentrancyGuard +- **Access Control**: Strict permissions for sensitive operations +- **Gas Limits**: Prevent out-of-gas attacks on delegatecall operations +- **Circuit Breakers**: Emergency pause mechanisms for rapid incident response + +### 9.2 Learning Security +- **Rate Limiting**: Prevent spam and gaming of learning systems (maximum 50 learning updates per day per agent) +- **Cryptographic Verification**: All learning claims must be provable through Merkle proofs +- **Module Approval**: Only governance-approved learning modules allowed +- **Privacy Protection**: Learning data access is controlled and auditable +- **Tamper-Proof History**: Learning history cannot be falsified due to cryptographic verification + +### 9.3 Economic Security +- **Agent Funding**: Agents must maintain balance for gas fees +- **Owner Controls**: Only owners can modify critical agent parameters +- **Governance Oversight**: System parameters controlled by decentralized governance + +### 9.4 Data Security +- **Vault Permissions**: Granular access control for off-chain data +- **Signature Verification**: Cryptographic verification for sensitive operations +- **Hash Verification**: Content integrity verification for off-chain data +- **Time-Based Access**: Delegated permissions with automatic expiry + +### 9.5 Dual-Path Security +- **Backward Compatibility**: Simple agents maintain all existing security guarantees +- **Optional Complexity**: Learning features are opt-in and don't affect simple agent security +- **Upgrade Safety**: Enabling learning on existing agents doesn't compromise existing functionality + +## 10. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BAPs/README.md b/BAPs/README.md new file mode 100644 index 000000000..8c49d9c49 --- /dev/null +++ b/BAPs/README.md @@ -0,0 +1,29 @@ +# BNB Chain Application Proposals (BAPs) + +- [BNB Chain Application Proposals (BAPs)](#bnb-chain-application-proposals-baps) + - [What is a BAP?](#what-is-a-bap) + - [BAP Workflow](#bap-workflow) + - [BAP Format](#bap-format) + - [Numbering and File Naming](#numbering-and-file-naming) + +## What is a BAP? + +BNB Chain Application Proposals (BAPs) are community-driven design documents that specify application-level standards, conventions, and best practices for the BNB Chain ecosystem. BAPs aim to improve interoperability and user experience across dApps, wallets, services, and tooling. + +- Scope includes: token and NFT standards, wallet interaction flows, RPC/ABI conventions, indexer/query schemas, cross-dApp messaging, off-chain service interfaces, and other app-layer norms. +- BAPs are distinct from BEPs (BNB Chain Evolution Proposals), which target protocol/consensus or node-level changes. + +## BAP Workflow + +BAP workflow follows the process described in [BEP-1](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP1.md#4--bep-workflow). +![overall workflow](../BEPs/assets/bep-1/workflow.png) + +The **Review** stage is central to BAPs and requires feedback from the community, especially from relevant ecosystem partners. Feedback can be provided in this repository or on the [BNB Chain Forum](https://forum.bnbchain.org/). PR status is maintained by the BAP editors, primarily the maintainers of this GitHub repository. + +## BAP Format +The BAP format follows the [BEP format](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP1.md#5--bep-format). Providing reference implementations is strongly recommended to clarify interface definitions. + +### Numbering and File Naming + +- Provisional PRs may use `BAP-xxxx.md`; a concrete number is assigned upon Acceptance. +- Place the file at `BAPs/BAP-.md` with a clear, descriptive title. diff --git a/BEP1.md b/BEP1.md deleted file mode 100644 index 76a35609b..000000000 --- a/BEP1.md +++ /dev/null @@ -1,58 +0,0 @@ -# BEP 1: Purpose and Guidelines - - -- [BEP 1: Purpose and Guidelines](#bep-1--purpose-and-guidelines) - * [1. What is BEP?](#1--what-is-bep) - * [2. BEP Rationale](#2--bep-rationale) - * [3. BEP Types](#3--bep-types) - * [4. BEP Workflow](#4--bep-workflow) - * [5. Reference](#5--reference) - * [6. License](#6--license) - - -## 1. What is BEP? - -BEP stands for Binance Chain Evolution Proposal. Each BEP will be a proposal document providing information to the Binance Chain/DEX community. The BEP should provide a concise technical specification of the feature or improvement and the rationale behind it. Each BEP proposer is responsible for building consensus within the community and documenting dissenting opinions. Each BEP has a unique index number. - -## 2. BEP Rationale - -BEP is the primary mechanism for proposing new features, for collecting community technical input on an issue, and for documenting the design decisions that go into Binance Chain. Because the BEP are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal. - -For Binance Chain contributors, BEPs are a convenient way to track the progress of their implementation. This will give end users a convenient way to know the current status of a given feature, function or improvement. - -## 3. BEP Types - -There are three types of BEP: - -- Feature Request: A Feature Request BEP describes functional changes on Binance Chain or/and Binance DEX, such as a change to the network protocol, proposer selection mechanism in consensus algorithm, change in block size or fee mechanism in application level. -- Improvement: Improvements are advice gathered from the community. -- Standard: This kind of proposal will change the workflow of Binance Chain working process, like this BEP itself. - -## 4. BEP Workflow - -![img](https://lh3.googleusercontent.com/auaU1Ur5SZZKVcwQrFrHN-3T1vUP8C1wCjFWqJzzJpcdVCHR4JXe1Mzm7hCFuoEqVjkUOZIF5WrwK47jGw8r3wp9RLEPvAWY6DOsncNz0yCeVc84qew1Xf7ouk1qrcNdXpjGSNQG) - -*Figure 1: BEP workflow* - -Each status change is requested by the BEP author and reviewed by the BEP editors. Use a pull request to update the status. - -- Work in progress (WIP) -- A community member will write a draft BEP as a pull request. -- Draft -- An editor will add notes and some requests, then if all changes are made, it will go to the next stage. If it’s not approved, it will be dropped. -- Final -- This BEP is ready to be implemented -- Implementation -- the development team could start work on this BEP - -Other exceptional statuses include: - -- Deferred -- This is for some BEPs that depend on changes of a future BEP implementation. The current BEP will stay in the *Deferred* state and wait for the hardfork. -- Dropped -- A BEP that is dropped and will not be implemented. Usually, it is due to some prerequisite conditions that are not true anymore. -- Superseded -- A BEP which was previously final but is no longer considered applicable. This happens when an on-going implementation conflicts with a newly created BEP in *Final* state. The latter needs to refer to the incompatibility BEP and elaborate backward incompatibilities issue. - -## 5. Reference - -Ethereum Improvement Proposals: [https://github.com/ethereum/EIPs](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1.md) - -Bitcoin Improvement Proposals: - -## 6. License - -All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-225.md b/BEPs/BEP-225.md new file mode 100644 index 000000000..0d925feb4 --- /dev/null +++ b/BEPs/BEP-225.md @@ -0,0 +1,133 @@ +
+  BEP: 225
+  Title: Implement EIP2565 ModExp Gas Cost 
+  Status: Enabled
+  Type: Standards
+  Created: 2023-4-27
+
+ +# BEP-225: Implement EIP-2565 ModExp Gas Cost +- [BEP-225: Implement EIP2565 ModExp Gas Cost](#bep-225-implement-eip-2565-modexp-gas-cost) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Test Cases](#6-test-cases) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + +## 1. Summary + +As part of Berlin upgrade, EIP-2565: ModExp Gas Cost is required to be implemented to BSC. + +This EIP Defines the gas cost of the `ModExp (0x00..05)` precompile. + +## 2. Abstract + +To accurately reflect the real world operational cost of the `ModExp` precompile, this EIP specifies an algorithm for +calculating the gas cost. + +This algorithm approximates the multiplication complexity cost and multiplies that by an approximation of the +iterations required to execute the exponentiation. + +## 3. Motivation + +Refer to EIP-2565 description: + +Modular exponentiation is a foundational arithmetic operation for many cryptographic functions including signatures, +VDFs, SNARKs, accumulators, and more. Unfortunately, the ModExp precompile is currently over-priced, making these +operations inefficient and expensive. + +By reducing the cost of this precompile, these cryptographic functions become more practical, enabling improved +security, stronger randomness (VDFs), and more. + +## 4. Specification + +As of `FORK_BLOCK_NUMBER`, the gas cost of calling the precompile at address `0x0000000000000000000000000000000000000005` +will be calculated as follows: + +``` +def calculate_multiplication_complexity(base_length, modulus_length): +max_length = max(base_length, modulus_length) +words = math.ceil(max_length / 8) +return words**2 + +def calculate_iteration_count(exponent_length, exponent): +iteration_count = 0 +if exponent_length <= 32 and exponent == 0: iteration_count = 0 +elif exponent_length <= 32: iteration_count = exponent.bit_length() - 1 +elif exponent_length > 32: iteration_count = (8 * (exponent_length - 32)) + ((exponent & (2**256 - 1)).bit_length() - 1) +return max(iteration_count, 1) + +def calculate_gas_cost(base_length, modulus_length, exponent_length, exponent): +multiplication_complexity = calculate_multiplication_complexity(base_length, modulus_length) +iteration_count = calculate_iteration_count(exponent_length, exponent) +return max(200, math.floor(multiplication_complexity * iteration_count / 3)) +``` + +## 5. Rationale + +After benchmarking the ModExp precompile, we discovered that it is ‘overpriced’ relative to other precompiles. We also discovered that the current gas pricing formula could be improved to better estimate the computational complexity of various ModExp input variables. The following changes improve the accuracy of the ModExp pricing: + +### Modify `computational complexity` formula to better reflect the computational complexity +The complexity function defined in EIP-198 is as follow: + +``` +def mult_complexity(x): +if x <= 64: return x ** 2 +elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 +else: return x ** 2 // 16 + 480 * x - 199680 +``` + +where is x is max(length_of_MODULUS, length_of_BASE) + +The complexity formula in EIP-198 was meant to approximate the difficulty of Karatsuba multiplication. However, we found a better approximation for modelling modular exponentiation. In the complexity formula defined in this EIP, x is divided by 8 to account for the number of limbs in multiprecision arithmetic. A comparison of the current ‘complexity’ function and the proposed function against the execution time can be seen below: + +![Complexity Function](./assets/BEP-225/Complexity_Regression.png) + +The complexity function defined here has a better fit vs. the execution time when compared to the EIP-198 complexity function. This better fit is because this complexity formula accounts for the use of binary exponentiation algorithms that are used by ‘bigint’ libraries for large exponents. You may also notice the regression line of the proposed complexity function bisects the test vector data points. This is because the run time varies depending on if the modulus is even or odd. + +### Change the value of GQUADDIVISOR + After changing the ‘computational complexity’ formula in EIP-198 to the one defined here it is necessary to change QGUADDIVSOR to bring the gas costs inline with their runtime. By setting the QGUADDIVISOR to 3 the cost of the ModExp precompile will have a higher cost (gas/second) than other precompiles such as ECRecover. + +![GQuad_Change](./assets/BEP-225/GQuad_Change.png) + +### Set a minimum gas cost to prevent abuse + This prevents the precompile from underpricing small input values. + +## 6. Test Cases +There are no changes to the underlying interface or arithmetic algorithms, so the existing test vectors can be reused. Below is a table with the updated test vectors: + +| Test Case | EIP-198 Pricing | EIP-2565 Pricing | +| --------- | -----------------|------------------| +| modexp_nagydani_1_square | 204 | 200 | +| modexp_nagydani_1_qube | 204 | 200 | +| modexp_nagydani_1_pow0x10001 | 3276 | 341 | +| modexp_nagydani_2_square |665| 200 | +| modexp_nagydani_2_qube |665| 200 | +| modexp_nagydani_2_pow0x10001 |10649| 1365 | +| modexp_nagydani_3_square |1894| 341 | +| modexp_nagydani_3_qube |1894| 341 | +| modexp_nagydani_3_pow0x10001 |30310 | 5461 | +| modexp_nagydani_4_square |5580 | 1365 | +| modexp_nagydani_4_qube |5580 | 1365 | +| modexp_nagydani_4_pow0x10001 |89292 | 21845 | +| modexp_nagydani_5_square |17868 | 5461 | +| modexp_nagydani_5_qube |17868 | 5461 | +| modexp_nagydani_5_pow0x10001 |285900 | 87381 | + +## 7. Security Considerations + +The biggest security consideration for this EIP is creating a potential DoS vector by making ModExp operations too inexpensive relative to their computation time. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Most description of this BEP refer to [EIP-2565](https://eips.ethereum.org/EIPS/eip-2565): + +Kelly Olson (@ineffectualproperty), Sean Gulley (@sean-sn), Simon Peffers (@simonatsn), Justin Drake (@justindrake), Dankrad Feist (@dankrad), "EIP-2565: ModExp Gas Cost," Ethereum Improvement Proposals, no. 2565, March 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-2565. \ No newline at end of file diff --git a/BEPs/BEP-229.md b/BEPs/BEP-229.md new file mode 100644 index 000000000..83c549a1b --- /dev/null +++ b/BEPs/BEP-229.md @@ -0,0 +1,95 @@ +
+  BEP: 229
+  Title: Implement EIP-2718 Typed Transaction Envelope
+  Status: Enabled
+  Type: Standards
+  Created: 2023-4-19
+
+ +# BEP-229: Implement EIP-2718 Typed Transaction Envelope +- [BEP-229: Implement EIP-2718 Typed Transaction Envelope](#bep-229-implement-eip-2718-typed-transaction-envelope) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + +## 1. Summary +As part of Berlin upgrade, EIP-2718 Typed Transaction Envelope is required to be implemented to BSC. + +## 2. Abstract +`TransactionType || TransactionPayload` is a valid transaction and `TransactionType || ReceiptPayload` is a valid transaction receipt where `TransactionType` identifies the format of the transaction and `*Payload` is the transaction/receipt contents, which are defined in future EIPs. + +## 3. Motivation +In the past, when we have wanted to add new transaction types we have had to ensure they were backward compatible with all other transactions, meaning that you could differentiate them based only on the encoded payload, and it was not possible to have a transaction that matched both types. +This was seen in [EIP-155](./eip-155.md) where the new value was bit-packed into one of the encoded fields. +There are multiple proposals in discussion that define new transaction types such as one that allows EOA accounts to execute code directly within their context, one that enables someone besides `msg.sender` to pay for gas, and proposals related to layer 1 multi-sig transactions. +These all need to be defined in a way that is mutually compatible, which quickly becomes burdensome to EIP authors and to clients who now have to follow complex rules for differentiating transaction type. + +By introducing an envelope transaction type, we only need to ensure backward compatibility with existing transactions and from then on we just need to solve the much simpler problem of ensuring there is no numbering conflict between `TransactionType`s. + +## 4. Specification +### Definitions +* `||` is the byte/byte-array concatenation operator. + +### Transactions +As of `FORK_BLOCK_NUMBER`, the transaction root in the block header **MUST** be the root hash of `patriciaTrie(rlp(Index) => Transaction)` where: +* `Index` is the index in the block of this transaction +* `Transaction` is either `TransactionType || TransactionPayload` or `LegacyTransaction` +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction +* `TransactionPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyTransaction` is `rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])` + +All signatures for future transaction types **SHOULD** include the `TransactionType` as the first byte of the signed data. +This makes it so we do not have to worry about signatures for one transaction type being used as signatures for a different transaction type. + +### Receipts +As of `FORK_BLOCK_NUMBER`, the receipt root in the block header **MUST** be the root hash of `patriciaTrie(rlp(Index) => Receipt)` where: +* `Index` is the index in the block of the transaction this receipt is for +* `Receipt` is either `TransactionType || ReceiptPayload` or `LegacyReceipt` +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction +* `ReceiptPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs +* `LegacyReceipt` is `rlp([status, cumulativeGasUsed, logsBloom, logs])` + +The `TransactionType` of the receipt **MUST** match the `TransactionType` of the transaction with a matching `Index`. + +## 5. Rationale +### TransactionType only goes up to 0x7f +For the forseable future, 0x7f is plenty and it leaves open a number of options for extending the range such as using the high bit as a continuation bit. +This also prevents us from colliding with legacy transaction types, which always start with a byte `>= 0xc0`. +### **SHOULD** instead of **MUST** for the TransactionType being first byte of signed data +While it is strongly recommended that all future transactions sign the first byte to ensure that there is no problem with signature reuse, the authors acknowledge that this may not always make sense or be possible. +One example where this isn't possible is wrapped legacy transactions that are signature compatible with the legacy signing scheme. +Another potential situation is one where transactions don't have a signature in the traditional sense and instead have some other mechanism for determining validity. +### TransactionType selection algorithm +There was discussion about defining the `TransactionType` identifier assignment/selection algorithm in this standard. +While it would be nice to have a standardized mechanism for assignment, at the time of writing of this standard there is not a strong need for it so it was deemed out of scope. +A future EIP may introduce a standard for TransactionType identifier assignment if it is deemed necessary. +### Opaque byte array rather than an RLP array +By having the second byte on be opaque bytes, rather than an RLP (or other encoding) list, we can support different encoding formats for the transaction payload in the future such as SSZ, LEB128, or a fixed width format. +### ORIGIN and CALLER +There was discussion about having ORIGIN and CALLER opcodes become dependent on the transaction type, so that each transaction type could define what those opcodes returned. +However, there is a desire to make transaction type opaque to the contracts to discourage contracts treating different types of transactions differently. +There also were concerns over backward compatibility with existing contracts which make assumptions about ORIGIN and CALLER opcodes. +Going forward, we will assume that all transaction types will have an address that reasonably represents a `CALLER` of the first EVM frame and `ORIGIN` will be the same address in all cases. +If a transaction type needs to supply additional information to contracts, they will need a new opcode. + +## 6. Backwards Compatibility +Clients can differentiate between the legacy transactions and typed transactions by looking at the first byte. +If it starts with a value in the range `[0, 0x7f]` then it is a new transaction type, if it starts with a value in the range `[0xc0, 0xfe]` then it is a legacy transaction type. +`0xff` is not realistic for an RLP encoded transaction, so it is reserved for future use as an extension sentinel value. + +## 7. Security Considerations +When designing a new 2718 transaction type, it is **STRONGLY** recommended to include the transaction type as the first byte of the signed payload. If you fail to do this, it is possible that your transaction may be signature compatible with transactions of another type which can introduce security vulnerabilities for users. + +## 8. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference +Most description of this BEP refer to [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) + +Micah Zoltu (@MicahZoltu), "EIP-2718: Typed Transaction Envelope," Ethereum Improvement Proposals, no. 2718, June 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-2718. diff --git a/BEPs/BEP-230.md b/BEPs/BEP-230.md new file mode 100644 index 000000000..db69c6db4 --- /dev/null +++ b/BEPs/BEP-230.md @@ -0,0 +1,183 @@ +
+  BEP: 230
+  Title: Implement EIP-2929 Gas cost increases for state access opcodes
+  Status: Enabled
+  Type: Standards
+  Created: 2023-4-19
+
+ +# BEP-230: Implement EIP-2929 Gas cost increases for state access opcodes +- [BEP-230: Implement EIP-2929 Gas cost increases for state access opcodes](#bep-230-implement-eip-2929-gas-cost-increases-for-state-access-opcodes) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#7-test-cases) + - [8. Security Considerations](#8-security-considerations) + - [9. License](#9-license) + - [10. Reference](#10-reference) + +## 1. Summary +As part of Berlin upgrade, EIP-2929 Gas cost increases for state access opcodes is required to be implemented to BSC. + +Increases gas cost for `SLOAD`, `*CALL`, `BALANCE`, `EXT*` and `SELFDESTRUCT` when used for the first time in a transaction. + +## 2. Abstract + +Increase the gas cost of `SLOAD` (`0x54`) to 2100, and the `*CALL` opcode family (`0xf1`, `f2`, `f4`, `fA`), `BALANCE` `0x31` and the `EXT*` opcode family (`0x3b`, `0x3c`, `0x3f`) to 2600. Exempts (i) precompiles, and (ii) addresses and storage slots that have already been accessed in the same transaction, which get a decreased gas cost. Additionally reforms `SSTORE` metering and `SELFDESTRUCT` to ensure "de-facto storage loads" inherent in those opcodes are priced correctly. + +## 3. Motivation + +Generally, the main function of gas costs of opcodes is to be an estimate of the time needed to process that opcode, the goal being for the gas limit to correspond to a limit on the time needed to process a block. However, storage-accessing opcodes (`SLOAD`, as well as the `*CALL`, `BALANCE` and `EXT*` opcodes) have historically been underpriced. In the 2016 Shanghai DoS attacks, once the most serious client bugs were fixed, one of the more durably successful strategies used by the attacker was to simply send transactions that access or call a large number of accounts. + +Gas costs were increased to mitigate this, but recent numbers suggest they were not increased enough. Quoting [https://arxiv.org/pdf/1909.07220.pdf](https://arxiv.org/pdf/1909.07220.pdf): + +> Although by itself, this issue might seem benign, `EXTCODESIZE` forces the client to search the contract ondisk, resulting in IO heavy transactions. While replaying the Ethereum history on our hardware, the malicious transactions took around 20 to 80 seconds to execute, compared to a few milliseconds for the average transactions + +This proposed EIP increases the costs of these opcodes by a factor of ~3, reducing the worst-case processing time to ~7-27 seconds. Improvements in database layout that involve redesigning the client to read storage directly instead of hopping through the Merkle tree would decrease this further, though these technologies may take a long time to fully roll out, and even with such technologies the IO overhead of accessing storage would remain substantial. + +A secondary benefit of this EIP is that it also performs most of the work needed to make [stateless witness sizes](https://ethereum-magicians.org/t/protocol-changes-to-bound-witness-size/3885) in Ethereum acceptable. Assuming [a switch to binary tries](https://ethresear.ch/t/binary-trie-format/7621), the theoretical maximum witness size not including code size (hence "most of the work" and not "all") would decrease from `(12500000 gas limit) / (700 gas per BALANCE) * (800 witness bytes per BALANCE) ~= 14.3M bytes` to `12500000 / 2600 * 800 ~= 3.85M bytes`. Pricing for code access could be changed when code merklization is implemented. + +In the further future, there are similar benefits in the case of SNARK/STARK witnesses. Recent numbers from Starkware suggest that they are able to prove 10000 Rescue hashes per second on a consumer desktop; assuming 25 hashes per Merkle branch, and a block full of state accesses, at present this would imply a witness would take `12500000 / 700 * 25 / 10000 ~= 44.64` seconds to generate, but after this EIP that would reduce to `12500000 / 2500 * 25 / 10000 ~= 12.5` seconds, meaning that a single desktop computer would be able to generate witnesses on time under any conditions. Future gains in STARK proving could be spent on either (i) using a more expensive but robust hash function or (ii) reducing proving times further, reducing the delay and hence improving user experience of stateless clients that rely on such witnesses. + +## 4. Specification + +### Parameters + +| Constant | Value | +|-----------------------|-------| +| `FORK_BLOCK` | 12244000 | +| `COLD_SLOAD_COST` | 2100 | +| `COLD_ACCOUNT_ACCESS_COST` | 2600 | +| `WARM_STORAGE_READ_COST` | 100 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +When executing a transaction, maintain a set `accessed_addresses: Set[Address]` and `accessed_storage_keys: Set[Tuple[Address, Bytes32]]` . + +The sets are transaction-context-wide, implemented identically to other transaction-scoped constructs such as the self-destruct-list and global `refund` counter. In particular, if a scope reverts, the access lists should be in the state they were in before that scope was entered. + +When a transaction execution begins, +- `accessed_storage_keys` is initialized to empty, and +- `accessed_addresses` is initialized to include + - the `tx.sender`, `tx.to` (or the address being created if it is a contract creation transaction) + - and the set of all precompiles. + + +### Storage read changes + +When an address is either the target of a (`EXTCODESIZE` (`0x3B`), `EXTCODECOPY` (`0x3C`), `EXTCODEHASH` (`0x3F`) or `BALANCE` (`0x31`)) opcode or the target of a (`CALL` (`0xF1`), `CALLCODE` (`0xF2`), `DELEGATECALL` (`0xF4`), `STATICCALL` (`0xFA`)) opcode, the gas costs are computed as follows: + +* If the target is not in `accessed_addresses`, charge `COLD_ACCOUNT_ACCESS_COST` gas, and add the address to `accessed_addresses`. +* Otherwise, charge `WARM_STORAGE_READ_COST` gas. + +In all cases, the gas cost is charged and the map is updated at the time that the opcode is being called. +When a `CREATE` or `CREATE2` opcode is called, immediately (ie. before checks are done to determine whether or not the address is unclaimed) add the address being created to `accessed_addresses`, but gas costs of `CREATE` and `CREATE2` are unchanged. +Clarification: If a `CREATE`/`CREATE2` operation fails later on, e.g during the execution of `initcode` or has insufficient gas to store the code in the state, the `address` of the contract itself remains in `access_addresses` (but any additions made within the inner scope are reverted). + +For `SLOAD`, if the `(address, storage_key)` pair (where `address` is the address of the contract whose storage is being read) is not yet in `accessed_storage_keys`, charge `COLD_SLOAD_COST` gas and add the pair to `accessed_storage_keys`. If the pair is already in `accessed_storage_keys`, charge `WARM_STORAGE_READ_COST` gas. + +Note: For call-variants, the `100`/`2600` cost is applied immediately (exactly like how `700` was charged before this EIP), i.e: before calculating the `63/64ths` available for entering the call. + +Note 2: There is currently no way to perform a 'cold sload read/write' on a 'cold account', simply because in order to read/write a `slot`, the execution must already be inside the `account`. Therefore, the behaviour of cold storage reads/writes on cold accounts is undefined as of this EIP. Any future EIP which +proposes to add 'remote read/write' would need to define the pricing behaviour of that change. + +### SSTORE changes + +When calling `SSTORE`, check if the `(address, storage_key)` pair is in `accessed_storage_keys`. If it is not, charge an additional `COLD_SLOAD_COST` gas, and add the pair to `accessed_storage_keys`. Additionally, modify the parameters defined in [EIP-2200](./eip-2200.md) as follows: + +| Parameter | Old value | New value | +| --- | --- |----------------------------| +| `SLOAD_GAS` | 800 | `= WARM_STORAGE_READ_COST` | +| `SSTORE_RESET_GAS` | 5000 | `5000 - COLD_SLOAD_COST` | + +The other parameters defined in EIP 2200 are unchanged. +Note: The constant `SLOAD_GAS` is used in several places in EIP 2200, e.g `SSTORE_SET_GAS - SLOAD_GAS`. Implementations that are using composite definitions have to ensure to update those definitions too. + +### SELFDESTRUCT changes + +If the ETH recipient of a `SELFDESTRUCT` is not in `accessed_addresses` (regardless of whether or not the amount sent is nonzero), charge an additional `COLD_ACCOUNT_ACCESS_COST` on top of the existing gas costs, and add the ETH recipient to the set. + +Note: `SELFDESTRUCT` does not charge a `WARM_STORAGE_READ_COST` in case the recipient is already warm, which differs from how the other call-variants work. The reasoning behind this is to keep the changes small, a `SELFDESTRUCT` already costs `5K` and is a no-op if invoked more than once. + +## 5. Rationale + +### Opcode costs vs charging per byte of witness data + +The natural alternative path to changing gas costs to reflect witness sizes is to charge per byte of witness data. However, that would take a longer time to implement, hampering the goal of providing short-term security relief. Furthermore, following that path faithfully would lead to extremely high gas costs to transactions that touch contract code, as one would need to charge for all 24576 contract code bytes; this would be an unacceptably high burden on developers. It is better to wait for [code merklization](https://medium.com/ewasm/evm-bytecode-merklization-2a8366ab0c90) to start trying to properly account for gas costs of accessing individual chunks of code; from a short-term DoS prevention standpoint, accessing 24 kB from disk is not much more expensive than accessing 32 bytes from disk, so worrying about code size is not necessary. + +### Adding the accessed_addresses / accessed_storage_keys sets + +The sets of already-accessed accounts and storage slots are added to avoid needlessly charging for things that can be cached (and in all performant implementations already are cached). Additionally, it removes the current undesirable status quo where it is needlessly unaffordable to do self-calls or call precompiles, and enables contract breakage mitigations that involve pre-fetching some storage key allowing a future execution to still take the expected amount of gas. + +### SSTORE gas cost change + +The change to SSTORE is needed to avoid the possibility of a DoS attack that "pokes" a randomly chosen zero storage slot, changing it from 0 to 0 at a cost of 800 gas but requiring a de-facto storage load. The `SSTORE_RESET_GAS` reduction ensures that the total cost of SSTORE (which now requires paying the `COLD_SLOAD_COST`) remains unchanged. Additionally, note that applications that do `SLOAD` followed by `SSTORE` (eg. `storage_variable += x`) _would actually get cheaper_! + +### Change SSTORE accounting only minimally + +The SSTORE gas costs continue to use Wei Tang's original/current/new approach, instead of being redesigned to use a dirty map, because Wei Tang's approach correctly accounts for the actual costs of changing storage, which only care about current vs final value and not intermediate values. + +### How would gas consumption of average applications increase under this proposal? + +#### Rough analysis from witness sizes + +We can look at [Alexey Akhunov's earlier work](https://medium.com/@akhounov/data-from-the-ethereum-stateless-prototype-8c69479c8abc) for data on average-case blocks. In summary, average blocks have witness sizes of ~1000 kB, of which ~750 kB is Merkle proofs and not code. Assuming a conservative 2000 bytes per Merkle branch this implies ~375 accesses per block (SLOADs have a similar gas-increase-to-bytes ratio so there's no need to analyze them separately). + +Data on [txs per day](https://etherscan.io/chart/tx) and [blocks per day](https://etherscan.io/chart/blocks) from Etherscan gives ~160 transactions per block (reference date: Jul 1), implying a large portion of those accesses are just the `tx.sender` and `tx.to` which are excluded from gas cost increases, though likely less than 320 due to duplicate addresses. + +Hence, this implies ~50-375 chargeable accesses per block, and each access suffers a gas cost increase of 1900; `50 * 1900 = 95000` and `375 * 1900 = 712500`, implying the gas limit would need to be raised by ~1-6% to compensate. However, this analysis may be complicated further in either direction by (i) accounts / storage keys being accessed in multiple transactions, which would appear once in the witness but twice in gas cost increases, and (ii) accounts / storage keys being accessed multiple times in the same transaction, which lead to gas cost _decreases_. + +#### Goerli analysis + +A more precise analysis can be found by scanning Goerli transactions, as done by Martin Swende here: https://github.com/holiman/gasreprice + +The conclusion is that on average gas costs increase by ~2.36%. One major contributing factor to reducing gas costs is that a large number of contracts inefficiently read the same storage slot multiple times, which leads to this EIP giving a few transactions gas cost _savings_ of over 10%. + +## 6. Backwards Compatibility + +These gas cost increases may potentially break contracts that depend on fixed gas costs; see the security considerations section for details and arguments for why we expect the total risks to be low and how if desired they can be reduced further. + +## 7. Test Cases + +Some test cases can be found here: https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a + +Ideally we would test the following: + +* SLOAD the same storage slot {1, 2, 3} times +* CALL the same address {1, 2, 3} times +* (SLOAD | CALL) in a sub-call, then revert, then (SLOAD | CALL) the same (storage slot | address) again +* Sub-call, SLOAD, sub-call again, revert the inner sub-call, SLOAD the same storage slot +* SSTORE the same storage slot {1, 2, 3} times, using all combinations of zero/nonzero for original value and the value being set +* SSTORE then SLOAD the same storage slot +* `OP_1` then `OP_2` to the same address where `OP_1` and `OP_2` are all combinations of (`*CALL`, `EXT*`, `SELFDESTRUCT`) +* Try to `CALL` an address but with all possible failure modes (not enough gas, not enough ETH...), then (`CALL` | `EXT*`) that address again successfully + +## 8. Security Considerations + +As with any gas cost increasing EIP, there are three possible cases where it could cause applications to break: + +1. Fixed gas limits to sub-calls in contracts +2. Applications relying on contract calls that consume close to the full gas limit +3. The 2300 base limit given to the callee by ETH-transferring calls + +These risks have been studied before in the context of an earlier gas cost increase, EIP-1884. See [Martin Swende's earlier report](https://github.com/holiman/eip-1884-security) and [Hubert Ritzdorf's analysis](https://gist.github.com/ritzdorf/1c6bd72955391e831f8a397d3152b4e0/) focusing on (1) and (3). (2) has received less analysis, though one can argue that it is very unlikely both because applications tend to very rarely use close to the entire gas limit in a transaction, and because gas limits were very recently raised from 10 million to 12.5 million. EIP-1884 in practice [did lead to a small number of contracts breaking](https://www.coindesk.com/ethereums-istanbul-upgrade-will-break-680-smart-contracts-on-aragon) for this reason. + +There are two ways to look at these risks. First, we can note that as of today developers have had years of warning; gas cost increases on storage-accessing opcodes have been [discussed for a long time](https://ethereum-magicians.org/t/protocol-changes-to-bound-witness-size/3885), with multiple statements made including to major dapp developers around the likelihood of such changes. EIP-1884 itself provided an important wake-up call. Hence, we can argue that risks this time will be significantly lower than EIP-1884. + +### Contract breakage mitigations + +A second way to look at the risks is to explore mitigations. First of all, the existence of an `accessed_addresses` and `accessed_storage_keys` map (present in this EIP, absent in EIP-1884) already makes some cases recoverable: in any case where a contract A needs to send funds to some address B, where that address accepts funds from any source but leaves a storage-dependent log, one can recover by first sending a separate call to B to pull it into the cache, and then call A, knowing that the execution of B triggered by A will only charge 100 gas per SLOAD. This fact does not fix all situations, but it does reduce risks significantly. + +But there are ways to further expand the usability of this pattern. One possibility is to add a `POKE` precompile, which would take an address and a storage key as input and allow transactions that attempt to "rescue" stuck contracts by pre-poking all of the storage slots that they will access. This works even if the address only accepts transactions from the contract, and works in many other contexts with present gas limits. The only case where this will not work would be the case where a transaction call _must_ go from an EOA straight into a specific contract that then sub-calls another contract. + +Another option is [EIP-2930](./eip-2930.md), which would have a similar effect to `POKE` but is more general: it also works for the EOA -> contract -> contract case, and generally should work for all known cases of breakage due to gas cost increases. This option is more complex, though it is arguably a stepping stone toward access lists being used for other use cases (regenesis, account abstraction, SSA all demand access lists). + +## 9. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 10. Reference +Vitalik Buterin (@vbuterin), Martin Swende (@holiman), "EIP-2929: Gas cost increases for state access opcodes," Ethereum Improvement Proposals, no. 2929, September 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-2929. \ No newline at end of file diff --git a/BEPs/BEP-293.md b/BEPs/BEP-293.md new file mode 100644 index 000000000..d83573868 --- /dev/null +++ b/BEPs/BEP-293.md @@ -0,0 +1,182 @@ +
+	BEP: 293
+	Title: Greenfield Link to opBNB
+	Status: Draft
+	Type: Standards
+	Created: 2023-10-11
+
+ +# BEP-293: Greenfield Link to opBNB + +- [BEP-293: Greenfield Link to opBNB](#bep-293-greenfield-link-to-opbnb) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 The tradeoff of opBNB's finality](#31-the-tradeoff-of-opbnbs-finality) + - [3.2 Circulation model for BNB](#32-circulation-model-for-bnb) + - [3.3 Greenfield Changes](#33-greenfield-changes) + - [3.3.1 Add Destination Chain Id in Cross-chain Messages](#331-add-destination-chain-id-in-cross-chain-messages) + - [3.3.2 Add Cross-chain Related Fees for opBNB](#332-add-cross-chain-related-fees-for-opbnb) + - [3.4 opBNB Changes](#34-opbnb-changes) + - [3.4.1 Precompile Contracts](#341-precompile-contracts) + - [4. License](#6-license) + +## 1. Summary + +This BEP proposes to enable the cross-chain communication between Greenfield and opBNB. + +Improving programmable capabilities on different platforms allows us to leverage the unique advantages of each platform. +One example is to enable the Greenfield link to opBNB, which offers lower gas fees and faster cross-chain transactions. + +## 2. Motivation + +Greenfield's dependence on another EVM-compatible L1 chain for programming might lead to elevated cross-chain fees. +When a user purchases a data asset on the BSC data marketplace, they need to pay a gas fee of +$0.524(calculated at a price of 3 Gwei). The fees for the opBNB will be much lower, about one-tenth of the fees on the BSC. +Furthermore, cross-chain communication is significantly faster on opBNB because it achieves one-block finality in most cases. +In BSC, relayers must wait for two blocks (6 seconds) at least to achieve finality before relaying the cross-chain packages. +With one-block finality, relayers only need to wait for one block (1 second) in opBNB. + +By connecting Greenfield to opBNB, the dapp becomes more cost-effective and faster. + +## 3. Specification + +### 3.1 The tradeoff of opBNB's finality + +OpBNB may take up to 5 minutes to transition from an unsafe block to a safe block. However, reaching a safe block +does not guarantee finality. It still needs to wait for BSC on L1 to process multiple blocks before we can reasonably +confirm that it is finalized on the DA layer. If Greenfield relayers wait for opBNB to fully finalize before handling +cross-chain packages, it will result in a poor user experience. + +In most cases, Optimism Layer2 doesn't revert, making it equivalent to one block finality. Some popular centralized +exchanges accept deposits with confirmation of just one block for both OP and ARB. While it is possible to revert, +these exchanges have a high level of confidence in the finality of one block. + +To minimize the impact of block reverts and improve cross-chain communication speed, we can make some tradeoffs. +Specifically, we won't enable BNB cross-chain transfers between opBNB and Greenfield, focusing solely on Greenfield +resource management. Our protocol can prevent double-spending attacks in the event of a revert. So when an unsafe +block emerges on opBNB, the relayer can start relaying cross-chain packages to Greenfield. + +Given this tradeoff, we assume that the application layer(the dapps) can tolerate the inconsistency between greenfield +and opBNB when there is a revert on opBNB. The inconsistency means the state of the application on Greenfield and +opBNB can be different such like the ownership of one object and etc. In practice, the likelihood of such inconsistency +is expected to be minimal. It only arises when a cross-chain transaction is replaced by another transaction with the same nonce. + +### 3.2 Circulation model for BNB + +Since we won't enable cross-chain BNB transfers between opBNB and Greenfield. It's crucial to ensure that +opBNB's [TokenHub](https://docs.bnbchain.org/bnb-greenfield/core-concept/cross-chain/programmability/) has +enough BNB to cover relayer fees at any time. The token hub is used to hold the BNB for cross-chain usage in +EVM-compatible chains like BSC and opBNB. The cross-chain module account in Greenfield is used to custody the BNB +for cross-chain functions. + +![](./assets/BEP-293/cross_chain.png) + +In the BSC and Greenfield scenario, we can ensure this by initiating cross-chain transfer transactions from BSC +to Greenfield. The cross-chain transfers replenish the BSC token hub's BNB balance, ensuring it can cover relayer +fees for cross-chain transactions from Greenfield to BSC. However, in the case of opBNB, if the token hub's balance +reaches zero, we won't have the means to cover relayer fees for cross-chain transactions originating from Greenfield +to opBNB. Because we can not increase the balance of the opBNB token hub with the cross-chain transfers from opBNB +to Greenfield which will transfer user's BNB to the token hub. + +To address this, we must initially transfer some BNB to opBNB's TokenHub. These BNB should be considered permanently +locked, as they won't be recoverable. These allocations can be deducted from the [Quarterly BNB Burn](https://www.bnbburn.info/). + +Without the opBNB link, the circulating BNB on Greenfield is equal to the BNB amount in the BSC TokenHub +which means every BNB can be cross-chain transferred to BSC. The relayer fees paid to the relayers for the +cross-chain transactions from opBNB to Greenfield in Greenfield can slightly increase the circulating BNB in Greenfield. +So with the link of Greenfield to opBNB, the total BNB circulating supply on Greenfield may slightly exceed the BNB +amount held in the BSC token hub. + +This means there won't be sufficient BNB for redemption in BSC through cross-chain transfers from Greenfield to BSC. +Given the lack of direct BNB cross-chain transfers between opBNB and Greenfield, surplus circulating BNB can't be +moved to opBNB. It's important to note that the surplus BNB in Greenfield should be minimal, not exceeding the +initial deposit made to opBNB's TokenHub. + +To resolve this, we can also deposit an equivalent amount of surplus BNB into the BSC token hub, which should be +considered permanently locked. This allows the surplus BNB to be transferred to BSC without increasing the total +circulating BNB across all chains. + +### 3.3 Greenfield Changes + +#### 3.3.1 Add Destination Chain Id in Cross-chain Messages + +The cross-chain messages initiated by users should add the destination chain id to specify the target chain of the message. + +A new field named `dest_chain_id` should be added to the below messages: + +* gov module + 1. `MsgUpdateCrossChainParams` + + + +* storage module: + 1. `MirrorObject` + 2. `MirrorBucket` + 3. `MirrorGroup` + + +For example, `MsgUpdateCrossChainParams` should be like + +```plain +// MsgUpdateCrossChainParams for cross-chain gov +message MsgUpdateCrossChainParams { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "cosmos-sdk/x/gov/v1/MsgUpdateCrossChainParams"; + + // authority is the address that controls the module (defaults to x/gov unless overwritten). + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // for cross chain param change or contract upgrade + CrossChainParamsChange params = 2 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; + + uint32 dest_chain_id = 3; +} +``` + +If the newly added field is the last field in the proto struct, it will not affect the marshaled binary so there is +no need to add a new message type just to add a new field. + +#### 3.3.2 Add Cross-chain Related Fees for opBNB + +The cross-chain related fee between opBNB and greenfield should not be the same as the fee between greenfield and BSC, +so another set of fees should be added. + +Since the cross-chain transfer of BNB will not be enabled, only the related fees of the storage module should be added to `Params` : + +```plain +// relayer fee for the mirror bucket tx to bsc +string opbnb_mirror_bucket_relayer_fee = 18; +// relayer fee for the ACK or FAIL_ACK package of the mirror bucket tx to opbnb +string opbnb_mirror_bucket_ack_relayer_fee = 19; +// relayer fee for the mirror object tx to bsc +string opbnb_mirror_object_relayer_fee = 20; +// Relayer fee for the ACK or FAIL_ACK package of the mirror object tx to opbnb +string opbnb_mirror_object_ack_relayer_fee = 21; +// relayer fee for the mirror object tx to opbnb +string opbnb_mirror_group_relayer_fee = 22; +// Relayer fee for the ACK or FAIL_ACK package of the mirror object tx to opbnb +string opbnb_mirror_group_ack_relayer_fee = 23; +``` + +### 3.4 opBNB Changes + +#### 3.4.1 Precompile Contracts + +The greenfield-related precompile contracts should be added to opBNB. + +The below precompile contracts should be added: + +```plain +common.BytesToAddress([]byte{102}): &blsSignatureVerify{} +common.BytesToAddress([]byte{103}): &cometBFTLightBlockValidate{} +``` + +The contract `blsSignatureVerify` is used to verify the aggregated BLS signatures from the relayers. + +The contract `cometBFTLightBlockValidate` is used to validate the light blocks of cometBFT. + +For more details about the two contracts, you can refer to [BEP 221](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP221.md) and [BEP 126](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md) + +## 4. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-299.md b/BEPs/BEP-299.md new file mode 100644 index 000000000..e49cb357f --- /dev/null +++ b/BEPs/BEP-299.md @@ -0,0 +1,94 @@ +
+  BEP: 299
+  Title: Token Migration after BC Fusion
+  Status: Enabled
+  Type: Standards
+  Created: 2023-10-16
+
+ +# BEP-299: Token Migration after BC Fusion +- [BEP-299: BSC Native Governance Module](#bep-299-token-migration-after-bc-fusion) +- [1. Summary](#1-summary) +- [2. Abstract](#2-abstract) +- [3. Status](#3-status) +- [4. Motivation](#4-motivation) +- [5. Specification](#5-specification) +- [6. License](#6-license) + +# 1. Summary + +After the Beacon Chain fusion, certain digital assets remain on the Beacon Chain. This proposal presents a secure and trustless solution for users to recover their assets on the BSC once the BC stops running. + +# 2. Abstract + +Before the discontinuation of operations on the Beacon Chain, it is highly recommended that users promptly transfer their assets to other networks through cross-chain transactions. Once BC ceases operations, the community team will capture a snapshot of users' assets on BC, which will be publicly released and acknowledged by the community. Subsequently, a Merkle tree will be generated based on the users' balances in the snapshot. The root of this tree will be stored in the system contract of BNB Smart Chain (BSC). + +Any user can prove their ownership of the original tokens on BC by providing a Merkle proof and their BC account's signature. Once the ownership and token information are verified, the system contract on BSC will unlock the corresponding amount of tokens from the token hub and allocate them to the user's account on BSC. Users can initiate token claims through a web app or command line interface (CLI). + +# 3. Status + +Draft. + +# 4. Motivation + +The Beacon Chain was originally created as a platform for issuing data assets. Currently, there are 7.6 million accounts on BC, along with 557 tokens that comply with the **BEP2** or **BEP8** standards. The digital assets of these users will not vanish with BC Fusion. BNB Chain is responsible for safeguarding the assets of these users, irrespective of their value. Users do not have a specific ETA to access these assets. However, BC Fusion is expected to happen within a reasonable timeframe. We plan to implement a solution that enables the timely execution of BC Fusion and secure access to users' digital assets afterwards. + +# 5. Specification + +## 5.1 Asset Back to Wallet + +Digital assets on the BNB Beacon Chain may not always be stored in a user's wallet in specific situations. For example, when users participate in staking, their BNB is actually transferred to the system account of the staking module until they redeem it. Modules that can cause similar asset transfers include: + + - Staking module. + - Timelock module. + - Atomic swap module. + - Governance module. + +The mentioned modules allow users to contribute funds to a shared pool, making it difficult to distinguish an individual user's share. Hence, we need a solution to ensure users can retrieve their funds into their wallets. + +Before BC (Blockchain) comes to a halt, the following logic will be executed: +1. Disable all transactions that would channel user funds into the liquidity pool. +2. During the endblock phase, the following transactions are automatically triggered to return user funds to their wallets, like unstake, timer unlock, and atomic swap unlock. + +Assets in a user's wallet can be in three states: Free, Frozen, and Locked. When calculating the asset balance, we consider the quantities in all three states. So, even if a token is Locked or Frozen when the Beacon Chain halts, it can still be recovered on the BSC chain. + +## 5.2 Asset Recover +### 5.2.1 Asset Tree +![overview](./assets/bep-299/asset_tree.png) + +The user's asset is abstracted as a node, which includes the *account address, symbol, and amount*. We'll exclude assets from non-EOA accounts, including module system accounts and clearly dead addresses. All these nodes are sorted in lexicographical order based on their keys, and then used to construct a Merkle tree. This Merkle tree will be published in the form of a file on GitHub and Greenfield, allowing anyone to verify the accuracy of their assets based on this file. Community members can challenge the accuracy and integrity of this document, and if any errors are found, the core team will make corrections until there are no objections. + +The Merkle tree enables anyone to verify token ownership on the blockchain using a Merkle proof. It ensures that an account possesses a specific number of tokens represented by the symbol "symbol." + +**Note that only tokens that have been linked to BEP20 tokens on BSC will create a Node. Therefore, assets that have not been mirrored to BSC prior to the BC halting can not be restored.** + +### 5.2.2 Asset Recovery App +![overview](./assets/bep-299/asset_recovery_app.png) + +This system consists of two main components: + 1. Approval server. This is an off-chain API service operated by the BNB Chain Foundation. It enables users to retrieve assets by providing merkle proof and approval signature. Only with the approval signature can users recover assets from the BSC network. + 2. Asset Claim Contract. This contract is responsible for handling users' requests to claim assets. It verifies and records the requests to prevent duplicate claims. + +The key process for users to claim assets in the BSC network is as follows: + 1. Users use the private key of the asset owner on BC to sign *{account address, symbol, amount, receiver}*, and request approval through the approval server. + 2. The approval server will fetch the node from a trust merkle tree, and + a. verify the account, symbol, amount are correct. + b. the signature is signed by the token owner. + c. the token is not claimed yet. + *After that, the approval will generate the merkle proof for this request and sign for the request using its approval key.* + 3. The user will send a transaction to the *Asset Claim* contract with merkle proof, node info, BC signature, signature from the approver, receiver account. + 4. The *Asset Claim contract* will do following checks + a. The asset of this node is never claimed. + b. The approval signature comes from the approver. + c. The BC signature comes from the owner of the token. + d. The merkle proof is able to prove the node is a leaf node of the tree. + *After all checks are passed, the *Asset Claim contract* will invoke the token hub contract to unlock the corresponding token to the receiver.* + +### 5.2.3 Security Enhancement +Considering the highly flexible implementation approach of BEP20 tokens on theBSC, there may be unforeseen scenarios that the BEP overlooks. During the initial phase of the BEP, the Approval Server only allows for the tokens in a whitelist that can be claimed. + +For tokens that are not in the whitelist, users can submit requests on the forum. After the core developers review the security of the token, it can be added to the whitelist. + +# 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-311.md b/BEPs/BEP-311.md new file mode 100644 index 000000000..5efd683d8 --- /dev/null +++ b/BEPs/BEP-311.md @@ -0,0 +1,62 @@ +
+  BEP: 311
+  Title: Implement EIP-3651: Warm COINBASE
+  Status: Enabled
+  Type: Standards
+  Created: 2023-10-30
+
+ + +# BEP-311: Implement EIP-3651 Warm COINBASE + +- [BEP-311: Implement EIP-3651 Warm COINBASE](#bep-311-implement-eip-3651-warm-coinbase) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Shanghai upgrade, EIP-3651: Warm COINBASE is required to be implemented to BSC. + +## 2. Abstract + +The `COINBASE` address shall be warm at the start of transaction execution, in accordance with the actual cost of reading that account. + +## 3. Motivation + +Direct `COINBASE` payments are becoming increasingly popular because they allow conditional payments, which provide benefits such as implicit cancellation of transactions that would revert. +But accessing `COINBASE` is overpriced; the address is initially cold under the access list framework introduced in [EIP-2929](./eip-2929.md). +This gas cost mismatch can incentivize alternative payments besides ETH, such as [ERC-20](./eip-20.md), but ETH should be the primary means of paying for transactions on Ethereum. + +## 4. Specification + +At the start of transaction execution, `accessed_addresses` shall be initialized to also include the address returned by `COINBASE` (`0x41`). + +## 5. Rationale + +The addresses currently initialized warm are the addresses that should already be loaded at the start of transaction validation. +The `ORIGIN` address is always loaded to check its balance against the gas limit and the gas price. +The `tx.to` address is always loaded to begin execution. +The `COINBASE` address should also be always be loaded because it receives the block reward and the transaction fees. + +## 6. Backwards Compatibility + +There are no known backward compatibility issues presented by this change. + +## 7. Security Considerations + +There are no known security considerations introduced by this change. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +William Morriss (@wjmelements), "EIP-3651: Warm COINBASE," Ethereum Improvement Proposals, no. 3651, July 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3651. \ No newline at end of file diff --git a/BEPs/BEP-312.md b/BEPs/BEP-312.md new file mode 100644 index 000000000..e496088e1 --- /dev/null +++ b/BEPs/BEP-312.md @@ -0,0 +1,58 @@ +
+  BEP: 312
+  Title: Announce EIP-6049: Deprecate SELFDESTRUCT
+  Status: Review
+  Type: Standards
+  Created: 2023-10-30
+
+ +# BEP-312: Announce EIP-6049 Deprecate SELFDESTRUCT + +- [BEP-312: Announce EIP-6049 Deprecate SELFDESTRUCT](#bep-312-announce-eip-6049-deprecate-selfdestruct) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Shanghai upgrade, EIP-6049: Deprecate SELFDESTRUCT is required to be announced in the BSC community. + +## 2. Abstract + +This EIP deprecates the `SELFDESTRUCT` opcode and warns against its use. A breaking change to this functionality is likely to come in the future. + +## 3. Motivation + +Discussions about how to change `SELFDESTRUCT` are ongoing. But there is a strong consensus that *something* will change. + +## 4. Specification + +Documentation of the `SELFDESTRUCT` opcode is updated to warn against its use and to note that a breaking change may be forthcoming. + +## 5. Rationale + +As time goes on, the cost of doing something increases, because any change to `SELFDESTRUCT` will be a breaking change. + +The Ethereum Blog and other official sources have not provided any warning to developers about a potential forthcoming change. + +## 6. Backwards Compatibility + +This EIP updates non-normative text in the Yellow Paper. No changes to clients is applicable. + +## 7. Security Considerations + +None. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +William Entriken (@fulldecent), "EIP-6049: Deprecate SELFDESTRUCT," Ethereum Improvement Proposals, no. 6049, November 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-6049. \ No newline at end of file diff --git a/BEPs/BEP-319.md b/BEPs/BEP-319.md new file mode 100644 index 000000000..10d9c4dac --- /dev/null +++ b/BEPs/BEP-319.md @@ -0,0 +1,93 @@ +
+  BEP: 319
+  Title: Optimize the incentive mechanism of the Fast Finality feature
+  Status: Enabled
+  Type: Standards
+  Created: 2023-11-13
+  Discussions(optional): https://forum.bnbchain.org/t/bep-319-make-rewards-for-fast-finality-governable/2174
+
+ +# BEP-319: Optimize the incentive mechanism of the Fast Finality feature + + + + + +- [BEP-319: Optimize the incentive mechanism of the Fast Finality feature](#bep-319-optimize-the-incentive-mechanism-of-the-fast-finality-feature) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Governable Rewards](#41-governable-rewards) + - [4.1.1 Existing Allocation Logic](#411-existing-allocation-logic) + - [4.1.2 Allocation Logic Moved to the Contract](#412-allocation-logic-moved-to-the-contract) + - [4.1.3 Maintain Burn Ratio](#413-maintain-burn-ratio) + - [4.2 Balancing Rewards](#42-balancing-rewards) + - [4.3 Extending Submission Deadline for Malicious Voting Evidence](#43-extending-submission-deadline-for-malicious-voting-evidence) + - [5. License](#5-license) + + + + + +## 1. Summary +This BEP proposes three optimizations to the incentive mechanism of the Fast Finality feature in BSC. + +## 2. Abstract +The proposal focuses on three key optimizations for the incentive mechanism of the Fast Finality feature: +1. Making Fast Finality rewards governable while maintaining the basic block transaction fee allocation ratio. +2. Ensuring a more balanced distribution of Fast Finality rewards between epochs. +3. Extending the submission deadline for malicious voting evidence. + +## 3. Motivation +The introduction of the Fast Finality feature in BSC significantly reduces the time required for transaction final confirmation. This feature represents a substantial advantage for BSC compared to other EVM-compatible chains. The purpose of this BEP is to solidify and enhance this advantage. + +## 4. Specification +### 4.1 Governable Rewards +Currently, the reward is approximately 1/16 of the block transaction fees, leading to a lack of incentive for some validators to participate in voting, thereby reducing the stability expectation of the Fast Finality feature. This BEP makes Fast Finality rewards governable, laying the groundwork for future reward enhancements. +#### 4.1.1 Existing Allocation Logic +
+ +
+The existing allocation steps are as follows: + +1. Validators collect transaction fees from within the block. +2. In the client, if the balance of the SystemRewardContract is less than 100 BNB, 1/16 of the collected transaction fees is allocated as rewards for relayers and Fast Finality voting. The remainder is deposited into the ValidatorContract. +3. Within the ValidatorContract, 10% of the deposited amount is burned directly, and the remainder serves as potential earnings for validators and stakers. + +#### 4.1.2 Allocation Logic Moved to the Contract +
+ +
+Due to the deposition of the SystemRewardContract being in the client, requiring hard forks for each change, and for ease of governance, it is moved to the smart contract. The adjusted allocation logic is as follows: + +1. Validators collect transaction fees from within the block and deposit all into the ValidatorContract. +2. Deposit systemRewardRatio of transaction fees into the SystemRewardContract, where systemRewardRatio is governable, with an initial value of 1/16. +3. Within the ValidatorContract, 10% of the deposited amount is burned directly, and the remainder serves as potential earnings for validators and stakers. +#### 4.1.3 Maintain Burn Ratio +The real-time burning mechanism constitutes a pivotal element within the BNB deflationary strategy. With the inception of the burn mechanism in BEP-95, a fractional segment of the SystemRewardContract balance was earmarked for relayer incentive fees, while the burn ratio was calibrated to approximate 10% of the collected block transaction fees. +The present BEP adheres to the consistency established in BEP-95, upholding a burn ratio of 10%. +## 4.2 Balancing Rewards +Fast Finality rewards are unevenly distributed between epochs. Assuming the current balance of the systemReward contract is currentSystemRewardBalance, and the balance after award distribution in the previous epoch is previousSystemRewardBalance, the totalReward calculation formula is as follows: +``` +if currentSystemRewardBalance > 100BNB + totalReward = currentSystemRewardBalance / 100 +else + totalReward = (currentSystemRewardBalance - previousSystemRewardBalance) * 0.5 +``` +This algorithm allocates a portion of the systemReward contract balance increment for each epoch, causing the systemReward contract balance to continuously grow. When it exceeds 100BNB, a reward exceeding 1 BNB is distributed at once, far more than other epochs. +The new formula is as follows: +``` +if currentSystemRewardBalance > 100BNB + totalReward = currentSystemRewardBalance - 100BNB +else + totalReward = 0 // this rarely happens because validators keep depositing and relayers consume much less +``` +This formula allocates the entire increment of the systemReward contract balance for each epoch, resulting in a more even distribution. + +## 4.3 Extending Submission Deadline for Malicious Voting Evidence +When rule-violating votes occur, the current requirement is to submit evidence within 256 blocks; otherwise, rewards cannot be obtained, and malicious validators are not penalized. +This BEP proposes making the submission deadline governable, initialized to 3 days, for increased operability. + +## 5. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-334.md b/BEPs/BEP-334.md new file mode 100644 index 000000000..e3649f676 --- /dev/null +++ b/BEPs/BEP-334.md @@ -0,0 +1,105 @@ +
+  BEP: 334
+  Title: Greenfield CrossChain Permission Module
+  Status: Draft
+  Type: Standards
+  Created: 2023-12-06
+
+ +# BEP-334: Greenfield CrossChain Permission Module + + + + + +- [BEP-334: Greenfield CrossChain Permission Module](#bep-334-greenfield-crosschain-permission-module) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Definitions](#41-definitions) + - [4.2 Interface](#42-interface) + - [4.2.1 Create Policy](#421-create-policy) + - [4.2.2 Delete Policy](#422-delete-policy) + - [5. License](#5-license) + + + + + +## 1. Summary +Currently, Greenfield supports creating buckets and groups from the smart contracts deployed on BSC/opBNB. This means that the owner of a bucket can be a contract address. However, contract addresses cannot upload objects or put policies under the bucket, resulting in empty buckets owned by smart contracts. +To address this issue, we are going to introduce the cross-chain permission module. With this BEP, smart contracts can grant EOA addresses the ability to upload objects under their buckets, and even support additional functions. + +## 2. Abstract +Greenfield CrossChain Permission Module has several significant differences and improvements compared to current implementations: +- BSC/opBNB account is allowed to put policy for Greenfield resources. +- BSC/opBNB account is allowed to disable policy for Greenfield resources. + +## 3. Motivation +In the current framework, Users can use the "policy put [RESOURCE-URL]" command to assign read/write permissions to other accounts or groups (called principal) for GreenField resource, such as the permission to delete objects. +Users could only change the permissions on Greenfield. The proposal allows Greenfield users to change the read/write permissions of GreenField resource directly on the BSC/opBNB network. + +## 4. Specification +### 4.1 Definitions +- PermissionHub Contract: A new middle-layer contract to request permission changes from BSC/opBNB to Greenfield + +### 4.2 Interface +#### 4.2.1 Create Policy +The interface to create policy is as follows: +**function createPolicy(bytes calldata _data, ExtraData memory _extraData) external;** +`_data` is the protobuf encoded bytes of the struct MsgPutPolicy as follows: +```golang +type Policy struct { + Id Uint `protobuf:"bytes,1,opt,name=id,proto3,customtype=Uint" json:"id"` + Principal *Principal `protobuf:"bytes,2,opt,name=principal,proto3" json:"principal,omitempty"` + ResourceType resource.ResourceType `protobuf:"varint,3,opt,name=resource_type,json=resourceType,proto3,enum=greenfield.resource.ResourceType" json:"resource_type,omitempty"` + ResourceId Uint `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3,customtype=Uint" json:"resource_id"` + Statements []*Statement `protobuf:"bytes,5,rep,name=statements,proto3" json:"statements,omitempty"` + ExpirationTime *time.Time `protobuf:"bytes,6,opt,name=expiration_time,json=expirationTime,proto3,stdtime" json:"expiration_time,omitempty"` +} + +type Statement struct { + Effect Effect `json:"effect,omitempty"` + Actions []ActionType `json:"actions,omitempty"` + Resources []string `protobuf:"bytes,3,rep,name=resources,proto3" json:"resources,omitempty"` + ExpirationTime *time.Time `json:"expiration_time,omitempty"` + LimitSize *common.UInt64Value `json:"limit_size,omitempty"` +} +``` + +For `Policy`: +`Id` is an unique u256 sequence for each policy. It also be used as NFT tokenID. +`Principal` defines the roles that can grant permissions. Currently, it can be account or group. +`Resource` defines a greenfield standard resource name that can be generated by GRN structure. +`Statements` defines a list of individual statement which describe the detail rules of policy. +`ExpirationTime` defines the whole expiration time of all the statements. + +For Statement: +`Effect` define the impact of permissions, which can be `Allow`/`Deny`. +`ActionType` defines the operation type you can act on. greenfield defines a set of permission that you can specify in a permissionInfo. see `ActionType` enum for detail. +`ExpirationTime` defines how long the permission is valid. If not explicitly specified, it means it will not expire. +`LimitSize` defines the total data size that is allowed to operate. If not explicitly specified, it means it will not limit. + + +ExtraData is as follows: +```golang +struct ExtraData { + address appAddress; // callback app address + address refundAddress; // refund callback gas fee + bytes callbackData; // calldata for callback +} +``` +`appAddress` defines the callback contract after receiving the cross-chain ack package. +`refundAddress` defines the refund address to receive the unspent callback gas fee. +`callbackData` defines the calldata for the callback call. + +#### 4.2.2 Delete Policy +The interface to delete policy is as follows: +**function deletePolicy(uint256 policyId) external payable returns (bool);** + +`policyId` is generated while creating policy. Only the owner of the policy can delete it. +The deletion of a nonexistent policy will fail on GreenField. + +## 5. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-335.md b/BEPs/BEP-335.md new file mode 100644 index 000000000..4c785711c --- /dev/null +++ b/BEPs/BEP-335.md @@ -0,0 +1,152 @@ +
+  BEP: 335
+  Title: Simplify Storage Provider Exit
+  Status: Enabled
+  Type: Standards
+  Created: 2023-12-13
+
+ +# BEP-335: Simplify Storage Provider Exit + + + + + +- [BEP-335: Simplify Storage Provider Exit](#bep-335-simplify-storage-provider-exit) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 Background](#41-background) + - [4.1.1 Global Virtual Group](#411-global-virtual-group) + - [4.1.2 Virtual Group Family](#412-virtual-group-family) + - [4.1.3 Definition Of SP Exit](#413-definition-of-sp-exit) + - [4.1.4 Categories Of SP Exit](#414-categories-of-sp-exit) + - [4.1.4.1 Graceful Exit](#4141-graceful-exit) + - [4.1.4.2 Forced Exit](#4142-forced-exit) + - [4.2 The Current SP Graceful Exit Procedure](#42-the-current-SP-graceful-exit-procedure) + - [4.3 The New SP Graceful Exit Procedure](#43-the-new-SP-graceful-exit-procedure) + - [4.3.1 Data heal process](#431-data-heal-process) + - [4.4 The SP Forced Exit Procedure](#44-the-SP-forced-exit-procedure) + - [4.5 Concurrent SP Exit](#45-concurrent-SP-exit) + + + + +## 1. Summary +The proposed BEP introduces a new implementation of a graceful exit and forced exit mechanism for storage providers (SP) +in the Greenfield network. + +## 2. Motivation +This proposal addresses the current issues with the fragile and low success rate of the SP exiting process in the Greenfield +network. It aims to improve the process by implementing a new graceful exit and forced exit mechanism for storage providers. +The current process requires the exiting SP to transfer all data stored to other successor SPs, making it difficult to track +and troubleshoot any issues. The new implementation will decouple the reliance on the exiting SP, allowing other SPs to +recover data from the remaining SPs that hold data copies. This will help overcome factors that lower the success rate or +hinder the process, such as data loss, lack of transparency, concurrent SP exit restrictions, and conflicts between primary +and secondary SPs. + +## 4. Specification + +### 4.1 Background + +#### 4.1.1 Global Virtual Group(GVG) + +In the Greenfield network, storage providers need to cooperate with each other through Global Virtual Groups (GVG). A GVG +consists of one primary SP and six secondary storage providers, which is determined by the redundancy strategy. Each object +is associated with a virtual group, where the primary SP holds all segments of each object, while EC chunks of each object +are stored in secondary SPs, so In the event that one or more segments of object is lost from the primary Storage Provider (SP), +it is possible to recover them using any four out of the six SPs. Similarly, if any EC chunk of a specific segment held by +a secondary SP is lost, the secondary SP can retrieve it from the primary SP or other secondary SPs. +For more detailed information, please refer to `Greenfield Doc` [Virtual Group](https://github.com/bnb-chain/greenfield/blob/master/docs/modules/virtual-group.md) and [Redundancy](https://github.com/bnb-chain/greenfield-storage-provider/blob/master/docs/modules/redundancy.md) + +#### 4.1.2 Virtual Group family(VGF) + +A Virtual Group Family (VGF) is a collection of virtual groups that share the same primary Storage Provider (SP). +Each bucket is exclusively served by one VGF, and the objects within the bucket can only be served by Group Virtual +Groups (GVGs) that belong to the respective VGF. It is important to note that a VGF has the capability to serve multiple +buckets simultaneously. + +![](./assets/BEP-335/4.1.2-VGF.png) + +#### 4.1.3 Definition of SP Exit + +A Storage Provider (SP) needs to get suitable successors for both its primary SP role in serving VGF and its secondary SP +role in serving GVG. The successor for the primary role should inherit all segments associated with the objects that the +current SP serves through VGF. Additionally, the successor for the secondary role should receive segment-specific EC chunks +for objects served through GVG. Summarized as: + +- Get successor for primary SP role in VGF exit. +- Get successor for secondary SP role in GVG exit. + +#### 4.1.4 Categories of SP Exit + +There are two types of exit based on the behavior and choices of the Service Provider (SP): Graceful Exit and Forced Exit. + +##### 4.1.4.1 Graceful Exit + +A Storage Provider (SP) voluntarily exits by following the predefined standard procedures, including notifying Greenfield +network the intention to exit, and during the graceful exit, ensures that user query requests can still be fulfilled before +transitioning responsibility and data to other SPs. Once successor SPs have taken over all data in its GVG and VGF, the exit +SP completes the exit process and retrieves all the staked BNB. + +##### 4.1.4.2 Forced Exit + +An uncooperative SP no longer wishes to provide service and refuses to go through the standard exit process. In such a case, +Greenfield governance will force the SP to exit. The successor SP is allowed to recover all data in the GVG and GVG family. +Once the recovery process and SP replacement within the GVG and GVG family are completed, the forced exit SP will be removed from the chain, +and its staked BNB will not be refunded. + +### 4.2 The Current SP Graceful Exit Procedure + +The SP initiates a `StorageProviderExit` transaction to Greenfield, declaring its status as Graceful_Exiting, it then repeatedly +calls SwapOut to remove itself from all GVGs. For those GVGs that it is the primary SP, the SwapOut would occur at family level. +If the successor is already a secondary in any GVG within the VGF, the successor needs to SwapOut first from the GVG, as GVG is +required to have all unique SPs. This means that before the exit SP can choose the successor SP to transfer data, the successor +SP needs to find a successor and transfer data first. This brings the fragility and complexity to the SP exit process. + +### 4.3 The New SP Graceful Exit Procedure + +In the new implementation, the successor SP no longer needs to acquire data from the exit SP due to the redundancy strategy in place. This ensures that the successor primary SP can recover from secondary SPs in the GVG, while the successor secondary SP can recover from the primary SP in the GVG. This approach effectively addresses the issues of data loss and single point of failure associated with the exit SP. +However, it is worth noting that even though the exit SP may cooperate, transferring a significant amount of data to all successors can be challenging to predict or manage effectively. +The graph below illustrates the necessary operations that each component must complete when the SP needs to exit as the primary SP from a GVG. + +![](./assets/BEP-335/4-3-new-sp-graceful-exit-procedure.png) + +1. The SP initiates a `StorageProviderExit` transaction to Greenfield, declares itself Graceful_Exiting status, After this, it will no longer serve any new bucket requests, and existing buckets will not receive new objects. Additionally, it will not serve as a secondary SP for any new objects. However, user query requests will still be accepted. + Note: Once the graceful exit is started, it can not be canceled. +2. Other interested SPs who wish to take over VGF and GVG can send a `ReserveSwapIn` transaction to Greenfield. This reservation will expire in 7 days. During this period, the prospective successor SP will be allowed to acquire data from secondary SPs( If the exiting SP served as a secondary SP, the prospective successor SP will acquire data from the primary SP) +3. The prospective successor SP will continually request data recovery from these secondary SPs. The secondary SPs will verify the validity of the successor SP against Greenfield. Additionally, the successor SP will verify the received data against Greenfield to ensure its integrity. +4. Once the successor SP successfully acquires the data and verifies its integrity, it will send a `CompleteSwapIn` transaction to acknowledge the success. This will officially replace the exiting SP in the VGF/GVG. +5. Once the exiting SP no longer has any GVG bind, it can send out a `CompleteStorageProviderExit` transaction to signify its completion of the exit process. + +### 4.3.1 Data heal process + +As described in the current SP graceful exit procedure, one of the significant challenges is the SP conflict issue, let’s discuss it in more detail. Let's delve into this matter in more detail using an example. + +Consider a GVG with SPs {SP1, SP2, SP3, SP4, SP5, SP6, SP7}, where SP1 is the primary SP. +If SP3 needs to become the successor, it must first be swapped out from the GVG by a successor, let's say SP8. The data transfer from SP3 to SP8 will take place before the transfer from SP1 to SP3. However, the new implementation allows the successor SP to take the primary SP role, even if it is currently a secondary SP in the GVG. This means that a GVG can temporarily break the redundancy requirement, and data redundancy can be achieved through a healing process. + +Returning to the case, with the new implementation, SP3 can initiate a `ReserveSwapIn` transaction directly and then complete a SwapIn transaction after recovering all data from the secondary SPs. The GVG will now become {SP3, SP2, SP3, SP4, SP5, SP6, SP7}. This GVG will be flagged for its broken redundancy, and any other unique SP can take necessary action to `ReserveSwapIn`. This action involves acquiring data from the primary SP and ultimately completing the SwapIn process. Such a GVG will not be used for serving new objects until redundancy is resolved. + +Enabling data healing serves the purpose of facilitating the SP exit process. It is challenging to anticipate the number of GVGs that may encounter such conflicts. However, we can address them once the SP exit is finalized, ensuring a smooth transition and maintaining data integrity. + +## 4.4 The SP forced exit procedure + +The SP forced exit is similar to the graceful exit procedure with a few differences: +- The `StorageProviderExit` is initiated by the SP itself, while the `StorageProviderForcedExit` is executed through Greenfield governance. + Validators must come to an agreement that a specific SP is behaving maliciously and poses a threat to the Greenfield ecosystem. + Once a proposal is passed, the SP's status will be changed to force_exit. Successor SPs must follow the same procedures to take over the forced exit SP's VGF and GVG. + +- During the exiting period, users may experience inability to access their data for a specific bucket until the successor SP completes the swap-in process + for the VGF associated with that bucket. As a consequence, the forced exit SP will face penalties and its staked BNB will be locked into the Payment module governance account, + this payment account is used to receive forced settlement fee, and pay for potential debt from late forced settlement. + +## 4.5 Concurrent SP exit +The new implementation aims to ensure that only one concurrent SP exit is allowed, considering the interconnected nature of a GVG with multiple linked SPs. To address potential issues where a lengthy SP exit process could block other SPs. When a successor SP reserves the swapIn, an expiration time is set to ensure that the transfer is completed within a specific timeframe. + +In cases where the successor SP is unable to complete the transfer within the allotted time, other SPs interested in becoming the successor can still proceed with the swapIn. It's important to note that the efficiency of successor SPs plays a significant role in determining the duration of the SP exit process. + + +## 5. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-336.md b/BEPs/BEP-336.md new file mode 100644 index 000000000..dcf59f154 --- /dev/null +++ b/BEPs/BEP-336.md @@ -0,0 +1,362 @@ +
+  BEP: 336
+  Title: Implement EIP-4844: Shard Blob Transactions
+  Status: Enabled
+  Type: Standards
+  Created: 2023-12-04
+
+ +# BEP-336: Implement EIP-4844: Shard Blob Transactions + +- [BEP-336: Implement EIP-4844: Shard Blob Transactions](#bep-336-implement-eip-4844-shard-blob-transactions) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Parameters](#51-parameters) + - [5.2 Type aliases](#52-type-aliases) + - [5.3 Cryptographic Helpers](#53-cryptographic-helpers) + - [5.4 Helpers](#54-helpers) + - [5.5 Blob transaction](#55-blob-transaction) + - [Signature](#signature) + - [5.6 Header extension](#56-header-extension) + - [5.7 Gas accounting](#57-gas-accounting) + - [5.8 Opcode to get versioned hashes](#58-opcode-to-get-versioned-hashes) + - [5.9 Point evaluation precompile](#59-point-evaluation-precompile) + - [5.10 Execution layer validation](#510-execution-layer-validation) + - [5.11 Networking](#511-networking) + - [TransactionPayload](#transactionpayload) + - [BlockPayload and P2P Message](#blockpayload-and-p2p-message) + - [6. Rationale](#6-rationale) + - [6.1 Why Not Integrate The Sidecar Protocol On BSC](#61-why-not-integrate-the-sidecar-protocol-on-bsc) + - [7. Backwards Compatibility](#7-backwards-compatibility) + - [8. Security Considerations](#8-security-considerations) + - [9. License](#9-license) + +## 1. Summary + +This BEP proposes introduction of blob-carrying transactions which may contain large amount of data. + +## 2. Abstract + +Introduce a new transaction format for “blob-carrying transactions” which contain a large amount of data that cannot be accessed by EVM execution, but whose commitment can be accessed. The format is intended to be fully compatible with the format that will be used in full sharding. + +## 3. Status + +Work in progress. + +## 4. Motivation + +Rollups are significantly reducing fees for many Ethereum users: Optimism and Arbitrum frequently provide fees that are ~3-8x lower than the Ethereum base layer itself, and ZK rollups, which have better data compression and can avoid including signatures, have fees ~40-100x lower than the base layer. In case of BSC, opBNB leverages block size of 100MB along with low gas fees making it suitable for widespread adoption across various digital fields such as gaming and DEXs. + +However, these fees are too expensive for many users in Ethereum ecosystem. The long-term solution to the long-term inadequacy of rollups by themselves has always been data sharding, which would add ~16 MB per block of dedicated data space to the chain that rollups could use. However, data sharding will still take a considerable amount of time to finish implementing and deploying. + +EIP-4844 provides a stop-gap solution until that point by implementing the transaction format that would be used in sharding, but not actually sharding those transactions. Instead, the data from this transaction format is simply part of the chain and is fully downloaded by all consensus nodes (but can be deleted after only a relatively short delay). Compared to full data sharding, EIP-4844 has a reduced cap on the number of these transactions that can be included, corresponding to a target of ~0.375 MB per block and a limit of ~0.75 MB in Ethereum. + +BSC has same target to reduce the L2 rollup cost. This BEP will propose an idea on how to integrate EIP-4844 on BSC, so BSC rollups like opBNB can enjoy an even cheaper gas fee. + +## 5. Specification +### 5.1 Parameters + +| Constant | Value | +| - | - | +| `BLOB_TX_TYPE` | `Bytes1(0x03)` | +| `BYTES_PER_FIELD_ELEMENT` | `32` | +| `FIELD_ELEMENTS_PER_BLOB` | `4096` | +| `BLS_MODULUS` | `52435875175126190479447740508185965837690552500527637822603658699938581184513` | +| `VERSIONED_HASH_VERSION_KZG` | `Bytes1(0x01)` | +| `POINT_EVALUATION_PRECOMPILE_ADDRESS` | `Bytes20(0x0A)` | +| `POINT_EVALUATION_PRECOMPILE_GAS` | `50000` | +| `MAX_BLOB_GAS_PER_BLOCK` | `786432` | +| `TARGET_BLOB_GAS_PER_BLOCK` | `393216` | +| `MIN_BLOB_GASPRICE` | `1` | +| `BLOB_GASPRICE_UPDATE_FRACTION` | `3338477` | +| `GAS_PER_BLOB` | `2**17` | +| `HASH_OPCODE_BYTE` | `Bytes1(0x49)` | +| `HASH_OPCODE_GAS` | `3` | +| `MIN_BLOCKS_FOR_BLOB_REQUESTS` | `524288` | + +### 5.2 Type aliases + +| Type | Base type | Additional checks | +| - | - | - | +| `Blob` | `ByteVector[BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB]` | | +| `VersionedHash` | `Bytes32` | | +| `KZGCommitment` | `Bytes48` | Perform IETF BLS signature "KeyValidate" check but do allow the identity point | +| `KZGProof` | `Bytes48` | Same as for `KZGCommitment` | + +### 5.3 Cryptographic Helpers + +Throughout this proposal we use cryptographic methods and classes defined in the corresponding [consensus 4844 specs](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb). + +Specifically, we use the following methods from [`polynomial-commitments.md`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md): + +- [`verify_kzg_proof()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_kzg_proof) +- [`verify_blob_kzg_proof_batch()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_blob_kzg_proof_batch) + +### 5.4 Helpers + +```python +def kzg_to_versioned_hash(commitment: KZGCommitment) -> VersionedHash: + return VERSIONED_HASH_VERSION_KZG + sha256(commitment)[1:] +``` + +Approximates `factor * e ** (numerator / denominator)` using Taylor expansion: + +```python +def fake_exponential(factor: int, numerator: int, denominator: int) -> int: + i = 1 + output = 0 + numerator_accum = factor * denominator + while numerator_accum > 0: + output += numerator_accum + numerator_accum = (numerator_accum * numerator) // (denominator * i) + i += 1 + return output // denominator +``` + +### 5.5 Blob transaction + +We introduce a new type of [EIP-2718](./eip-2718.md) transaction, "blob transaction", where the `TransactionType` is `BLOB_TX_TYPE` and the `TransactionPayload` is the RLP serialization of the following `TransactionPayloadBody`: + +``` +[chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes, y_parity, r, s] +``` + +The fields `chain_id`, `nonce`, `max_priority_fee_per_gas`, `max_fee_per_gas`, `gas_limit`, `value`, `data`, and `access_list` follow the same semantics as [EIP-1559](./eip-1559.md). + +The field `to` deviates slightly from the semantics with the exception that it MUST NOT be `nil` and therefore must always represent a 20-byte address. This means that blob transactions cannot have the form of a create transaction. + +The field `max_fee_per_blob_gas` is a `uint256` and the field `blob_versioned_hashes` represents a list of hash outputs from `kzg_to_versioned_hash`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + +#### Signature + +The signature values `y_parity`, `r`, and `s` are calculated by constructing a secp256k1 signature over the following digest: + +`keccak256(BLOB_TX_TYPE || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))`. + +### 5.6 Header extension + +The current header encoding is extended with two new 64-bit unsigned integer fields: + +- `blob_gas_used` is the total amount of blob gas consumed by the transactions within the block. +- `excess_blob_gas` is a running total of blob gas consumed in excess of the target, prior to the block. Blocks with above-target blob gas consumption increase this value, blocks with below-target blob gas consumption decrease it (bounded at 0). + +The resulting RLP encoding of the header is therefore: + +``` +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, + blob_gas_used, + excess_blob_gas, +]) +``` + +The value of `excess_blob_gas` can be calculated using the parent header. + +```python +def calc_excess_blob_gas(parent: Header) -> int: + if parent.excess_blob_gas + parent.blob_gas_used < TARGET_BLOB_GAS_PER_BLOCK: + return 0 + else: + return parent.excess_blob_gas + parent.blob_gas_used - TARGET_BLOB_GAS_PER_BLOCK +``` + +For the first post-fork block, both `parent.blob_gas_used` and `parent.excess_blob_gas` are evaluated as `0`. + +### 5.7 Gas accounting + +We introduce blob gas as a new type of gas. It is independent of normal gas and follows its own targeting rule, similar to EIP-1559. +We use the `excess_blob_gas` header field to store persistent data needed to compute the blob gas price. For now, only blobs are priced in blob gas. +![BlobGasPrice](./assets/BEP-336/blob_gasprice.png) + +```python +def calc_data_fee(header: Header, tx: Transaction) -> int: + return get_total_blob_gas(tx) * get_blob_gasprice(header) + +def get_total_blob_gas(tx: Transaction) -> int: + return GAS_PER_BLOB * len(tx.blob_versioned_hashes) + +def get_blob_gasprice(header: Header) -> int: + return fake_exponential( + MIN_BLOB_GASPRICE, + header.excess_blob_gas, + BLOB_GASPRICE_UPDATE_FRACTION + ) +``` + +The block validity conditions are modified to include blob gas checks (see the [Execution layer validation](#execution-layer-validation) section below). + +The actual `data_fee` as calculated via `calc_data_fee` is deducted from the sender balance before transaction execution and is not refunded in case of transaction failure. But unlike Ethereum, the `data_fee` will not be burnt on BSC, as BSC already has its own burn mechanism. + +### 5.8 Opcode to get versioned hashes + +We add an instruction `BLOBHASH` (with opcode `HASH_OPCODE_BYTE`) which reads `index` from the top of the stack +as big-endian `uint256`, and replaces it on the stack with `tx.blob_versioned_hashes[index]` +if `index < len(tx.blob_versioned_hashes)`, and otherwise with a zeroed `bytes32` value. +The opcode has a gas cost of `HASH_OPCODE_GAS`. + +### 5.9 Point evaluation precompile + +Add a precompile at `POINT_EVALUATION_PRECOMPILE_ADDRESS` that verifies a KZG proof which claims that a blob +(represented by a commitment) evaluates to a given value at a given point. + +The precompile costs `POINT_EVALUATION_PRECOMPILE_GAS` and executes the following logic: + +```python +def point_evaluation_precompile(input: Bytes) -> Bytes: + """ + Verify p(z) = y given commitment that corresponds to the polynomial p(x) and a KZG proof. + Also verify that the provided commitment matches the provided versioned_hash. + """ + # The data is encoded as follows: versioned_hash | z | y | commitment | proof | with z and y being padded 32 byte big endian values + assert len(input) == 192 + versioned_hash = input[:32] + z = input[32:64] + y = input[64:96] + commitment = input[96:144] + proof = input[144:192] + + # Verify commitment matches versioned_hash + assert kzg_to_versioned_hash(commitment) == versioned_hash + + # Verify KZG proof with z and y in big endian format + assert verify_kzg_proof(commitment, z, y, proof) + + # Return FIELD_ELEMENTS_PER_BLOB and BLS_MODULUS as padded 32 byte big endian values + return Bytes(U256(FIELD_ELEMENTS_PER_BLOB).to_be_bytes32() + U256(BLS_MODULUS).to_be_bytes32()) +``` + +The precompile MUST reject non-canonical field elements (i.e. provided field elements MUST be strictly less than `BLS_MODULUS`). + +### 5.10 Execution layer validation + +As there is no consensus layer on BSC, the execution layer will be tasked with persistence and propagation of the blobs for data availability. Blobs will be kept for at least for `MIN_BLOCKS_FOR_BLOB_REQUESTS` blocks, which is ~18.2 days on BSC, same as Ethereum. +![BlobExpire](./assets/BEP-336/blob_expire.png) + +And on the execution layer, the block validity conditions are extended as follows: +```python +def validate_block(block: Block) -> None: + ... + + # check that the excess blob gas was updated correctly + assert block.header.excess_blob_gas == calc_excess_blob_gas(block.parent.header) + + blob_gas_used = 0 + + for tx in block.transactions: + ... + + # modify the check for sufficient balance + max_total_fee = tx.gas * tx.max_fee_per_gas + if get_tx_type(tx) == BLOB_TX_TYPE: + max_total_fee += get_total_blob_gas(tx) * tx.max_fee_per_blob_gas + assert signer(tx).balance >= max_total_fee + + ... + + # add validity logic specific to blob txs + if get_tx_type(tx) == BLOB_TX_TYPE: + # there must be at least one blob + assert len(tx.blob_versioned_hashes) > 0 + + # all versioned blob hashes must start with VERSIONED_HASH_VERSION_KZG + for h in tx.blob_versioned_hashes: + assert h[0] == VERSIONED_HASH_VERSION_KZG + + # ensure that the user was willing to at least pay the current blob gasprice + assert tx.max_fee_per_blob_gas >= get_blob_gasprice(block.header) + + # keep track of total blob gas spent in the block + blob_gas_used += get_total_blob_gas(tx) + + # ensure the total blob gas spent is at most equal to the limit + assert blob_gas_used <= MAX_BLOB_GAS_PER_BLOCK + + # ensure blob_gas_used matches header + assert block.header.blob_gas_used == blob_gas_used + +``` + +### 5.11 Networking + +#### TransactionPayload + +Blob transactions have two network representations. During transaction gossip responses (`PooledTransactions`), the EIP-2718 `TransactionPayload` of the blob transaction is wrapped to become: + +``` +rlp([tx_payload_body, blobs, commitments, proofs]) +``` + +Each of these elements are defined as follows: + +- `tx_payload_body` - is the `TransactionPayloadBody` of standard EIP-2718 [blob transaction](#blob-transaction) +- `blobs` - list of `Blob` items +- `commitments` - list of `KZGCommitment` of the corresponding `blobs` +- `proofs` - list of `KZGProof` of the corresponding `blobs` and `commitments` + +The node MUST validate `tx_payload_body` and verify the wrapped data against it. To do so, ensure that: + +- There are an equal number of `tx_payload_body.blob_versioned_hashes`, `blobs`, `commitments`, and `proofs`. +- The KZG `commitments` hash to the versioned hashes, i.e. `kzg_to_versioned_hash(commitments[i]) == tx_payload_body.blob_versioned_hashes[i]` +- The KZG `commitments` match the corresponding `blobs` and `proofs`. (Note: this can be optimized using `verify_blob_kzg_proof_batch`, with a proof for a + random evaluation at a point derived from the commitment and blob data for each blob) + +For body retrieval responses (`BlockBodies`), the standard EIP-2718 blob transaction `TransactionPayload` is used. + +Nodes MUST NOT automatically broadcast blob transactions to their peers. +Instead, those transactions are only announced using `NewPooledTransactionHashes` messages, and can then be manually requested via `GetPooledTransactions`. + +#### BlockPayload and P2P Message + +Unlike Ethereum, block & blobs are broadcasted as a unit for BSC. But from network message perspective, it can be one single message(approach 1) or several interactive messages(approach 2): + +**Approach 1**: Broadcast block and blobs in a single message, the broadcast message will be rlp encoded as: +``` +rlp([block_body, sidecars]) +``` +Each of these elements are defined as follows: +- `block_body`: it is the standard block body definition. +- `sidecars`: a array of sidecar, each sidecar contains `blobs`, `commitments`, `proofs` of a blob transaction. + +**Approach 2**: Broadcast block and blobs separately to reduce the network traffic, e.g. broadcast the block first, but if the receiver does not have the corresponding sidecars, it needs to request the missing sidecars through a query message. + +## 6. Rationale + +BSC shares the same rational of [Ethereum EIP-4844](https://eips.ethereum.org/EIPS/eip-4844), but with several extra points. + +### 6.1 Why Not Integrate The Sidecar Protocol On BSC + +For Ethereum, Blob sync is implemented on the consensus layer with a module called: sidecar. Unlike Ethereum, BSC does not have the consensus layer, it could be quite complicated to implement it on BSC, as it will involve mechanisms like: backfilling, sidecar sync protocol, sidecar persistent… So it would be better to implement it in a simpler way, just sync blobs with blocks directly. It would be much more reliable for blob availability, since we make it mandatory that blocks and blobs are propagated as a unit; When there is a block, its unexpired blobs must exist as well. +Sidecar is also designed to support the future Danksharding DAS, it could be a challenge for BSC to support Danksharding in the future. But as Danksharding would not be delivered in near future, BSC still have plenty of time to support it. + +## 7. Backwards Compatibility + +This part will be same as [Ethereum EIP-4844](https://eips.ethereum.org/EIPS/eip-4844). + +## 8. Security Considerations + +This BEP increases the bandwidth requirements per block by a maximum of ~0.75 MB. This is ~9% larger than the theoretical maximum size of a block today (140M gas / 16 gas per calldata byte = ~8.345M bytes), and so it will not greatly increase worst-case bandwidth. +Basically, BSC has a good network bandwidth, it may not be a big issue to support the extra 0.75 MB. + +## 9. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-341.md b/BEPs/BEP-341.md new file mode 100644 index 000000000..41e8182d7 --- /dev/null +++ b/BEPs/BEP-341.md @@ -0,0 +1,120 @@ +
+  BEP: 341
+  Title: Validators can produce consecutive blocks
+  Status: Draft
+  Type: Standards
+  Created: 2023-09-27
+  Discussions(optional): https://forum.bnbchain.org/t/bep-idea-validators-can-produce-consecutive-blocks/2052
+
+ +# BEP-341: Validators can produce consecutive blocks + + + + + +- [BEP-341: Validators can produce consecutive blocks](#bep-341-validators-can-produce-consecutive-blocks) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Scaling Principle](#41-scaling-principle) + - [4.2 Implementation Specification](#42-implementation-specification) + - [4.2.1 Priority Allocation](#421-priority-allocation) + - [4.2.2 Validator Set Switch](#422-validator-set-switch) + - [4.2.3 Block Avoidance](#423-block-avoidance) + - [4.2.4 Governable Number of Consecutive Blocks](#424-governable-number-of-consecutive-blocks) + - [4.2.5 Combatting MEV](#425-combatting-mev) + - [5. Incentive Fairness Analysis](#5-incentive-fairness-analysis) + - [6. Security Analysis](#6-security-analysis) + - [7. Liveness Analysis](#7-liveness-analysis) + - [8. License](#8-license) + + + +## 1. Summary +Each epoch in BSC consists of multiple slots, and a batch of validators take turns in a predefined order to obtain priority block-producing rights for each slot. This BEP proposes an adjustment to the allocation of priority block-producing rights: each validator receives priority block-producing rights for a predetermined number of consecutive slots per round. +## 2. Abstract +BEP-341 describes a new allocation method for priority block-producing rights, which is logically concise and significantly enhances the system's transaction processing capacity, while remaining orthogonal to transaction processing optimization techniques within blocks. +## 3. Motivation +The BSC ecosystem is active and continuously evolving, requiring ongoing improvements to the system's transaction processing capacity. +## 4. Specification +### 4.1 Scaling Principle +Currently, each validator obtains priority block-producing rights for a single slot and is then rotated, with a fixed block interval of t. The transaction processing limit is t/2 for validating transactions from the previous block and t/2 for processing transactions in the new block. +
+ +
+Assuming the number of transactions that can be processed is T, the average TPS is calculated as follows: +
+ +
+After implementing this BEP, each validator can obtain priority block-producing rights for a continuous sequence of n slots in one round. The first block they process still allocates t/2 for validating transactions from the previous block and t/2 for processing transactions in the new block. However, subsequent blocks can skip the transaction validation process and focus on processing transactions in the new block. It is recommended that the processing time for the last block in their current round be only half of the time required to process transactions in the new block. This helps avoid the situation where the first block processed by the next validator is close to being an empty block. +
+ +
+The TPS after continuous block production is as follows: +
+ +
+Therefore, the TPS improvement rate is: +
+ +
+The relationship between the number of continuous blocks produced and TPS improvement is +
+ +
+As shown in the graph, it is evident that continuous block production cannot double the TPS. There is no benefit when n<3, and increasing n beyond 5 does not proportionally increase the benefits. Therefore, a value within the range [3, 5] is suitable for n; when n=4, r=50%. + +### 4.2 Implementation Specification +#### 4.2.1 Priority Allocation +Each epoch predefines a set of validators, with a total of validatorN validators, and each validator within the set has a unique index ranging from [0, validatorN). If the current block height is blockN, then the validators with the following indices obtain priority block-producing rights. +
+ +
+ +#### 4.2.2 Validator Set Switch +Each epoch will choose a new validator set, assuming an epoch contains epochSlots slots. The validator set switch occurs only when the block height reaches Bswitch to prevent epoch block forging. The calculation of Bswitch is as follows: +
+ +
+ +#### 4.2.3 Block Avoidance +To prevent fewer than 1/2 of the nodes from controlling the entire network, block producers are required to produce fewer than n blocks within the previous ((validatorN/2+1)\*n-1) historical blocks. + + +#### 4.2.4 Governable Number of Consecutive Blocks +When n=1, it is equivalent to disabling the feature of consecutive block production, while significant optimization is observed when n belongs to the range [3,5]. Currently, the range for the value of n is set to [1,9] but except 2. + +The initial value of n is 1, and changing its value requires the BSC governance process. + +#### 4.2.5 Combatting MEV +As the consecutive period in which a single validator gains priority in block production extends, it may facilitate MEV extraction, potentially leading validators to include more transactions in the later blocks they consecutively produce. To constrain validators to promptly package transactions, within a validator's consecutive priority over n blocks, the transaction fees' split to the SystemRewardContract will increase linearly with block number, capped at the value denoted as systemRewardAntiMEVRatio. +Respectively, the split ratio remains at systemRewardBaseRatio when continuous block production is disabled. Once continuous block production is enabled (i.e., when n > 1), the systemRewardRatio is calculated as: +
+ +
+as shown in the following picture: +
+ +
+ +The initial value of systemRewardAntiMEVRatio is 0, and changing its value also requires the BSC governance process. + +## 5. Incentive Fairness Analysis +Within a single epoch, tail validators have fewer block-producing opportunities, but the allocation of priority rights is unbiased and cannot be manipulated. Therefore, from a statistical perspective, it is fair. + +If a validator tries to extract more MEV by placing more transactions in later blocks they produce, it will also increase user transaction confirmation times. To curb this, the systemRewardAntiMEVRatio can be raised through the governance process, which will increase the proportion of transaction fees allocated to the SystemRewardContract. These bonuses will be distributed as Fast Finality voting rewards to validators, keeping their overall benefits unchanged. However, during high traffic and transaction backlog, high-performance validators usually handle more transactions. These changes will reduce the income advantage of having high performance. + +## 6. Security Analysis +This BEP relies on BSC's Fast Finality feature. If Fast Finality fails, it may result in the following issues: +1. Nodes intentionally hide mined blocks, potentially leading to longer short-term reorganizations. +2. The probability of finality for transactions increases, requiring waiting for 2/3\*validatorN\*n+ blocks. + +## 7. Liveness Analysis +The liveness of the chain remains unchanged, meaning it is required to ensure that at least (validatorN/2+1) validators are active. The proof is as follows: + +If (validatorN/2+1) validators are active and none are allowed to produce blocks at a certain moment, each validator must have produced at least n blocks in the past ((validatorN/2+1)\*n-1) blocks. Thus, collectively, at least (validatorN/2+1)\*n blocks must have been produced, which is impossible. Therefore, at any moment, at least one of the (validatorN/2+1) validators must be allowed to produce blocks. + +## 8. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-342.md b/BEPs/BEP-342.md new file mode 100644 index 000000000..71b41ed80 --- /dev/null +++ b/BEPs/BEP-342.md @@ -0,0 +1,130 @@ +
+  BEP: 342
+  Title: Implement EIP-5656: MCOPY
+  Status: Enabled
+  Type: Standards
+  Created: 2024-01-15
+
+ + +# BEP-342: Implement EIP-5656: MCOPY + +- [BEP-342: Implement EIP-5656: MCOPY](#bep-342-implement-eip-5656-mcopy) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Cancun upgrade, EIP-5656: MCOPY is required to be implemented to BSC. + +## 2. Abstract + +Provide an efficient EVM instruction for copying memory areas. + +## 3. Motivation + +Memory copying is a basic operation, yet implementing it on the EVM comes with overhead. + +This was recognised and alleviated early on with the introduction of the "identity" precompile, which accomplishes +memory copying by the use of `CALL`'s input and output memory offsets. Its cost is `15 + 3 * (length / 32)` gas, plus +the call overhead. The identity precompile was rendered ineffective by the raise of the cost of `CALL` to 700, but subsequently +the reduction by [EIP-2929](./BEP-230.md) made it slightly more economical. + +Copying exact words can be accomplished with ` MLOAD MSTORE` or ` DUP1 MLOAD DUP2 MSTORE`, +at a cost of at least 12 gas per word. This is fairly efficient if the offsets are known upfront and the copying can be unrolled. +In case copying is implemented at runtime with arbitrary starting offsets, besides the control flow overhead, the offset +will need to be incremented using `32 ADD`, adding at least 6 gas per word. + +Copying non-exact words is more tricky, as for the last partial word, both the source and destination needs to be loaded, +masked, or'd, and stored again. This overhead is significant. One edge case is if the last "partial word" is a single byte, +it can be efficiently stored using `MSTORE8`. + +As example use case, copying 256 bytes costs: + +- at least 757 gas pre-EIP-2929 using the identity precompile +- at least 157 gas post-EIP-2929 using the identity precompile +- at least 96 gas using unrolled `MLOAD`/`MSTORE` instructions +- 27 gas using this EIP + +According to an analysis of blocks 10537502 to 10538702, roughly 10.5% of memory copies would have had improved performance with the +availability of an `MCOPY` instruction. + +Memory copying is used by languages like Solidity and Vyper, where we expect this improvement to provide efficient means of building +data structures, including efficient sliced access and copies of memory objects. Having a dedicated `MCOPY` instruction would also add +forward protection against future gas cost changes to `CALL` instructions in general. + +Having a special `MCOPY` instruction makes the job of static analyzers and optimizers easier, since the effects of a `CALL` in general +have to be fenced, whereas an `MCOPY` instruction would be known to only have memory effects. Even if special cases are added +for precompiles, a future hard fork could change `CALL` effects, and so any analysis of code using the identity precompile would only +be valid for a certain range of blocks. + +Finally, we expect memory copying to be immensely useful for various computationally heavy operations, such as EVM384, +where it is identified as a significant overhead. + +## 4. Specification + +The instruction `MCOPY` is introduced at `0x5E`. + +### Input stack + +| Stack | Value | +|-------|-------| +| top - 0 | `dst` | +| top - 1 | `src` | +| top - 2 | `length` | + +This ordering matches the other copying instructions, i.e. `CALLDATACOPY`, `RETURNDATACOPY`. + +### Gas costs + +Per yellow paper terminology, it should be considered part of the `W_copy` group of opcodes, and follow the gas calculation for `W_copy` in the yellow paper. While the calculation in the yellow paper should be considered the final word, for reference, as of time of this writing, that currently means its gas cost is: + +``` +words_copied = (length + 31) // 32 +g_verylow = 3 +g_copy = 3 * words_copied + memory_expansion_cost +gas_cost = g_verylow + g_copy +``` + +### Output stack + +This instruction returns no stack items. + +### Semantics + +It copies `length` bytes from the offset pointed at `src` to the offset pointed at `dst` in memory. +Copying takes place as if an intermediate buffer was used, allowing the destination and source to overlap. + +If `length > 0` and (`src + length` or `dst + length`) is beyond the current memory length, the memory is extended with respective gas cost applied. + +The gas cost of this instruction mirrors that of other `Wcopy` instructions and is `Gverylow + Gcopy * ceil(length / 32)`. + +## 5. Rationale + +Production implementation of exact-word memory copying and partial-word memory copying can be found in the Solidity, Vyper and Fe compilers. + +With [EIP-2929](./BEP-230.md) the call overhead using the identity precompile was reduced from 700 to 100 gas. +This is still prohibitive for making the precompile a reasonable alternative again. + +## 6. Backwards Compatibility + +This BEP introduces a new instruction which did not exist previously. Already deployed contracts using this instruction could change their behaviour after this EIP. + +## 7. Security Considerations + +There are no known security considerations introduced by this change. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Alex Beregszaszi (@axic), Paul Dworzanski (@poemm), Jared Wasinger (@jwasinger), Casey Detrio (@cdetrio), Pawel Bylica (@chfast), Charles Cooper (@charles-cooper), "EIP-5656: MCOPY - Memory copying instruction [DRAFT]," Ethereum Improvement Proposals, no. 5656, February 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5656. \ No newline at end of file diff --git a/BEPs/BEP-343.md b/BEPs/BEP-343.md new file mode 100644 index 000000000..1e4f52f0e --- /dev/null +++ b/BEPs/BEP-343.md @@ -0,0 +1,143 @@ +
+  BEP: 343
+  Title: Implement EIP-1153: Transient storage opcodes
+  Status: Enabled
+  Type: Standards
+  Created: 2024-01-15
+
+ + +# BEP-343: Implement EIP-1153: Transient storage opcodes + +- [BEP-343: Implement EIP-1153: Transient storage opcodes](#bep-343-implement-eip-1153-transient-storage-opcodes) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Cancun upgrade, EIP-1153: Transient storage opcodes is required to be implemented to BSC. + +## 2. Abstract + +This proposal introduces transient storage opcodes, which manipulate state that behaves identically to storage, except that transient storage is discarded after every transaction. In other words, the values of transient storage are never deserialized from storage or serialized to storage. Thus transient storage is cheaper since it never requires disk access. Transient storage is accessible to smart contracts via 2 new opcodes, `TLOAD` and `TSTORE`, where “T” stands for "transient:" + +``` +TLOAD (0x5c) +TSTORE (0x5d) +``` + +## 3. Motivation + +Running a transaction in Ethereum can generate multiple nested frames of execution, each created by `CALL` (or similar) instructions. Contracts can be re-entered during the same transaction, in which case there are more than one frame belonging to one contract. Currently, these frames can communicate in two ways: via inputs/outputs passed via `CALL` instructions, and via storage updates. If there is an intermediate frame belonging to another untrusted contract, communication via inputs/outputs is not secure. Notable example is a reentrancy lock which cannot rely on the intermediate frame to pass through the state of the lock. Communication via storage (`SSTORE`/`SLOAD`) is costly. Transient storage is a dedicated and gas efficient solution to the problem of inter frame communication. + +Storage refunds accumulated due to inter frame communication are also limited to 20% of gas spent by a transaction due to [EIP-3529](./BEP212.md) (introduced in the London hard fork). This greatly reduces the refunds for transiently-set storage slots in otherwise low-cost transactions. For example, in order to receive the full refund of one re-entrancy lock, the transaction must spend ~80k gas on other operations. + +Language support could be added in relatively easy way. For example, in Solidity, a qualifier `transient` can be introduced (similar to the existing qualifiers `memory` and `storage`, and Java's own `transient` keyword with a similar meaning). Since the addressing scheme of `TSTORE` and `TLOAD` is the same as for `SSTORE` and `SLOAD`, code generation routines that exist for storage variables, can be easily generalised to also support transient storage. + +Potential use cases enabled or improved by this EIP include: + +1. Reentrancy locks +2. On-chain computable CREATE2 addresses: constructor arguments are read from the factory contract instead of passed as part of init code hash +3. Single transaction [ERC-20](https://github.com/ethereum/ercs/blob/master/ERCS/erc-20.md) approvals, e.g. `#temporaryApprove(address spender, uint256 amount)` +4. Fee-on-transfer contracts: pay a fee to a token contract to unlock transfers for the duration of a transaction +5. "Till" pattern: allowing users to perform all actions as part of a callback, and checking the "till" is balanced at the end +6. Proxy call metadata: pass additional metadata to an implementation contract without using calldata, e.g. values of immutable proxy constructor arguments + +These opcodes are more efficient to execute than the `SSTORE` and `SLOAD` opcodes because the original value never needs to be loaded from storage (i.e. is always 0). The gas accounting rules are also simpler, since no refunds are required. + +## 4. Specification + +Two new opcodes are added to EVM, `TLOAD` (`0x5c`) and `TSTORE` (`0x5d`). (Note that previous drafts of this EIP specified the values `0xb3` and `0xb4` for `TLOAD` and `TSTORE` respectively to avoid conflict with other EIPs. The conflict has since been removed.) + +They use the same arguments on stack as `SLOAD` (`0x54`) and `SSTORE` (`0x55`). + +`TLOAD` pops one 32-byte word from the top of the stack, treats this value as the address, fetches 32-byte word from the transient storage at that address, and pushes the value on top of the stack. + +`TSTORE` pops two 32-byte words from the top of the stack. The word on the top is the address, and the next is the value. `TSTORE` saves the value at the given address in the transient storage. + +Addressing is the same as `SLOAD` and `SSTORE`. i.e. each 32-byte address points to a unique 32-byte word. + +Gas cost for `TSTORE` is the same as a warm `SSTORE` of a dirty slot (i.e. original value is not new value and is not current value, currently 100 gas), and gas cost of `TLOAD` is the same as a hot `SLOAD` (value has been read before, currently 100 gas). Gas cost cannot be on par with memory access due to transient storage's interactions with reverts. + +All values in transient storage are discarded at the end of the transaction. + +Transient storage is private to the contract that owns it, in the same way as persistent storage. Only owning contract frames may access their transient storage. And when they do, all the frames access the same transient store, in the same way as persistent storage, but unlike memory. + +When transient storage is used in the context of `DELEGATECALL` or `CALLCODE`, then the owning contract of the transient storage is the contract that issued `DELEGATECALL` or `CALLCODE` instruction (the caller) as with persistent storage. When transient storage is used in the context of `CALL` or `STATICCALL`, then the owning contract of the transient storage is the contract that is the target of the `CALL` or `STATICCALL` instruction (the callee). + +If a frame reverts, all writes to transient storage that took place between entry to the frame and the return are reverted, including those that took place in inner calls. This mimics the behavior of persistent storage. + +If the `TSTORE` opcode is called within the context of a `STATICCALL`, it will result in an exception instead of performing the modification. `TLOAD` is allowed within the context of a `STATICCALL`. + +## 5. Rationale + +Another option to solve the problem of inter-frame communication is repricing the `SSTORE` and `SLOAD` opcodes to be cheaper for the transient storage use case. This has already been done as of [EIP-2200](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2200.md). However, [EIP-3529](./BEP212.md) reduced the maximum refund to only 20% of the transaction gas cost, which means the use of transient storage is severely limited. + +Another approach is to keep the refund counter for transient storage separate from the refund counter for other storage uses, and remove the refund cap for transient storage. However, that approach is more complex to implement and understand. For example, the 20% refund cap must be applied to the gas used _after_ subtracting the uncapped gas refund. Otherwise, the refund amount available subject to the 20% refund cap could be increased by executing transient storage writes. Thus it is preferable to have a separate mechanism that does not interact with the refund counter. Future hard forks can remove the complex refund behavior meant to support the transient storage use case, encouraging migration to contracts that are more efficient for the Ethereum clients to execute. + +There is a known objection to the word-addressed storage-like interface of the `TSTORE` and `TLOAD` opcodes since transient storage is more akin to memory than storage in lifecycle. A byte-addressed memory-like interface is another option. The storage-like word-addressed interface is preferred due to the usefulness of mappings in combination with the transaction-scoped memory region. Often times, you will need to keep transient state with arbitrary keys, such as in the [ERC-20](https://github.com/ethereum/ercs/blob/master/ERCS/erc-20.md) temporary approval use case which uses a mapping of `(owner, spender)` to `allowance`. Mappings are difficult to implement using linear memory, and linear memory must also have dynamic gas costs. It is also more complicated to handle reverts with a linear memory. It is possible to have a memory-like interface while the underlying implementation uses a map to allow for storage in arbitrary offsets, but this would result in a third memory-storage hybrid interface that would require new code paths in compilers. + +Some think that a unique transaction identifier may obviate the need for transient storage as described in this EIP. This is a misconception: a transaction identifier used in combination with regular storage has all the same issues that motivate this EIP. The two features are orthogonal. + +Relative cons of this transient storage EIP: + +- Does not address transient usages of storage in existing contracts +- New code in the clients +- New concept for the yellow paper (more to update) + +Relative pros of this transient storage EIP: + +- Transient storage opcodes are considered separately in protocol upgrades and not inadvertently broken (e.g. [EIP-3529](./BEP212.md)) +- Clients do not need to load the original value +- No upfront gas cost to account for non-transient writes +- Does not change the semantics of the existing operations +- No need to clear storage slots after usage +- Simpler gas accounting rules +- Future storage designs (e.g. Verkle tree) do not need to account for transient storage refunds + +## 6. Backwards Compatibility + +This EIP requires a hard fork to implement. + +Since this EIP does not change behavior of any existing opcodes, it is backwards compatible with all existing smart contracts. + +## 7. Security Considerations + +`TSTORE` presents a new way to allocate memory on a node with linear cost. In other words, each TSTORE allows the developer to store 32 bytes for 100 gas, excluding any other required operations to prepare the stack. Given 30 million gas, the maximum amount of memory that can be allocated using TSTORE is: + +``` +30M gas * 1 TSTORE / 100 gas * 32 bytes / 1 TSTORE * 1MB / 2^20 bytes ~= 9.15MB +``` + +Given the same amount of gas, the maximum amount of memory that can be allocated in a single context by `MSTORE` is ~3.75MB: + +``` +30M gas = 3x + x^2 / 512 => x = ~123,169 32-byte words +~123,169 words * 32 bytes/word * 1MB / 2^20 bytes = 3.75MB +``` + +However, if you only spend 1M gas allocating memory in each context, and make calls to reset the memory expansion cost, you can allocate ~700KB per million gas, for a total of ~20MB of memory allocated: + +``` +1M gas = 3x + x^2 / 512 => x = ~21,872 32-byte words +30M gas * ~21,872 words / 1M gas * 32 bytes/word * 1MB / 2^20 bytes = ~20MB +``` + +Smart contract developers should understand the lifetime of transient storage variables before use. Because transient storage is automatically cleared at the end of the transaction, smart contract developers may be tempted to avoid clearing slots as part of a call in order to save gas. However, this could prevent further interactions with the contract in the same transaction (e.g. in the case of re-entrancy locks) or cause other bugs, so smart contract developers should be careful to _only_ leave transient storage slots with nonzero values when those slots are intended to be used by future calls within the same transaction. Otherwise, these opcodes behave exactly the same as `SSTORE` and `SLOAD`, so all the usual security considerations apply especially in regard to reentrancy risk. + +Smart contract developers may also be tempted to use transient storage as an alternative to in-memory mappings. They should be aware that transient storage is not discarded when a call returns or reverts, as is memory, and should prefer memory for these use cases so as not to create unexpected behavior on reentrancy in the same transaction. The necessarily high cost of transient storage over memory should already discourage this usage pattern. Most usages of in-memory mappings can be better implemented with key-sorted lists of entries, and in-memory mappings are rarely required in smart contracts (i.e. the author knows of no known use cases in production). + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Alexey Akhunov (@AlexeyAkhunov), Moody Salem (@moodysalem), "EIP-1153: Transient storage opcodes [DRAFT]," Ethereum Improvement Proposals, no. 1153, June 2018. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-1153. \ No newline at end of file diff --git a/BEPs/BEP-344.md b/BEPs/BEP-344.md new file mode 100644 index 000000000..879e63555 --- /dev/null +++ b/BEPs/BEP-344.md @@ -0,0 +1,93 @@ +
+  BEP: 344
+  Title: Implement EIP-6780: SELFDESTRUCT only in same transaction
+  Status: Enabled
+  Type: Standards
+  Created: 2024-01-15
+
+ + +# BEP-344: Implement EIP-6780: SELFDESTRUCT only in same transaction + +- [BEP-344: Implement EIP-6780: SELFDESTRUCT only in same transaction](#bep-344-implement-eip-6780-selfdestruct-only-in-same-transaction) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Cancun upgrade, Implement EIP-6780: SELFDESTRUCT only in same transaction is required to be implemented to BSC. + +## 2. Abstract + +This EIP changes the functionality of the `SELFDESTRUCT` opcode. The new functionality will be only to send all Ether in the account to the target, except that the current behaviour is preserved when `SELFDESTRUCT` is called in the same transaction a contract was created. + +## 3. Motivation + +The `SELFDESTRUCT` opcode requires large changes to the state of an account, in particular removing all code and storage. This will not be possible in the future with Verkle trees: Each account will be stored in many different account keys, which will not be obviously connected to the root account. + +This EIP implements this change. Applications that only use `SELFDESTRUCT` to retrieve funds will still work. Applications that only use `SELFDESTRUCT` in the same transaction as they created a contract will also continue to work without any changes. + +## 4. Specification + +The behaviour of `SELFDESTRUCT` is changed in the following way: + +1. When `SELFDESTRUCT` is executed in a transaction that is not the same as the contract calling `SELFDESTRUCT` was created: + + - The current execution frame halts. + - `SELFDESTRUCT` does not delete any data (including storage keys, code, or the account itself). + - `SELFDESTRUCT` transfers the entire account balance to the target. + - Note that if the target is the same as the contract calling `SELFDESTRUCT` there is no net change in balances. Unlike the prior specification, Ether will not be burnt in this case. + - Note that no refund is given since [EIP-3529](./BEP212.md). + - Note that the rules of [EIP-2929](./BEP-230.md) regarding `SELFDESTRUCT` remain unchanged. + +2. When `SELFDESTRUCT` is executed in the same transaction as the contract was created: + + - `SELFDESTRUCT` continues to behave as it did prior to this EIP, this includes the following actions + - The current execution frame halts. + - `SELFDESTRUCT` deletes data as previously specified. + - `SELFDESTRUCT` transfers the entire account balance to the target + - The account balance of the contact calling `SELFDESTRUCT` is set to `0`. + - Note that if the target is the same as the contract calling `SELFDESTRUCT` that Ether will be burnt. + - Note that no refund is given since [EIP-3529](./BEP212.md). + - Note that the rules of [EIP-2929](./BEP-230.md) regarding `SELFDESTRUCT` remain unchanged. + +A contract is considered created at the beginning of a create transaction or when a CREATE series operation begins execution (CREATE, CREATE2, and other operations that deploy contracts in the future). If a balance exists at the contract's new address it is still considered to be a contract creation. + +The `SELFDESTRUCT` opcode remains deprecated as specified in [EIP-6049](./BEP-312.md). Any use in newly deployed contracts is strongly discouraged even if this new behaviour is taken into account, and future changes to the EVM might further reduce the functionality of the opcode. + +## 5. Rationale + +Getting rid of the `SELFDESTRUCT` opcode has been considered in the past, and there are currently no strong reasons to use it. This EIP implements a behavior that will attempt to leave some common uses of `SELFDESTRUCT` working, while reducing the complexity of the change on EVM implementations that would come from contract versioning. + +Handling the account creation and contract creation as two distinct and possibly separate events is needed for use cases such as counterfactual accounts. By allowing the `SELFDESTRUCT` to delete the account at contract creation time it will not result in stubs of counterfactually instantiated contracts that never had any on-chain state other than a balance prior to the contract creation. These accounts would never have any storage and thus the trie updates to delete the account would be limited to the account node, which is the same impact a regular transfer of ether would have. + +## 6. Backwards Compatibility + +This EIP requires a hard fork, since it modifies consensus rules. + +Contracts that depended on re-deploying contracts at the same address using `CREATE2` (after a `SELFDESTRUCT`) will no longer function properly if the created contract does not call `SELFDESTRUCT` within the same transaction. + +Previously it was possible to burn ether by calling `SELFDESTRUCT` targeting the executing contract as the beneficiary. If the contract existed prior to the transaction the ether will not be burned. If the contract was newly created in the transaction the ether will be burned, as before. + +## 7. Security Considerations + +The following applications of `SELFDESTRUCT` will be broken and applications that use it in this way are not safe anymore: + +1. Where `CREATE2` is used to redeploy a contract in the same place in order to make a contract upgradable. This is not supported anymore and [ERC-2535](https://github.com/ethereum/ERCs/blob/master/ERCS/erc-2535.md) or other types of proxy contracts should be used instead. + +2. Where a contract depended on burning Ether via a `SELFDESTRUCT` with the contract as beneficiary, in a contract not created within the same transaction. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad), "EIP-6780: SELFDESTRUCT only in same transaction [DRAFT]," Ethereum Improvement Proposals, no. 6780, March 2023. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-6780. \ No newline at end of file diff --git a/BEPs/BEP-345.md b/BEPs/BEP-345.md new file mode 100644 index 000000000..c86922d02 --- /dev/null +++ b/BEPs/BEP-345.md @@ -0,0 +1,69 @@ +
+  BEP: 345
+  Title: Implement EIP-7516: BLOBBASEFEE opcode
+  Status: Enabled
+  Type: Standards
+  Created: 2024-01-15
+
+ + +# BEP-345: Implement EIP-7516: BLOBBASEFEE opcode + +- [BEP-345: Implement EIP-7516: BLOBBASEFEE opcode](#bep-345-implement-eip-7516-blobbasefee-opcode) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + - [9. Reference](#9-reference) + + +## 1. Summary +As part of Cancun upgrade, EIP-7516: BLOBBASEFEE opcode is required to be implemented to BSC. + +## 2. Abstract + +Add a `BLOBBASEFEE (0x4a)` that returns the value of the blob base-fee of the current block it is executing in. It is the identical to [EIP-3198](./BEP227.md) (`BASEFEE` opcode) except that it returns the blob base-fee as per [EIP-4844](./BEP-336.md). + +## 3. Motivation + +The intended use case would be for contracts to get the value of the blob base-fee. This feature enables blob-data users to programmatically account for the blob gas price, eg: + +- Allow rollup contracts to trustlessly account for blob data usage costs. +- Blob gas futures can be implemented based on it which allows for blob users to smooth out data blob costs. + +## 4. Specification + +Add a `BLOBBASEFEE` opcode at `(0x4a)`, with gas cost `2`. + +| Op | Input | Output | Cost | +|------|-------|--------|------| +| 0x4a | 0 | 1 | 2 | + +`BLOBBASEFEE` returns the result of the `get_blob_gasprice(header) -> int` function as defined in [EIP-4844 §Gas accounting](./BEP-336.md#gas-accounting). + +## 5. Rationale + +### Gas cost + +The value of the blob base-fee is needed to process data-blob transactions. That means its value is already available before running the EVM code. +The opcode does not add extra complexity and additional read/write operations, hence the choice of `2` gas cost. This is also identical to [EIP-3198](./BEP227.md) (`BASEFEE` opcode)'s cost as it just makes available data that is in the header. + +## 6. Backwards Compatibility + +There are no known backward compatibility issues with this opcode. + +## 7. Security Considerations + +The value of the blob base-fee is not sensitive and is publicly accessible in the block header. There are no known security implications with this opcode. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Carl Beekhuizen (@carlbeek), "EIP-7516: BLOBBASEFEE opcode [DRAFT]," Ethereum Improvement Proposals, no. 7516, September 2023. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7516. \ No newline at end of file diff --git a/BEPs/BEP-346.md b/BEPs/BEP-346.md new file mode 100644 index 000000000..9fa6e3ea5 --- /dev/null +++ b/BEPs/BEP-346.md @@ -0,0 +1,69 @@ +
+  BEP: 346
+  Title: Streamline off-chain authentication on Greenfield
+  Status: Candidate
+  Type: Standards
+  Created: 2024-03-14
+
+ + +# BEP-346: Streamline off-chain authentication on Greenfield + +- [BEP-346: Streamline off-chain authentication on Greenfield](#bep-346-streamline-off-chain-authentication-on-greenfield) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [5. License](#5-license) + + +## 1. Summary +This BEP introduces GNFD2-EDDSA, a simplified off-chain authentication signature verification method. It streamlines the authentication process, reducing developer integration complexity and improving user interaction. + +## 2. Motivation + +Greenfield is an object storage system with permission management. SP uses an off-chain authentication mechanism to authenticate users from the dApps. For more details, refer to [Greenfield Storage Provider Off-Chain Authentication](https://github.com/bnb-chain/greenfield-storage-provider/blob/master/docs/modules/authenticator.md). + +In the previous design, users first needed to request a Metamask signature to derive an EdDSA private key. Subsequently, registering this EdDSA public key with various SPs required another Metamask signature. We strive to simplify the off-chain authentication procedure by consolidating the two signatures into a single one. + + +## 3. Status +This BEP is in progress. + +## 4. Specification + +When maintaining security integrity, we recommend streamlining the off-chain authentication process as follows: + +1. In a dApp frontend, a random EdDSA private key is generated without fetching a nonce from the service provider or requesting a user wallet signature, and this private key would be stored in the browser's local storage. The generation of a private EdDSA key is to use Ed25519 as the EdDSA curve. Here is the sample code: + ``` + // use js lib at https://github.com/paulmillr/noble-ed25519 + const privateKeyBytes = ed.utils.randomPrivateKey(); + ``` + +2. To register the user’s current EdDSA public key with SPs, users are required to sign the message. This step ensures SPs can verify the user's identity. The simplified content for signing is as follows: + + ``` + https://www.yourwebsite.com wants you to sign in with your BNB Greenfield account:0xA4cFxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0af6 + Register your identity public key 280e1a3f143215c010db9c4f1bbd0675b39356a8ee8b4b3b6f965b5c7a42d3aa + URI: https://www.yourwebsite.com + Version: 1 + Chain ID: 1017 + Issued At: 2024-03-02T07:24:24Z + Expiration Time: 2024-03-07T07:24:24Z + ``` + + After users register their EdDSA public keys with the SPs, they can sign requested messages using the private key. This allows the SP to verify their identity based on the registered public key. This off-chain authentication signature doesn't require block chain network operations, so users can verify signatures without switching to the Greenfield network. + +3. When a user initiates a request to the SP, they sign the request using the EdDSA private key generated in step one. The signature is then placed in the authorization field of the header. To ensure backward compatibility, this new signature verification method is labeled as GNFD2-EDDSA. While the previous signature verification method is no longer recommended, it is still supported. The new format is as follows: + + ``` + Authorization = auth_type + "," + Signature + string-to-sign = crypto.Keccak256(canonical) + Signature = ed25519.Sign(privateKey, string-to-sign) + + Authorization: GNFD2-EDDSA, Signature=0a9d0e0c4778cdfbbc7d86f4aad2651d3c0140c15a80b4f80315dee58987c2a401877bfb05aef6f8a9c4137b8587a4f02536b3cb7e303c444edaacee476e7ad2 + ``` + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-362.md b/BEPs/BEP-362.md new file mode 100644 index 000000000..d72b5ece3 --- /dev/null +++ b/BEPs/BEP-362.md @@ -0,0 +1,117 @@ +
+  BEP: 362
+  Title: Greenfield Storage Fee Paymaster
+  Status: Candidate
+  Type: Standards
+  Created: 2024-03-14
+
+ + +# BEP-362: Greenfield Storage Fee Paymaster + +- [BEP-362: Greenfield Storage Fee Paymaster](#bep-362-greenfield-storage-fee-paymaster) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 Create and update bucket](#41-create-and-update-bucket) + - [4.2 Set the flow rate limit for a bucket](#42-set-the-flow-rate-limit-for-a-bucket) + - [4.3 Update bucket payment address](#43-update-bucket-payment-address) + - [5. License](#5-license) + +## 1. Summary +The BEP introduces a storage fee paymaster solution for sponsors to cover storage costs on Greenfield, making it easier +for regular users to utilize the platform. Currently, users need to pay the storage fee for the buckets by themselves, +so they need to hold BNB in Greenfield and understand the charging mechanism. Allowing the sponsors to pay the storage +fee for the users will make it easier to use Greenfield. + +## 2. Motivation + +Objects stored on Greenfield incur storage fees, with additional data access incurring read traffic fees. +Greenfield employs stream payment to charge for storage and read traffic. For regular users, grasping the concept of +stream payment and knowing when to renew can be challenging. Users need to know what is the stream payment and they +need to calculate the cost of the BNB according to the price of storage which is confusing for normal users. +To address this, we aim to introduce the Paymaster approach, enabling sponsors to cover storage and read traffic costs for their users seamlessly. + +## 3. Status + +This BEP is in progress. + +## 4. Specification + +### 4.1 Create and update bucket + +When creating a bucket via `MsgCreateBucket`, users can specify a payment address for the bucket to make payments. + +``` +message MsgCreateBucket { + string creator = 1; + string bucket_name = 2; + VisibilityType visibility = 3; + string payment_address = 4; + ... +} +``` + +In previous implementations, this payment address had to be the bucket owner or be created by the bucket owner. +However, in the new design, we allow this payment address to be any address. + +Users can specify any payment address when creating the bucket. But if the payment address does not set a flow rate +limit(which you can refer to [below section](#42-set-the-flow-rate-limit-for-a-bucket)) for the bucket, they may not use the bucket normally. + +Users can also update the payment address for the bucket via the `MsgUpdateBucketInfo` by specifying the payment address +to be replaced if they want to use another payment address after creating the bucket. + +We recommend setting the bucket's payment address to the sponsor's payment address for optimal convenience and flexibility. + +### 4.2 Set the flow rate limit for a bucket + +When the payment account’s owner of a bucket is different from the bucket owner, it is necessary to check if the current +payment flow exceeds the flow rate limit when deducting charges for streaming payments. + +The payment account owner can use the `MsgSetBucketFlowRateLimit` transaction to set the maximum payment flow size for a +specific bucket. The default flow rate limit is 0, but if the payment account is owned by the bucket owner, the default +flow rate limit is unlimited. If the payment account owner hasn't set a flow rate limit for the bucket, users can't create +any objects in it or set read quota for the bucket. + +``` +message MsgSetBucketFlowRateLimit { + // operator defines the account address of the operator, either the object owner or the updater with granted permission. + string operator = 1; + // bucket_name defines the name of the bucket + string bucket_name = 2; + // bucket_owner defines the account address of the bucket owner + string bucket_owner = 3; + // payment_address defines an account address to pay the fee for the bucket. + string payment_address = 4; + // flow_rate_limit defines the flow rate limit of the bucket + string flow_rate_limit = 5; +} +``` + +The payment account owner can send a `MsgSetBucketFlowRateLimit` transaction on the Greenfield side to set the flow rate +limit for a bucket. However, this process requires maintaining a backend program to detect the creation of a qualifying +bucket and trigger the transaction for setting it up. A more recommended approach would be to wait for the implementation +of the GreenfieldExecutor contract in another BEP for improving Greenfield cross-chain programming capability to enable +setting flow rate limits via smart contract. Once this is in place, users can directly create buckets on the BSC/opBNB +side and specify a payment address as a contract address. By doing so, users can simultaneously create a bucket and invoke +the payment contract address to set the flow rate limit, eliminating the need for backend transaction triggers and enabling +automatic flow rate limit configuration. + + +The payment account owner can adjust the flow rate limit for the bucket. The rules for adjusting the limit are as follows: + +1. Setting the new flow rate limit to 0 indicates will stop the payment for the bucket, the bucket is rate-limited and the user can’t use the bucket as normal. +2. Setting the new flow rate limit under the current flow rate of the bucket is the same as setting the new flow rate limit to 0. +3. To resume payment for the bucket, the flow rate limit must be set to a value not lower than the current net flow rate of the bucket. +4. The user’s operation will be rejected if the flow rate of the bucket exceeds the flow rate limit. + +### 4.3 Update bucket payment address + +When the payment account no longer pays for the bucket or the bucket is rate-limited by the current payment account, +the bucket owner can update the payment address to continue using the bucket. In this case, users will need to utilize +the new payment address for making payments. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-363.md b/BEPs/BEP-363.md new file mode 100644 index 000000000..77b32da64 --- /dev/null +++ b/BEPs/BEP-363.md @@ -0,0 +1,215 @@ +
+  BEP: 363
+  Title: Improve Greenfield cross-chain programming capability
+  Status: Draft
+  Type: Standards
+  Created: 2024-03-15
+
+ +# BEP-363: Improve Greenfield cross-chain programming capability + +- [BEP-363: Improve Greenfield cross-chain programming capability](#bep-363-improve-greenfield-cross-chain-programming-capability) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 MultiMessage](#41-multimessage) + - [4.1.1 Framework](#411-framework) + - [4.1.2 API](#412-api) + - [4.1.3 Inputs Encode](#413-inputs-encode) + - [4.1.4 Error Handling](#414-error-handling) + - [4.1.5 Relayer Fee](#415-relayer-fee) + - [4.1.6 Execution Order](#416-execution-order) + - [4.2 GreenfieldExecutor](#42-greenfieldexecutor) + - [4.2.1 Support Msgs](#421-support-msgs) + - [4.2.2 API](#422-api) + - [4.2.3 Error Handling](#423-error-handling) + - [4.2.4 Execution Order](#424-execution-order) + - [4.2.5 Pros and Cons](#425-pros-and-cons) + - [5. License](#5-license) + +## 1. Summary + +This BEP introduces enhanced cross-chain programming through a multi-message channel and a general Greenfield executor channel. It allows triggering Greenfield operations on BSC/opBNB without users having to switch between networks. + +## 2. Motivation + +Greenfield was initially designed with integrated cross-chain capabilities for BSC and opBNB. This allows users on the BSC/opBNB side to interact with Greenfield's features like buckets, objects, groups, permissions, and more through smart contracts. However, these different operations are currently carried out independently through separate cross-chain channels, lacking atomicity. For instance, if a user wants to sell a bucket on the BSC/opBNB side, the common procedure involves: + +1. Calling the createBucket method in the BucketHub contract to create a new bucket. +2. Calling the createGroup method in the GroupHub contract to create a new group. +3. Calling the createPolicy method in the PermissionHub contract to grant members of this group access to the contents of the bucket. +4. If users wish to purchase access to this bucket, they can be added as members of the group through GroupHub. + +Among the operations mentioned, some may succeed while others may fail, which makes error handling challenging. + +Besides that, dApps developed on Greenfield, such as a data marketplace, require users to switch back and forth between BSC/opBNB and Greenfield. This back-and-forth can lead to a suboptimal user experience, as users may find it challenging to determine the correct network for initiating operations. + +Since the introduction of [BEP-364: Primary Storage Provider acts as the upload agent for object creation and update on Greenfield](https://github.com/bnb-chain/BEPs/pull/364), users no longer need to switch to Greenfield to send transactions for object creation. However, Greenfield's cross-chain capabilities with BSC and opBNB are currently limited, restricting users from completing all operations on Greenfield via BSC/opBNB. Therefore, through this BEP, we aim to enhance Greenfield's cross-chain programming capabilities with BSC and opBNB, enabling users to seamlessly access and manipulate resources on Greenfield directly from the BSC/opBNB network. + + +## 3. Status + +This BEP is in progress. + +## 4. Specification + +In this BEP, we introduce a new MultiMessage contract, which incorporates a composite cross-chain channel. Users can aggregate different cross-chain operations by initiating cross-chain requests through the MultiMessage contract. These cross-chain requests will either all succeed or all fail, ensuring the atomicity to safeguard user actions. + +Additionally, we introduce a new GreenfieldExecutor contract, enabling users to initiate most of transactions on the Greenfield side that is feasible from the BSC/opBNB network. + +### 4.1 MultiMessage + +MultiMessage contract is designed for sending cross-chain messages that require composition. It is important to note that the MultiMessage contract is limited to supporting existing cross-chain operations such as BucketHub, ObjectHub, GroupHub, PermissionHub, and TokenHub. It enhances these functionalities by providing aggregation capabilities to support the atomicity of composite operations. + +#### 4.1.1 Framework + +There will be a new channel, MULTI_MESSAGE_CHANNEL_ID(0x08), a new system contract on the BSC side, and a new cross-app on the Greenfield side for this new message type. We will reuse the existing infra as much as possible. The whole framework will be like this: + +![4.1.1 Framework](./assets/bep-363/4.1.1_framework.png) + +The MultiMessage contract facilitates the creation of composite transactions by leveraging existing middle-layer contracts. Upon receiving packages from the MultiMessage channel, the new MultiMessage app endeavors to decode and break down the composite package into individual syn packages, distributing them to the appropriate cross apps. Subsequently, the MultiMessage app consolidates all executed results and transmits the ack package. If any of these operations fail, the entire transaction will be reverted and returned, ensuring the atomicity of the transaction. The MultiMessage contract decodes the ack package and processes it using the existing contracts again. + +#### 4.1.2 API + +It offers the following API: + +```solidity +function sendMessages(address[] calldata _targets, bytes[] calldata _data, uint256[] calldata _values) external payable returns (bool); +``` + +- `_targets`: Represents contract addresses to be called. They should be the cross-chain middle layer contracts like BucketHub, ObjectHub, GroupHub, and PermissionHub. + +- `_data`: Describes the calldata to be passed to the target contract. It should be `abi.encodeCall(TARGET_CONTRACT.FUNCTION_NAME, [PARAMETERS])`. + +- `_values`: Indicates the `msg.value` parameter for calling the target contract. + +The length of these arrays should be the same. The group of 3 values at each index(_targets[i], _data[i], _value[i]) represents an operation. + +#### 4.1.3 Inputs Encode + +The `_data` field is crucial for defining transaction content. To help generate this, BucketHub, ObjectHub, GroupHub, PermissionHub, and TokenHub will add encoding interfaces respectively. The interfaces will be like: + +```solidity +// Encode CreateBucket without callback +function encodeCreateBucket( + address sender, + CreateBucketSynPackage memory synPkg +) public payable returns (uint8, bytes memory, uint256, uint256, address); + +// Encode CreateBucket with callback +function encodeCreateBucket( + address sender, + CreateBucketSynPackage memory synPkg, + uint256 callbackGasLimit, + ExtraData memory extraData +) public payable returns (uint8, bytes memory, uint256, uint256, address); +``` + +These methods assist users in creating payloads for specific operations. For example, to send a MultiMessage transaction that includes creating a bucket and a group, and then binding the group to the bucket, the actor could do it by: + +```solidity +address sender; + +// 1. get the `_data` for creating bucket +CreateBucketSynPackage memory createBPkg; +bytes memory createBData = abi.encodeCall(IBucketHub.encodeCreateBucket, (sender, createBPkg)); + +// 2. get the `_data` for creating group +CreateGroupSynPackage memory createGPkg; +bytes memory createGData = abi.encodeCall(IGroupHub.encodeCreateGroup, (sender, createGPkg)); + +// 3. get the `_data` for binding +bytes memory bindMsg; +bytes memory createPData = abi.encodeCall(IPermissionHub.encodeCreatePolicy, (sender, bindMsg)); + +// 4. assemble all the params and call the contract +address[] memory targets = new address[](3); +bytes[] memory data = new bytes[](3); +uint256[] memory values = new uint256[](3); +targets[0] = BUCKET_HUB_ADDRESS; +targets[1] = GROUP_HUB_ADDRESS; +target[2] = PERMISSION_HUB_ADDRESS; +datas[0] = createBData; +datas[1] = createGData; +datas[2] = createPData; +(uint256 relayFee, uint256 minAckRelayFee) = ICrossChain(CROSS_CHAIN).getRelayFees(); +uint256 totalFee = relayFee + minAckRelayFee; +for (uint i;i < 3;++i) { + values[i] = totalFee; +} + +IMultiMessage(MULTI_MESSAGE_ADDRESS).sendMessages(targets, data, values); +``` + +#### 4.1.4 Error Handling + +Actors can specify different extra data for different operations by the encoding methods. The MultiMessage contract will execute the ack package of each operation one by one. For a dApp, there's no difference in the error handling process between sending 5 transactions at once by MultiMessage and sending 5 transactions separately. + +#### 4.1.5 Relayer Fee + +Actors can specify different relayer fees for different operations by the `_values`. The sum of `_values` should be equal to the `msg.value`. + +#### 4.1.6 Execution Order + +The transactions will be executed in the order specified in the input array. So please ensure that the order of elements is reasonable. For example, creating a bucket and a group must precede binding them. + +### 4.2 GreenfieldExecutor + +The GreenfieldExecutor contract acts as a wrapper, enabling users to execute transactions on the BSC/opBNB side that is possible on the Greenfield side. For instance, if a user needs to purchase read quota for a bucket, a capability not currently supported by any cross-chain operations, they would typically have to send a MsgUpdateBucketInfo message on the Greenfield network to make the purchase. To streamline this process and eliminate the need for users to switch to the Greenfield network, they can utilize GreenfieldExecutor to execute such transactions, allowing them to perform most of Greenfield operations on the BSC/opBNB network. + +#### 4.2.1 Support Msgs + +For safety reasons, GreenfieldExecutor will only support a subset of Greenfield messages. The supported messages are: +- MsgCreatePaymentAccount +- MsgDeposit +- MsgDisableRefund +- MsgUpdateParams +- MsgWithdraw +- MsgMigrateBucket +- MsgCancelMigrateBucket +- MsgCompleteMigrateBucket +- MsgRejectMigrateBucket +- MsgUpdateBucketInfo +- MsgToggleSPAsDelegatedAgent +- MsgDiscontinueBucket +- MsgSetBucketFlowRateLimit +- MsgCopyObject +- MsgDiscontinueObject +- MsgUpdateObjectInfo +- MsgLeaveGroup +- MsgUpdateGroupExtra +- MsgSetTag +- MsgCancelUpdateObjectContent + +#### 4.2.2 API + +GreenfieldExecutor provides the following interface: + +```solidity +function execute(uint8[] calldata _msgTypes, bytes[] calldata _msgBytes) external payable returns (bool); +``` + +- `_msgTypes`: Represents the msgs type. we will provide a list for the supported Greenfield messages and theirs corresponding index. The length of this array should be the same as the `_data` array. +- `__msgBytes`: Represents the collection of Greenfield messages' bytes to be executed. Multiple messages can be executed simultaneously, but this operation does not guarantee atomicity. Additionally, there is no notification sent back to the initiating side on BSC/opBNB regarding the success or failure of the execution. We will provide a tool to help get the encoded bytes. + +#### 4.2.3 Error Handling + +This message type will not have an ack package or callback to handle. Regardless of whether the transaction executes successfully, actors on the BSC side will not receive feedback. Therefore, for existing cross-chain message types, we still recommend using proprietary contracts to send transactions rather than using GreenfieldExecutor. + +#### 4.2.4 Execution Order + +The transactions will be executed in the order specified in the `_data` array. + +#### 4.2.5 Pros and Cons + +- Pros: + 1. The cross-chain functionality has been further enhanced, improving user-friendliness. Users can now bypass the hassle of switching networks. + +- Cons: + 1. Due to design complexities, error handling is not implemented, resulting in users being unable to receive feedback on transaction results. + 2. Initiating transactions on Greenfield via GreenfieldExecutor incurs additional cross-chain fees, making it more costly than initiating transactions directly on the Greenfield network. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-364.md b/BEPs/BEP-364.md new file mode 100644 index 000000000..5d622b11b --- /dev/null +++ b/BEPs/BEP-364.md @@ -0,0 +1,161 @@ +
+  BEP: 364
+  Title: Primary Storage Provider acts as the upload agent for object creation and update on Greenfield
+  Status: Candidate
+  Type: Standards
+  Created: 2024-03-16
+
+ + +# BEP-364: Primary Storage Provider acts as the upload agent for object creation and update on Greenfield + +- [BEP-364: Primary Storage Provider acts as the upload agent for object creation and update on Greenfield](#bep-364-primary-storage-provider-acts-as-the-upload-agent-for-object-creation-and-update-on-greenfield) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 APIs](#41-apis) + - [4.1.1 SP APIs](#411-sp-apis) + - [SDK](#sdk) + - [4.1.2 Greenfield Chain New Messages](#412-greenfield-chain-new-messages) + - [4.2 New workflow for object creation/update on Greenfield](#42-new-workflow-for-object-creationupdate-on-greenfield) + - [4.2.1 Users](#421-users) + - [4.2.2 SP](#422-sp) + - [4.3 Security](#43-security) + - [5. License](#5-license) + + +## 1. Summary +This BEP introduces a new method where the primary storage provider (SP) acts as the upload agent for creating objects in Greenfield. It allows users to send objects directly to the primary SP without sending transactions on chain. The primary SP will then create the object on-chain on behalf of the user, eliminating the requirement for users to switch over to the Greenfield network and incur gas fees when they create objects on Greenfield. + +## 2. Motivation + +The current object creation process requests users to send a MsgCreateObject transaction to the Greenfield chain. After the object is successfully created on chain, users would then send the object's payload data to the primary SP for data storage. Once the primary SP confirms the object’s integrity and distributes the EC chunks to secondary SPs, a MsgSealObject transaction will be sent to the Greenfield chain to finalize the object, enabling regular access to the object afterward. + +This approach ensures the safety of object creation. However, when integrating with Greenfield, developers often face the following challenges: + +Developers must conduct erasure coding (EC) processing and calculate checksums for objects on the client side. This increases integration complexity and resource usage on the client, particularly affecting user experience when handling large objects on web platforms. + +When a user uploads an object on Greenfield, they are required to initiate a transaction to create the object. This process presents several challenges: +Users must switch to the Greenfield network before uploading objects. +Users need to possess BNB on the Greenfield network. +Each object upload requires a transaction confirmation, resulting in multiple wallet pop-ups for signatures when uploading many objects. Greenfield provides a batch upload solution using temporary accounts, but this method complicates integration. + +The process for uploading objects is too complex, needing many interactions with SP and the Greenfield chain, making integration harder. Some project stakeholders may find integration exceptionally challenging if they can't use the official SDK directly due to version problems. + +In light of the challenges encountered during the previous object creation process in Greenfield, we are planning to introduce a new method of object creation while retaining the existing approach. + +The new solution enables users to send objects to the Primary SP directly using SP's API, eliminating the need for users to perform any additional steps. This significantly streamlines the complexity of object creations for users. + +## 3. Status +This BEP is in progress. + +## 4. Specification + +### 4.1 APIs + +#### 4.1.1 SP APIs + +SP currently exposes two APIs for users to upload object after they created/updated the object on-chain: + +- for small objects, refer [here](https://github.com/bnb-chain/greenfield-storage-provider/blob/master/docs/storage-provider-rest-api/put_object.md) for more details. +- resumable upload for large objects, refer to [this doc](https://github.com/bnb-chain/greenfield-storage-provider/blob/master/docs/storage-provider-rest-api/resumable_put_object.md). +for delegators who want to upload objects to SP, APIs are almost the same and users just need to specify it is a delegated request using the query parameter “delegate”, if it is for object update, specify the query parameter “is_update”. + +| ParameterName | Type | Required | Description | +| ------------- |:-------------:|--------------:|-----| +| delegate | string | false | specify whether need SP to delegate create object onchain. Either “” or not provided | +| is_update | string | false | specify whether to delegate to update a existing object. Either true or false | + +##### SDK +There are encapsulated interfaces provided by `greenfiled-go-sdk` to fulfill users' needs. + +`DelegatePutObject` + +The `DelegatePutObject` interface enables users to send objects to the primary SP, allowing the primary SP to create objects on the chain on behalf of the user. It supports resumable uploads, by automatically fetching previously uploaded segments to allow for seamless continuation, improving upload efficiency. + +```go +DelegatePutObject(ctx context.Context, bucketName, objectName string, objectSize int64, reader io.Reader, opts types.PutObjectOptions) error +``` + +`DelegateUpdateObjectContent` + +The `DelegateUpdateObjectContent` interface enables users to send updated objects to the primary SP directly without interaction with the Greenfield chain to update their existing object, allowing the primary SP to update objects on the chain on behalf of the user. + +```go +DelegateUpdateObjectContent(ctx context.Context, bucketName, objectName string, objectSize int64, reader io.Reader, opts types.PutObjectOptions) error +``` + +#### 4.1.2 Greenfield Chain New Messages + +Greenfield introduces several new messages for SP acts as the upload agent feature + +`MsgDelegateCreateObject` + +The MsgDelegateCreateObject message enables the primary SP linked to a bucket to create objects on behalf of users authorized to do so within the bucket. It includes below attributes: +- Operator: the account address of the SP +- Creator: the account address of the object creator +- BucketName: the name of the bucket +- ObjectName: the name of object +- PayloadSize: size of the object's payload +- ContentType: the format of the object which should be a standard MIME type. +- Visibility: visibility means the object is private or public +- ExpectChecksums: a list of hashes which was generated by the redundancy algorithm. It is optional. +- RedundancyType: can be ec or replica + +The MsgDelegateUpdateObjectContent message enables the primary SP linked to a bucket to update objects on behalf of users authorized to do so within the bucket. It includes below attributes: +- Operator: the account address of the SP +- Updater: the account address of the object updater +- BucketName: the name of the bucket +- ObjectName: the name of the object +- PayloadSize: the size of the object's payload +- ContentType: the format of the object which should be a standard MIME type +- ExpectChecksums: a list of hashes which was generated by the redundancy algorithm. It is optional + +`MsgSealObjectV2` + +In our previous implementation, users were responsible for calculating the checksum themselves and specifying it during object creation. However, in this new method, when the SP creates an object, it does not have the complete object information. It has to wait until the SP seals the object to fill this information into the object info. To address this, we need to upgrade the MsgSealObject message to MsgSealObjectV2 to enhance this functionality. + +`MsgToggleSPAsDelegatedAgent` + +It is used by bucket owners to enable/disable the delegated create/update feature for a specific bucket. +- Operator: account address of the operator, only the bucket owner can send the tx +- BucketName: the name of the bucket + +### 4.2 New workflow for object creation/update on Greenfield + +The delegate create/update object workflows is outlined below: + +![4.2 Workflow](./assets/bep-364/workflow.png) + +#### 4.2.1 Users +Users can simply use the APIs introduced in section 4.1, to upload objects to the primary SP of the bucket, without incurring any transaction fees or having to switch to the Greenfield network. + + +Users are required to sign the message. This step ensures SPs can verify the user's identity. +If users use go-sdk/js-sdk to send the “create/update object” request to SPs, the wallet signature will be added to the request automatically. +If users use a web-based Dapp, the Dapp needs to integrate Greenfield off-chain-auth mechanism, which has a built-in EDDSA signing process and makes sure that the request sent to SPs are attached with users’ signature. About EDDSA authentication, see BEP-346 + +#### 4.2.2 SP + +SP needs to do the following tasks: +1. Ensure the user has permission to create/update the object in the bucket. Send the MsgDelegateCreateObject/MsgUpdateObject transaction to Greenfield to create/update the object that represents the user, and wait for the object ID if creating a new object. +2. After generating the object ID on-chain, store the object piece and its metadata in S3 and the database promptly. +3. After the object is fully uploaded, the integrity hash for all segments will be calculated and stored in the database by the primary SP. +4. The primary SP should execute erasure coding (EC), calculate integrity hashes for each EC chunk, store them in the database, and replicate all EC chunks to the secondary SPs. +5. The secondary SP verifies the integrity hash of the received piece with the one sent by the primary SP, then signs to seal the object. +6. The primary SP collects signatures from secondary SPs, seals the object on-chain, and adds the integrity hash to objectinfo. + +### 4.3 Security + +This type of proxy for creating objects provides users with great convenience, but it also introduces potential security issues: +1. The primary SP may have the potential to tamper with objects. In such cases, users can download the objects for comparison. The easiest method is to use the md5sum tool for verification. +2. The primary SP may maliciously substitute objects not specified by the user for upload. In such cases, since the transactions creating the objects are all recorded on the blockchain, users can easily trace and find evidence of this situation. + +Once users detect malicious behavior from the primary SP, they have the following options: +1. Users can send the tx `ToggleSPAsDelegatedAgent` to prevent the Primary SP from creating files further, users can create object on their own. +2. By initiating the `MigrateBucket` operation, users can switch the primary SP and select a trusted SP to act as the new primary SP for the Bucket. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-366.md b/BEPs/BEP-366.md new file mode 100644 index 000000000..82405cc86 --- /dev/null +++ b/BEPs/BEP-366.md @@ -0,0 +1,109 @@ +
+  BEP: 366
+  Title: Greenfield Atomic Object Update
+  Status: Candidate
+  Type: Standards
+  Created: 2024-01-18
+
+ +# BEP-366: Greenfield Atomic Object Update + + + + + +- [BEP-366: Greenfield Atomic Object Update](#bep-366-greenfield-atomic-object-update) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 Requirements](#41-requirements) + - [4.2 Implementation](#42-implementation) + - [4.2.1. Change To Current Model](#421-change-to-current-model) + - [4.2.1. New Model And Message](#421-new-model-and-message) + - [4.3 Workflow](#43-workflow) + - [4.4 Fees \& User Charges](#44-fees--user-charges) + - [5. License](#5-license) + + +## 1. Summary +This proposal seeks to enhance the efficiency and reliability of object modifications in the Greenfield network by introducing +atomic object updates. This update will improve the management of objects in Greenfield by ensuring atomicity, and consistency. + +## 2. Motivation +Currently, users face the inconvenience of having to delete and recreate objects in Greenfield in order to replace their content. +This process results in the updated object being assigned a new ID, causing associated policies to be lost since they are based on object ID. +This restriction also applies to [Resource Mirror](https://docs.bnbchain.org/bnb-greenfield/core-concept/cross-chain/mirror/). +Consequently, users are required to re-enforce policies and re-trigger mirroring on the updated object if they had previously done so. +The proposed solution aims to address these issues and offer a more efficient and seamless object update process. + +## 3. Status +This BEP is under progress + +## 4. Specification + +### 4.1 Requirements +- Atomicity: Atomicity refers to the ability to ensure that updates to an object either all succeed or all fail, guaranteeing that the object is not partially updated. +- Consistency: Ensures that an object remains in a valid and predictable state after a successful update. Object metadata on the Greenfield Blockchain and the data stored on the Storage Provider will be maintained to ensure users can retrieve correct object data at any state of the updating process. + +### 4.2 Implementation + +#### 4.2.1. Change To Current Model +- ObjectInfo: + ObjectInfo is used for object metadata stored in Greenfield. Below fields are added. + - `updating`: Indicate whether an object is being updated. It means the user has initiated an update request, and the SP has not committed the change to Greenfield yet. + - `updated_at`: The timestamp that the user initiated to update the object. The storage price is determined by it, and a new store fee needs to be calculated. + - `version`: The current version of the object. It can be used to locate the correct version of object data in SP. + +#### 4.2.1. New Model And Message +- `ShadowObjectInfo`: It is introduced to store user updated object metadata, the life cycle for a shadowObjectInfo is + started when users trigger the update request on Greenfield, once SP has the updated object data stored and confirm + on Greenfield, it will be removed. + - `operator`: The account who initiates update object request, can be the owner or any account that has been granted permission to update object content. + - `id`: The id of the object, it is the same as the id in ObjectInfo. + - `payload_size`: The updated object size. + - `checksums`: The updated checksums of pieces stored in storage providers. + - `updated_at`: The timestamp that user initiated to update object request. + - `version`: The expected next version of the object. +- `MsgUpdateObjectContent`: A new message for users' update object content transaction. The new object's payload_size, + checksums along with approval from primary SP's approval need to be specifcied. + - `operator`: The account who initiates update object request, can be the owner or any account that has been granted permission to update object content. + - `bucket_name`: The bucket name which object belongs to. + - `object_name`: The object name. + - `payload_size`:The updated object size. + - `content_type`: The timestamp that user initiated to update object request. + - `expect_checksums`: The updated checksums of pieces stored in storage providers. + +## 4.3 Workflow + +The steps to update an object are illustrated below. To users, it is similar when compared to the current create-upload object process. + +![](assets/BEP-366/workflow.png) + +1. Users send the transaction to Greenfield with the message `MsgUpdateObjectContent`. This stores the updated object metadata via shadowObjectInfo and flags the object as + updating without changing the objectInfo on-chain. + +2. Users upload the updated object to the primary SP. The SP will validate if the object can be updated and authenticate + the user's account permission. + +3. The SP should keep the original and updated object data simultaneously. Version in ObjectInfo or ShadowObjectInfo is + also used to identify the object data persistence to ensure there is no conflict. Users should be able to `GET` + the original object data at this moment as the version field has not changed. + +4. The primary SP sends the sealing object transaction to the Greenfield blockchain, changes to objectInfo will take effect according + to meta stored in shadowObjectInfo with version increment. Users will be able to GET the updated object data. + In the case where SP fails to seal the object after retries, it would send tx RejectSealobject to Greenfield to reject + the users request. The metadata ShadowObjectInfo will be removed from chain, updated object data will be removed from SP. + +## 4.4 Fees & User Charges +The current policy regarding user charges is as follows: When users create and upload an object, a minimum of 6 months +storage fee is reserved on Greenfield. This fee is then paid to the Storage Providers' accounts through stream payment. +If objects are stored for more than 6 months, the storage fee will be calculated based on the actual time. +This rule applies to updating objects as well. When users update an object, Greenfield will deduct the payment for the +original object from users’s account and reserve at least 6 months of storage fee for the updated object, taking into +account the new object size. It's important for users to be aware that each time an object is updated, there will be +associated costs. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-381.md b/BEPs/BEP-381.md new file mode 100644 index 000000000..e088f68f7 --- /dev/null +++ b/BEPs/BEP-381.md @@ -0,0 +1,211 @@ +
+  BEP: 381
+  Title: Precompile for secp256r1 Curve Support
+  Status: Draft
+  Type: Standards
+  Created: 2024-04-17
+
+ +# BEP-381: Precompile for secp256r1 Curve Support + + + + + +- [BEP-381: Precompile for secp256r1 Curve Support](#bep-381-precompile-for-secp256r1-curve-support) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1.1 Elliptic Curve Information](#411-elliptic-curve-information) + - [4.1.2 Elliptic Curve Signature Verification Steps](#412-elliptic-curve-signature-verification-steps) + - [4.2 Required Checks in Verification](#42-required-checks-in-verification) + - [4.3 Precompiled Contract Specification](#43-precompiled-contract-specification) + - [4.4 Precompiled Contract Gas Usage](#44-precompiled-contract-gas-usage) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#7-test-cases) + - [8. Reference Implementation](#8-reference-implementation) + - [9. Security Considerations](#9-security-considerations) + - [10. Copyright](#10-copyright) + + +## 1. Summary + +This proposal creates a precompiled contract that performs signature verifications in the “secp256r1” elliptic curve by given parameters of message hash, `r` and `s` components of the signature, `x` and `y` coordinates of the public key. So that, any EVM chain - principally Ethereum rollups - will be able to integrate this precompiled contract easily. + +## 2. Motivation + +“secp256r1” elliptic curve is a standardized curve by NIST which has the same calculations by different input parameters with “secp256k1” elliptic curve used by the “ecrecover” precompiled contract. The cost of combined attacks and the security conditions are almost the same for both curves. Adding a precompiled contract which is similar to "ecrecover" can provide signature verifications using the “secp256r1” elliptic curve in the smart contracts and multi-faceted benefits can occur. One important factor is that this curve is widely used and supported in many modern devices such as Apple’s Secure Enclave, Webauthn, Android Keychain which proves the user adoption. Additionally, the introduction of this precompiled contract could enable valuable features in the account abstraction which allows more efficient and flexible management of accounts by transaction signs in mobile devices. +Most of the modern devices and applications rely on the “secp256r1” elliptic curve. The addition of this precompiled contract enables the verification of device native transaction signing mechanisms. For example: + +1. **Apple's Secure Enclave:** There is a separate “Trusted Execution Environment” in Apple hardware which can sign arbitrary messages and can only be accessed by biometric identification. +2. **Webauthn:** Web Authentication (WebAuthn) is a web standard published by the World Wide Web Consortium (W3C). WebAuthn aims to standardize an interface for authenticating users to web-based applications and services using public-key cryptography. It is being used by almost all of the modern web browsers. +3. **Android Keystore:** Android Keystore is an API that manages the private keys and signing methods. The private keys are not processed while using Keystore as the applications’ signing method. Also, it can be done in the “Trusted Execution Environment” in the microchip. +4. **Passkeys:** Passkeys is utilizing FIDO Alliance and W3C standards. It replaces passwords with cryptographic key-pairs which is also can be used for the elliptic curve cryptography. + +Modern devices have these signing mechanisms that are designed to be more secure and they are able to sign transaction data, but none of the current wallets are utilizing these signing mechanisms. So, these secure signing methods can be enabled by the proposed precompiled contract to initiate the transactions natively from the devices and also, can be used for the key management. This proposal aims to reach maximum security and convenience for the key management. + +## 3. Status +This BEP is under progress + +## 4. Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +As of `FORK_TIMESTAMP` in the integrated EVM chain, add precompiled contract `P256VERIFY` for signature verifications in the “secp256r1” elliptic curve at address `PRECOMPILED_ADDRESS` in `0x100`. + +### 4.1.1 Elliptic Curve Information + +“secp256r1” is a specific elliptic curve, also known as “P-256” and “prime256v1” curves. The curve is defined with the following equation and domain parameters: + +``` +# curve: short weierstrass form +y^2 ≡ x^3 + ax + b + +# p: curve prime field modulus +0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff + +# a: elliptic curve short weierstrass first coefficient +0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc + +# b: elliptic curve short weierstrass second coefficient +0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b + +# G: base point of the subgroup +(0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, + 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5) + +# n: subgroup order (number of points) +0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 + +# h: cofactor of the subgroup +0x1 + +``` + +### 4.1.2 Elliptic Curve Signature Verification Steps + +The signature verifying algorithm takes the signed message hash, the signature components provided by the “secp256r1” curve algorithm, and the public key derived from the signer private key. The verification can be done with the following steps: + +``` +# h (message hash) +# pubKey = (public key of the signer private key) + +# Calculate the modular inverse of the signature proof: +s1 = s^(−1) (mod n) + +# Recover the random point used during the signing: +R' = (h * s1) * G + (r * s1) * pubKey + +# Take from R' its x-coordinate: +r' = R'.x + +# Calculate the signature validation result by comparing whether: +r' == r + +``` + +### 4.2 Required Checks in Verification + +The following requirements **MUST** be checked by the precompiled contract to verify signature components are valid: + +- Verify that the `r` and `s` values are in `(0, n)` (exclusive) where `n` is the order of the subgroup. +- Verify that the point formed by `(x, y)` is on the curve and that both `x` and `y` are in `[0, p)` (inclusive 0, exclusive p) where `p` is the prime field modulus. Note that many implementations use `(0, 0)` as the reference point at infinity, which is not on the curve and should therefore be rejected. + +### 4.3 Precompiled Contract Specification + +The `P256VERIFY` precompiled contract is proposed with the following input and outputs, which are big-endian values: + +- **Input data:** 160 bytes of data including: + - 32 bytes of the signed data `hash` + - 32 bytes of the `r` component of the signature + - 32 bytes of the `s` component of the signature + - 32 bytes of the `x` coordinate of the public key + - 32 bytes of the `y` coordinate of the public key +- **Output data:** 32 bytes of result data and error + - If the signature verification process succeeds, it returns 1 in 32 bytes format. + +### 4.4 Precompiled Contract Gas Usage + +The use of signature verification cost by `P256VERIFY` is `3450` gas. Following reasons and calculations are provided in the [Rationale](#5-rationale) and [Test Cases](#7-test-cases) sections. + +## 5. Rationale + +“secp256r1” ECDSA signatures consist of `v`, `r`, and `s` components. While the `v` value makes it possible to recover the public key of the signer, most signers do not generate the `v` component of the signature since `r` and `s` are sufficient for verification. In order to provide an exact and more compatible implementation, verification is preferred over recovery for the precompile. + +Existing P256 implementations verify `(x, y, r, s)` directly. We've chosen to match this style here, encoding each argument for the EVM as a `uint256`. + +This is different from the `ecrecover` precompiled address specification. The advantage is that it 1. follows the NIST specification (as defined in NIST FIPS 186-5 Digital Signature Standard (DSS)), 2. matches the rest of the (large) P256 ecosystem, and most importantly 3. allows execution clients to use existing well-vetted verifier implementations and test vectors. + +Another important difference is that the NIST FIPS 186-5 specification does not include a malleability check. We've matched that here in order to maximize compatibility with the large existing NIST P-256 ecosystem. + +Wrapper libraries **SHOULD** add a malleability check by default, with functions wrapping the raw precompile call (exact NIST FIPS 186-5 spec, without malleability check) clearly identified. For example, `P256.verifySignature` and `P256.verifySignatureWithoutMalleabilityCheck`. Adding the malleability check is straightforward and costs minimal gas. + +The `PRECOMPILED_ADDRESS` is chosen as `0x100` as it is the next available address in the precompiled address set. + +The gas cost is proposed by comparing the performance of the `P256VERIFY` and the `ECRECOVER` precompiled contract which is implemented in the EVM at `0x01` address. It is seen that “secp256r1” signature verification is ~15% slower (elaborated in [test cases](#7-test-cases)) than “secp256k1” signature recovery, so `3450` gas is proposed by comparison which causes similar “mgas/op” values in both precompiled contracts. + +## 6. Backwards Compatibility + +No backward compatibility issues found as the precompiled contract will be added to `PRECOMPILED_ADDRESS` at the next available address in the precompiled address set. + +## 7. Test Cases + +Functional tests are applied for multiple cases in the [reference implementation](#8-reference-implementation) of `P256VERIFY` precompiled contract and they succeed. Benchmark tests are also applied for both `P256VERIFY` and `ECRECOVER` with some pre-calculated data and signatures in the “go-ethereum”s precompile testing structure to propose a meaningful gas cost for the “secp256r1” signature verifications by the precompiled contract implemented in the [reference implementation](#8-reference-implementation). The benchmark test results by example data in the assets can be checked: + +- [P256Verify Benchmark Test Results](./assets/BEP-381/p256Verify_benchmark_test) +- [Ecrecover Benchmark Test Results](./assets/BEP-381/ecrecover_benchmark_test) + +``` +# results of geth benchmark tests of +# ECRECOVER and P256VERIFY (reference implementation) +# by benchstat tool + +goos: darwin +goarch: arm64 +pkg: github.com/ethereum/go-ethereum/core/vm + │ compare_p256Verify │ compare_ecrecover │ + │ sec/op │ sec/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 57.75µ ± 1% +PrecompiledEcrecover/-Gas=3000-8 50.48µ ± 1% +geomean 57.75µ 50.48µ + + │ compare_p256Verify │ compare_ecrecover │ + │ gas/op │ gas/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 3.450k ± 0% +PrecompiledEcrecover/-Gas=3000-8 3.000k ± 0% +geomean 3.450k 3.000k + + │ compare_p256Verify │ compare_ecrecover │ + │ mgas/s │ mgas/s │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 59.73 ± 1% +PrecompiledEcrecover/-Gas=3000-8 59.42 ± 1% +geomean 59.73 59.42 + + │ compare_p256Verify │ compare_ecrecover │ + │ B/op │ B/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 1.523Ki ± 0% +PrecompiledEcrecover/-Gas=3000-8 800.0 ± 0% +geomean 1.523Ki 800.0 + + │ compare_p256Verify │ compare_ecrecover │ + │ allocs/op │ allocs/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 33.00 ± 0% +PrecompiledEcrecover/-Gas=3000-8 7.000 ± 0% +geomean 33.00 7.000 + +``` + +## 8. Reference Implementation + +Implementation of the `P256VERIFY` precompiled contract is applied to go-ethereum client to create a reference. Also, a “secp256r1” package has already been included in the Besu Native library which is used by Besu client. Other client implementations are in the future roadmap. + +## 9. Security Considerations + +The changes are not directly affecting the protocol security, it is related with the applications using `P256VERIFY` for the signature verifications. The “secp256r1” curve has been using in many other protocols and services and there is not any security issues in the past. + + +## 10. Copyright + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/), follows the original proposal [RIP-7212](https://github.com/ethereum/RIPs/blob/master/RIPS/rip-7212.md). \ No newline at end of file diff --git a/BEPs/BEP-402.md b/BEPs/BEP-402.md new file mode 100644 index 000000000..b545922e4 --- /dev/null +++ b/BEPs/BEP-402.md @@ -0,0 +1,94 @@ +
+  BEP: 402
+  Title: Complete Missing Fields in Block Header to Generate Signature
+  Status: Enabled
+  Type: Standards
+  Created: 2024-06-28
+
+ +# BEP-402: Complete Missing Fields in Block Header to Generate Signature + +- [BEP-402: Complete Missing Fields in Block Header to Generate Signature](#bep-402-complete-missing-fields-in-block-header-to-generate-signature) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [4.1 Define ParentBeaconRoot](#41-define-parentbeaconroot) + - [4.2 Encode Before Signing](#42-encode-before-signing) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [6. License](#6-license) + +## 1. Summary +Since the London upgrade on the BSC chain, 5 new fields have been added to the block header, but these fields are not used when generating the block signature. As a result, users cannot guarantee that these new fields have not been tampered with after only verifying the signature. This BEP aims to address this issue. + +## 2. Motivation +After a block producer mines a block, they first encode all fields in the block header along with the chainId, then sign it, and place the signature in the block header before broadcasting it. The receiver only needs to extract the signature and verify it to confirm whether the block has been tampered with. + +The BSC client, when signing the block header, omitted the 5 new fields. In most scenarios, this does not cause security issues, as the receiver will strictly validate these fields upon receiving the block. However, to adhere to best practices in blockchain and further enhance security, this BEP proposes to include these 5 new fields when generating the signature. + +## 3. Status +This BEP is in progress. + +## 4. Specification +
+ +
+ +### 4.1 Define ParentBeaconRoot +The ParentBeaconRoot is unnecessary for BSC and is retained for compatibility with Ethereum APIs. The value of this field will be changed from `nil` to `zero hash`, allowing the encoding stage for signing and verification to be based solely on the values of the fields in the header, independent of hard fork timing. Following Geth, the zero hash will be used as a placeholder. +```Go +header.ParentBeaconRoot = new(Hash) +``` +### 4.2 Encode Before Signing +The encoding logic will be determined based on whether `header.ParentBeaconRoot` is a zero hash. +```Go +if header.ParentBeaconRoot != nil && *header.ParentBeaconRoot == Hash{} { + encoding = rlp([chainId, + header.ParentHash, + header.UncleHash, + header.Coinbase, + header.Root, + header.TxHash, + header.ReceiptHash, + header.Bloom, + header.Difficulty, + header.Number, + header.GasLimit, + header.GasUsed, + header.Time, + // signature will be put at the end of header.Extra, exclude it + header.Extra[:len(header.Extra)-len(signature)], + header.MixDigest, + header.Nonce, + header.BaseFee, + header.WithdrawalsHash, + header.BlobGasUsed, + header.ExcessBlobGas, + header.ParentBeaconRoot, + ]) +} else { + encoding = rlp([chainId, + header.ParentHash, + header.UncleHash, + header.Coinbase, + header.Root, + header.TxHash, + header.ReceiptHash, + header.Bloom, + header.Difficulty, + header.Number, + header.GasLimit, + header.GasUsed, + header.Time, + // signature will be put at the end of header.Extra, exclude it + header.Extra[:len(header.Extra)-len(signature)], + header.MixDigest, + header.Nonce, + ]) +} +``` + +## 5. Backwards Compatibility +There are no known backward compatibility issues. +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/) \ No newline at end of file diff --git a/BEPs/BEP-404.md b/BEPs/BEP-404.md new file mode 100644 index 000000000..5d9cfbfb0 --- /dev/null +++ b/BEPs/BEP-404.md @@ -0,0 +1,54 @@ +
+  BEP: 404
+  Title: Clear Miner History when Switching Validators Set
+  Status: Enabled
+  Type: Standards
+  Created: 2024-07-01
+
+ +# BEP-404: Clear Miner History when Switching Validators Set + +- [BEP-404: Clear Miner History when Switching Validators Set](#bep-404-clear-miner-history-when-switching-validators-set) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Status](#3-status) + - [4. Specification](#4-specification) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [6. License](#6-license) + +## 1. Summary +After switching the validator set on the BSC chain, the previous block production record is still used to restrict some validators from producing blocks for the first few blocks after the switch, leading to brief network instability. This BEP aims to resolve this issue. + +## 2. Motivation +The validator set on the BSC chain switches at each epoch. + +Assume the number of validators in an epoch is validatorN. To ensure the consistency of the BSC chain, it is required that the chain must have at least validatorN/2+1 validators to continue advancing the chain. + +To achieve this constraint, a set called MinerHistory is defined, with a length of validatorN/2, recording the validators that produced the last validatorN/2 blocks. New block-producing validators are required to not be in MinerHistory. + +This BEP aims to enhance network stability by clearing MinerHistory when the validator set switches. + +## 3. Status +This BEP is in progress. + +## 4. Specification +In the previous specification, when the validator set switches at each epoch, MinerHistory is not cleared, causing some validators to be unable to produce blocks normally for the first few blocks after the switch. +
+ +
+This BEP clarifies that MinerHistory should be cleared when switching the validator set to solve this issue. + +```Go +MinerHistory map[uint64]Address + +// The conditions for switching remain unchanged +if BlockNum % EpochLength == (validatorN/2) { + MinerHistory = Address{} +} +``` + +## 5. Backwards Compatibility +There are no known backward compatibility issues. + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/) \ No newline at end of file diff --git a/BEPs/BEP-410.md b/BEPs/BEP-410.md new file mode 100644 index 000000000..f72e228db --- /dev/null +++ b/BEPs/BEP-410.md @@ -0,0 +1,106 @@ +
+  BEP: 410
+  Title: Add Agent for Validators
+  Status: Draft
+  Type: Standards
+  Created: 2024-07-15
+
+ +# BEP-410: Add Agent for Validators + +- [BEP-410: Add Agent for Validators](https://github.com/bnb-chain/BEPs/pull/410) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Reference Implementations](#5-reference-implementations) + - [6. License](#6-license) + + +## 1. Summary + +This BEP attempts to enhance the security of validator account management through account isolation by delegating some of the validator operator's permissions to other accounts. + +## 2. Abstract + +Currently, validators need to manage the operator key, consensus key, and vote key. Among these, the operator key is used for operating a validator, including creating a validator, editing the information of a validator, and undelegating. +When creating a validator, the operator key is also used for self-delegating with more than 2001 BNB. Since the operator key holds a large amount of staking, it is not suitable for daily management of the validator. +Therefore, we have introduced a new `updateAgent` interface in the system contract. Through this interface, the operator can delegate another account to manage the validator. + +## 3. Motivation + +Before this BEP, the consensus address, commission rate, validator description and vote address can only be changed by the operator which also manages staking for the validator. +To reduce the usage of operator key and improve the security of operator key management, validators can set an agent to help them to take on the mentioned tasks below. + +## 4. Specification +### Data Structure +The current [`Validator`](https://github.com/bnb-chain/bsc-genesis-contract/blob/2dbebb57a0d436d6a30b78c1f123395035249035/contracts/BC_fusion/StakeHub.sol#L154) struct is as follows. +```solidity +struct Validator { + address consensusAddress; + address operatorAddress; + address creditContract; + uint256 createdTime; + bytes voteAddress; + Commission commission; + Description description; + bool jailed; + uint256 jailUntil; + uint256 updateTime; + uint256[20] __reservedSlots; +} +``` + + +The new `Validator` struct is as follows. This BEP adds a new field `agent` and reduce a slot of `__reservedSlots` in the `Validator` struct to keep +the slot layer compatibility of upgradeable contracts. + +```solidity +struct Validator { + address consensusAddress; + address operatorAddress; + address creditContract; + uint256 createdTime; + bytes voteAddress; + Description description; + Commission commission; + bool jailed; + uint256 jailUntil; + uint256 updateTime; + // The agent can perform transactions on behalf of the operatorAddress in certain scenarios. + address agent; + uint256[19] __reservedSlots; +} +``` + +### Interface + +The validator operator can set the agent address for the validator by calling the following function. +The `newAgent` cannot be any operator address or any existing agent. +Each validator can only have one agent assigned at a time. Updating to a new agent will override the previous one. + +```solidity + function updateAgent(address newAgent) external validatorExist(msg.sender); +``` + +### Agent Permission + +The agent is allowed to edit the consensus address, commission rate, description and vote address of the validator. +The methods that can be accessed are as follows: + +```solidity + function editConsensusAddress(address newConsensusAddress) external; + function editCommissionRate(uint64 commissionRate) external; + function editDescription(Description memory description) external; + function editVoteAddress(bytes calldata newVoteAddress, bytes calldata blsProof) external; +``` + +It is notable that even after the agent is set, the operator retains the ability to edit the information listed below. + +## 5. Reference Implementations +See https://github.com/bnb-chain/bsc-genesis-contract/pull/568. + + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-414.md b/BEPs/BEP-414.md new file mode 100644 index 000000000..5f68a8428 --- /dev/null +++ b/BEPs/BEP-414.md @@ -0,0 +1,191 @@ +
+  BEP: 414
+  Title: Paymaster API Spec for EOA Wallets
+  Status: Enabled
+  Type: Standards
+  Created: 2024-07-23
+
+ +# BEP-414: Paymaster API Spec for EOA Wallets + +- [BEP-414: Paymaster API Spec for EOA Wallets](#bep-414-paymaster-api-spec-for-eoa-wallets) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Definitions](#51-definitions) + - [5.2 Workflow](#52-workflow) + - [5.3 Wallet Interaction](#53-wallet-interaction) + - [5.4 Paymaster API Spec](#54-paymaster-api-spec) + - [`pm_isSponsorable`](#pm_issponsorable) + - [`eth_sendrawtransaction`](#eth_sendrawtransaction) + - [5.5 Sponsor Policy \&\& Fee Charge](#55-sponsor-policy--fee-charge) + - [6 License](#6-license) + +## 1. Summary + +Unlike the paymaster defined in EIP-4337, this proposal introduces a paymaster solution specifically tailored for EOA (Externally Owned Account) wallets, along with standardized paymaster APIs. With minimal modifications, wallets can integrate paymasters that implement these API standards, enabling users to send transactions with zero gas fees. + +## 2. Abstract + +Under [BEP322](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP322.md)'s Proposer-Builder Separation (PBS) architecture, the validator no longer verifies individual transaction gas prices within a block. The private transactions are grouped into bundles and submitted to the builder, who prioritizes based on the aggregate gas price of each bundle. Within a single bundle, gas prices can vary—some transactions may have zero fees while others have higher fees. This flexibility enables features such as sponsored gas fees or gasless transactions. Leveraging this feature, the paymaster, after verifying the user transaction's sponsorship rules, appends a high gas price sponsor transaction to the user's transaction. These are then bundled together and submitted to the MEV builder for inclusion in the blockchain. BEP322 ensures strong atomicity for bundles, guaranteeing that both the user's transaction and the paymaster's sponsor transaction within the bundle are either included in the blockchain together or not at all. + +To integrate with multiple paymasters, existing wallets need to implement minor modifications to their current transaction sending process. These modifications primarily involve adding API calls to paymaster interfaces. This BEP standardizes the paymaster API specifications and details the step-by-step integration process for wallet developers. + +## 3. Status + +Draft. + +## 4. Motivation + +There is growing interest in sponsoring transactions for users who lack BNB for gas fees. Currently, EIP-4337 is the most widely applied solution, but it's designed for smart contract wallets. Most users still rely on EOA wallets, and EIP-7702 may potentially provide a unified Account Abstraction framework for both contract and EOA wallets in the future. Therefore, before EIP-7702's implementation, it's necessary to offer a lightweight gasless solution for EOA wallets. + +## 5. Specification + +### 5.1 Definitions + +**Bundle**: An ordered array of transactions that execute atomically, ensuring all transactions in the bundle are processed together or not at all. + +**Builder**: A new stakeholder in the MEV supply chain responsible for constructing blocks. Builders package transaction bundles, individual transactions from the public txpool, and private transaction order flow into proposed blocks. + +**Proposer**: A validator who selects the most profitable block from multiple builders' proposals for inclusion in the blockchain. + +**Paymaster**: An infrastructure component that enables transaction sponsorship, allowing self or third parties to cover gas fees. + +**Sponsor Policy**: A set of rules defined by the gas sponsor to determine which transactions qualify for sponsorship. This may include criteria such as whitelisted transaction senders or specific transaction types. + +### 5.2 Workflow +![workflow](./assets/bep-414/workflow.png) + + +Any wallet can submit a zero gas price transaction to the paymaster. The paymaster then verifies the transaction's eligibility against existing sponsor policies. If approved, it appends a high-gas-price sponsor transaction to the user's original transaction, forming a bundle. This bundle is then dispatched to multiple MEV builders for potential inclusion in a block. Leveraging the atomicity of bundles, both the user's original transaction and the sponsor's transaction are either included in the blockchain together or not at all. + +### 5.3 Wallet Interaction + +![wallet-interact](./assets/bep-414/wallet-interact.png) + +For the Wallet Implementation: + +- **Transaction Assembly**: The wallet queries the `pm_isSponsorable` API to determine transaction sponsorship eligibility. +- **Gas Price Setting**: If sponsorship is available, the wallet sets the gas price to zero and informs the user that the transaction is sponsored by the “policy name” returned by the `pm_isSponsorable` API. +- **Transaction Submission**: The wallet submits the transaction to the Paymaster using the `eth_sendRawTransaction` API. + +No further modifications to the existing process are necessary. It may take 3-9 seconds for the tx to be verified on the chain on the BSC network and 1-3 seconds on the opBNB network. + +### 5.4 Paymaster API Spec + +Paymaster needs to implement a JSON-RPC API called `pm_isSponsorable`, so that it can return sponsor and policy information to wallets. Paymaster also needs to implement `eth_sendRawTransaction` JSON-RPC API. The detailed API Specs are defined as below: + +#### `pm_isSponsorable` + +**Request Parameters** + +- `jsonrpc`: The JSON-RPC protocol version ("2.0"). +- `id`: A unique identifier for the request (1 in this example). +- `method`: The method name to be invoked ("pm_isSponsorable"). +- `params`: An array containing a single object with the following fields: + - `to`: The recipient address of the transaction. + - `from`: The sender address of the transaction. + - `value`: The value of the transaction in hexadecimal. + - `data`: Additional data for the transaction in hexadecimal. + - `gas`: The gas limit of the transaction in hexadecimal. + +**Example:** + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "method": "pm_isSponsorable", + "params": [ + { + "to": "0x...", // an address + "from": "0x...", // an address + "value": "0xa1", + "data": "0x", + "gas" : "0xa1" + } + ] +} +``` + +**Response Fields** + +- `jsonrpc`: The JSON-RPC protocol version ("2.0"). +- `id`: The unique identifier for the request (1 in this example). +- `result`: Return error if no sponsor is found for the given tx or return an object containing the sponsorship details: + - (Required) `sponsorable`: A boolean indicating whether the transaction is sponsorable (true or false). + - (Optional) `sponsorName`: The name of the sponsor. + - (Optional) `sponsorIcon`: The icon of the sponsor. + - (Optional) `sponsorWebsite`: The website of the sponsor. + + +**Example:** + +Success Match Response: +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "sponsorable": true, + "sponsorName": "MockWeb3VC Ltd.", + "sponsorIcon": "https://www.mockweb3vc.io/favicon.ico", + "sponsorWebsite": "https://www.mockweb3vc.io/" + } +} +``` +Failed Match Response: + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "sponsorable": false + } +} +``` + +#### `eth_sendrawtransaction` +The `eth_sendrawtransaction` API implemented by the Paymaster should follow this [Ethereum API Spec](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction). The client can create a new message call transaction or a contract creation for signed transactions via `eth_sendrawtransaction` API. + +**Request Parameters** +The `params` should contain the signed transaction data. + +**Example:** +```json +{ + "jsonrpc": "2.0", + "id": 1, + "method": "eth_sendRawTransaction", + "params": [ + "0x02f86a6102850df8475800850df84758000a94cd9c02358c223a3e788c0b9d94b98d434c7aa0f18080c080a0bcb0e8ffa344e4b855c6e13ee9e4e5d22cff6ad8bd1145a93b93c5d332100c2ca03765236eba5fbb357e35014fd19ba4b3c6b87f3793bd14dddf7913fc8dcc88bf" + ] +} +``` + +**Response Fields** +DATA, 32 Bytes - the transaction hash. + +**Example:** +```json +{ + "id":1, + "jsonrpc": "2.0", + "result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" +} +``` + +### 5.5 Sponsor Policy && Fee Charge +Paymasters have complete autonomy in defining sponsor policies, which can be implemented either on-chain or off-chain: + +- **On-chain policy example**: Verifying if the transaction sender holds a specific NFT token. +- **Off-chain policy example**: Defined by sponsors within the paymaster platform, such as maintaining whitelists for transaction senders or specific interacting contracts. + +Paymasters also enjoy flexibility in their fee collection methods. Charges can be directly deducted from the sponsor's credit card, or sponsors can pre-deposit cryptocurrency to the paymaster platform, from which the balance is then charged. + +## 6 License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-439.md b/BEPs/BEP-439.md new file mode 100644 index 000000000..c24b16102 --- /dev/null +++ b/BEPs/BEP-439.md @@ -0,0 +1,440 @@ +
+  BEP: 439
+  Title: Implement EIP-2537: Precompile for BLS12-381 curve operations
+  Status: Enabled
+  Type: Standards
+  Created: 2024-09-23
+  Description: Adds operation on BLS12-381 curve as a precompile in a set necessary to efficiently perform operations such as BLS signature verification.
+
+ + +# BEP-439: Implement EIP-2537: Precompile for BLS12-381 curve operations + +- [BEP-439: Implement EIP-2537: Precompile for BLS12-381 curve operations](#bep-439-implement-eip-2537-precompile-for-bls12-381-curve-operations) + - [Abstract](#abstract) + - [Motivation](#motivation) + - [Specification](#specification) + - [Constants](#constants) + - [Curve parameters](#curve-parameters) + - [Fields and Groups](#fields-and-groups) + - [Fine points and encoding of base elements](#fine-points-and-encoding-of-base-elements) + - [Field elements encoding:](#field-elements-encoding) + - [Encoding of points in G1/G2:](#encoding-of-points-in-g1g2) + - [Point of infinity encoding:](#point-of-infinity-encoding) + - [Encoding of scalars for multiplication operation:](#encoding-of-scalars-for-multiplication-operation) + - [Behavior on empty inputs:](#behavior-on-empty-inputs) + - [ABI for operations](#abi-for-operations) + - [ABI for G1 addition](#abi-for-g1-addition) + - [ABI for G1 MSM](#abi-for-g1-msm) + - [ABI for G2 addition](#abi-for-g2-addition) + - [ABI for G2 MSM](#abi-for-g2-msm) + - [ABI for pairing check](#abi-for-pairing-check) + - [ABI for mapping Fp element to G1 point](#abi-for-mapping-fp-element-to-g1-point) + - [ABI for mapping Fp2 element to G2 point](#abi-for-mapping-fp2-element-to-g2-point) + - [Gas burning on error](#gas-burning-on-error) + - [DDoS protection](#ddos-protection) + - [Gas schedule](#gas-schedule) + - [G1 addition](#g1-addition) + - [G1 multiplication](#g1-multiplication) + - [G2 addition](#g2-addition) + - [G2 multiplication](#g2-multiplication) + - [G1/G2 MSM](#g1g2-msm) + - [G1 discounts](#g1-discounts) + - [G2 discounts](#g2-discounts) + - [Pairing check operation](#pairing-check-operation) + - [Fp-to-G1 mapping operation](#fp-to-g1-mapping-operation) + - [Fp2-to-G2 mapping operation](#fp2-to-g2-mapping-operation) + - [Gas schedule clarifications for the variable-length input](#gas-schedule-clarifications-for-the-variable-length-input) + - [Gas schedule clarifications for G1/G2 MSM](#gas-schedule-clarifications-for-g1g2-msm) + - [Gas schedule clarifications for pairing](#gas-schedule-clarifications-for-pairing) + - [Rationale](#rationale) + - [MSM as a separate call](#msm-as-a-separate-call) + - [No dedicated MUL call](#no-dedicated-mul-call) + - [Backwards Compatibility](#backwards-compatibility) + - [Subgroup checks](#subgroup-checks) + - [Field to curve mapping](#field-to-curve-mapping) + - [Test Cases](#test-cases) + - [Benchmarking test cases](#benchmarking-test-cases) + - [Reference Implementation](#reference-implementation) + - [Security Considerations](#security-considerations) + - [Copyright](#copyright) + + +## Abstract + +Add functionality to efficiently perform operations over the BLS12-381 curve, including those for BLS signature verification. + +Along with the curve arithmetic, multi-scalar-multiplication operations are included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. + +## Motivation + +The motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. + +## Specification + +### Constants + +| Name | Value | Comment | +|---------------------|-------|--------------------| +| BLS12_G1ADD | 0x0b | precompile address | +| BLS12_G1MSM | 0x0c | precompile address | +| BLS12_G2ADD | 0x0d | precompile address | +| BLS12_G2MSM | 0x0e | precompile address | +| BLS12_PAIRING_CHECK | 0x0f | precompile address | +| BLS12_MAP_FP_TO_G1 | 0x10 | precompile address | +| BLS12_MAP_FP2_TO_G2 | 0x11 | precompile address | + +We introduce *seven* separate precompiles to perform the following operations: + +- BLS12_G1ADD - to perform point addition in G1 (curve over base prime field) with a gas cost of `375` gas +- BLS12_G1MSM - to perform multi-scalar-multiplication (MSM) in G1 (curve over base prime field) with a gas cost formula defined in the corresponding section +- BLS12_G2ADD - to perform point addition in G2 (curve over quadratic extension of the base prime field) with a gas cost of `600` gas +- BLS12_G2MSM - to perform multi-scalar-multiplication (MSM) in G2 (curve over quadratic extension of the base prime field) with a gas cost formula defined in the corresponding section +- BLS12_PAIRING_CHECK - to perform a pairing operations between a set of *pairs* of (G1, G2) points a gas cost formula defined in the corresponding section +- BLS12_MAP_FP_TO_G1 - maps base field element into the G1 point with a gas cost of `5500` gas +- BLS12_MAP_FP2_TO_G2 - maps extension field element into the G2 point with a gas cost of `23800` gas + +A mapping functions specification is included as a separate [document](./assets/bep-439/field_to_curve.md). This mapping function does NOT perform mapping of the byte string into a field element (as it can be implemented in many different ways and can be efficiently performed in EVM), but only does field arithmetic to map a field element into a curve point. Such functionality is required for signature schemes. + +### Curve parameters + +The BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): + +``` +Base field modulus = p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +Fp - finite field of size p +Curve Fp equation: Y^2 = X^3+B (mod p) +B coefficient = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +Main subgroup order = q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +Extension tower +Fp2 construction: +Fp quadratic non-residue = nr2 = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa +Fp2 is Fp[X]/(X^2-nr2) +Curve Fp2 equation: Y^2 = X^3 + B*(v+1) where v is the square root of nr2 +Fp6/Fp12 construction: +Fp2 cubic non-residue c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Fp2 cubic non-residue c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +Twist parameters: +Twist type: M +B coefficient for twist c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +B coefficient for twist c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 +Generators: +H1: +X = 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb +Y = 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1 +H2: +X c0 = 0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8 +X c1 = 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e +Y c0 = 0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801 +Y c1 = 0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be +Pairing parameters: +|x| (miller loop scalar) = 0xd201000000010000 +x is negative = true +``` + +One should note that base field modulus `p` is equal to `3 mod 4` that allows an efficient square root extraction, although as described below gas cost of decompression is larger than gas cost of supplying decompressed point data in `calldata`. + +### Fields and Groups + +Field Fp is defined as the finite field of size `p` with elements represented as integers between 0 and p-1 (both inclusive). + +Field Fp2 is defined as `Fp[X]/(X^2-nr2)` with elements `el = c0 + c1 * v`, where `v` is the formal square root of `nr2` represented as integer pairs `(c0,c1)`. + +Group G1 is defined as a set of Fp pairs (points) `(x,y)` such that either `(x,y)` is `(0,0)` or `x,y` satisfy the curve Fp equation. + +Group G2 is defined as a set of Fp2 pairs (points) `(x',y')` such that either `(x,y)` is `(0,0)` or `(x',y')` satisfy the curve Fp2 equation. + +### Fine points and encoding of base elements + +#### Field elements encoding: + +In order to produce inputs to an operation, one encodes elements of the base field and the extension field. + +A base field element (Fp) is encoded as `64` bytes by performing the BigEndian encoding of the corresponding (unsigned) integer. Due to the size of `p`, the top `16` bytes are always zeroes. `64` bytes are chosen to have `32` byte aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]` with the latter assuming the BigEndian encoding). The corresponding integer **must** be less than field modulus. + +For elements of the quadratic extension field (Fp2), encoding is byte concatenation of individual encoding of the coefficients totaling in `128` bytes for a total encoding. For an Fp2 element in a form `el = c0 + c1 * v` where `v` is the formal square root of a quadratic non-residue and `c0` and `c1` are Fp elements the corresponding byte encoding will be `encode(c0) || encode(c1)` where `||` means byte concatenation (or one can use `bytes32[4]` or `uint256[4]` in terms of Solidity types). + +*Note on the top `16` bytes being zero*: it is required that an encoded element is "in a field", which means strictly `< modulus`. In BigEndian encoding it automatically means that for a modulus that is just `381` bit long the top `16` bytes in `64` bytes encoding are zeroes and this **must** be checked even if only a subslice of input data is used for actual decoding. + +On inputs that can not be a valid encodings of field elements the precompile *must* return an error. + +#### Encoding of points in G1/G2: + +Points of G1 and G2 are encoded as byte concatenation of the respective encodings of the `x` and `y` coordinates. Total encoding length for a G1 point is thus `128` bytes and for a G2 point is `256` bytes. + +#### Point of infinity encoding: + +Also referred to as the "zero point". For BLS12 curves, the point with coordinates `(0, 0)` (zeroes in Fp or Fp2) is *not* on the curve, so a sequence of `128` resp. `256` zero bytes, which naively would decode as `(0, 0)` is instead used by convention to encode the point of infinity of G1 resp. G2. + +#### Encoding of scalars for multiplication operation: + +A scalar for the multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer is **not** required to be less than or equal to main subgroup order `q`. + +#### Behavior on empty inputs: + +Certain operations have variable length input, such as MSMs (takes a list of pairs `(point, scalar)`), or pairing (takes a list of `(G1, G2)` points). While their behavior is well-defined (from an arithmetic perspective) on empty inputs, this EIP discourages such use cases and variable input length operations must return an error if the input is empty. + +### ABI for operations + +#### ABI for G1 addition + +G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). Output is an encoding of addition operation result - single G1 point (`128` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- Input has invalid length + +Note: + +There is no subgroup check for the G1 addition precompile. + +#### ABI for G1 MSM + +G1 MSM call expects `160*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of a G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G1 point (`128` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- An input is on the G1 elliptic curve but not in the correct subgroup +- Input has invalid length + +#### ABI for G2 addition + +G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - a single G2 point (`256` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- Input has invalid length + +Note: + +There is no subgroup check for the G2 addition precompile. + +#### ABI for G2 MSM + +G2 MSM call expects `288*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G2 point (`256` bytes). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- An input is on the G2 elliptic curve but not in the correct subgroup +- Input has invalid length + +#### ABI for pairing check + +Pairing check call expects `384*k` (`k` being a **positive** integer) bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: + +- `128` bytes of G1 point encoding +- `256` bytes of G2 point encoding + +Each point is expected to be in the subgroup of order `q`. + +It checks the equation `e(P1, Q1) * e(P2, Q2) * ... * e(Pk, Qk) == 1` in the pairing target field where `e` is the pairing operation. Output is `32` bytes where first `31` bytes are equal to `0x00` and the last byte is either `0x00` (false) or `0x01` (true). + +Error cases: + +- Invalid coordinate encoding +- An input is neither a point on its respective elliptic curve nor the infinity point +- An input is on its respective elliptic curve but not in the correct subgroup +- Input has invalid length + + +#### ABI for mapping Fp element to G1 point + +Field-to-curve call expects `64` bytes as an input that is interpreted as an element of Fp. Output of this call is `128` bytes and is an encoded G1 point. + +Error cases: + +- Input has invalid length +- Input is not correctly encoded + +#### ABI for mapping Fp2 element to G2 point + +Field-to-curve call expects `128` bytes as an input that is interpreted as an element of Fp2. Output of this call is `256` bytes and is an encoded G2 point. + +Error cases: + +- Input has invalid length +- Input is not correctly encoded + +### Gas burning on error + +Following the current state of all other precompiles, if a call to one of the precompiles in this EIP results in an error then all the gas supplied along with a `CALL` or `STATICCALL` is burned. + +### DDoS protection + +A sane implementation of this EIP *should not* contain potential infinite loops (it is possible and not even hard to implement all the functionality without `while` loops) and the gas schedule accurately reflects the time spent on computations of the corresponding function (precompiles pricing reflects an amount of gas consumed in the worst case where such a case exists). + +### Gas schedule + +Assuming `EcRecover` precompile as a baseline. + +#### G1 addition + +`375` gas + +#### G1 multiplication + +`12000` gas + +#### G2 addition + +`600` gas + +#### G2 multiplication + +`22500` gas + +#### G1/G2 MSM + +MSMs are expected to be performed by Pippenger's algorithm (we can also say that it **must** be performed by Pippenger's algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the MSM with a discount cap `max_discount` for `k > 128`. + +The call cost is calculated as `(k * multiplication_cost * discount) // multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding G1/G2 multiplication cost presented above and `//` is an integer division. + +G1 and G2 are priced separately, each having their own discount table and `max_discount`. + +##### G1 discounts + +Discounts table for G1 MSM as a vector of pairs `[k, discount]`: + +``` +[[1, 1000], [2, 949], [3, 848], [4, 797], [5, 764], [6, 750], [7, 738], [8, 728], [9, 719], [10, 712], [11, 705], [12, 698], [13, 692], [14, 687], [15, 682], [16, 677], [17, 673], [18, 669], [19, 665], [20, 661], [21, 658], [22, 654], [23, 651], [24, 648], [25, 645], [26, 642], [27, 640], [28, 637], [29, 635], [30, 632], [31, 630], [32, 627], [33, 625], [34, 623], [35, 621], [36, 619], [37, 617], [38, 615], [39, 613], [40, 611], [41, 609], [42, 608], [43, 606], [44, 604], [45, 603], [46, 601], [47, 599], [48, 598], [49, 596], [50, 595], [51, 593], [52, 592], [53, 591], [54, 589], [55, 588], [56, 586], [57, 585], [58, 584], [59, 582], [60, 581], [61, 580], [62, 579], [63, 577], [64, 576], [65, 575], [66, 574], [67, 573], [68, 572], [69, 570], [70, 569], [71, 568], [72, 567], [73, 566], [74, 565], [75, 564], [76, 563], [77, 562], [78, 561], [79, 560], [80, 559], [81, 558], [82, 557], [83, 556], [84, 555], [85, 554], [86, 553], [87, 552], [88, 551], [89, 550], [90, 549], [91, 548], [92, 547], [93, 547], [94, 546], [95, 545], [96, 544], [97, 543], [98, 542], [99, 541], [100, 540], [101, 540], [102, 539], [103, 538], [104, 537], [105, 536], [106, 536], [107, 535], [108, 534], [109, 533], [110, 532], [111, 532], [112, 531], [113, 530], [114, 529], [115, 528], [116, 528], [117, 527], [118, 526], [119, 525], [120, 525], [121, 524], [122, 523], [123, 522], [124, 522], [125, 521], [126, 520], [127, 520], [128, 519]] +``` + +`max_discount = 519` + +##### G2 discounts + +Discounts table for G2 MSM as a vector of pairs `[k, discount]`: + +``` +[[1, 1000], [2, 1000], [3, 923], [4, 884], [5, 855], [6, 832], [7, 812], [8, 796], [9, 782], [10, 770], [11, 759], [12, 749], [13, 740], [14, 732], [15, 724], [16, 717], [17, 711], [18, 704], [19, 699], [20, 693], [21, 688], [22, 683], [23, 679], [24, 674], [25, 670], [26, 666], [27, 663], [28, 659], [29, 655], [30, 652], [31, 649], [32, 646], [33, 643], [34, 640], [35, 637], [36, 634], [37, 632], [38, 629], [39, 627], [40, 624], [41, 622], [42, 620], [43, 618], [44, 615], [45, 613], [46, 611], [47, 609], [48, 607], [49, 606], [50, 604], [51, 602], [52, 600], [53, 598], [54, 597], [55, 595], [56, 593], [57, 592], [58, 590], [59, 589], [60, 587], [61, 586], [62, 584], [63, 583], [64, 582], [65, 580], [66, 579], [67, 578], [68, 576], [69, 575], [70, 574], [71, 573], [72, 571], [73, 570], [74, 569], [75, 568], [76, 567], [77, 566], [78, 565], [79, 563], [80, 562], [81, 561], [82, 560], [83, 559], [84, 558], [85, 557], [86, 556], [87, 555], [88, 554], [89, 553], [90, 552], [91, 552], [92, 551], [93, 550], [94, 549], [95, 548], [96, 547], [97, 546], [98, 545], [99, 545], [100, 544], [101, 543], [102, 542], [103, 541], [104, 541], [105, 540], [106, 539], [107, 538], [108, 537], [109, 537], [110, 536], [111, 535], [112, 535], [113, 534], [114, 533], [115, 532], [116, 532], [117, 531], [118, 530], [119, 530], [120, 529], [121, 528], [122, 528], [123, 527], [124, 526], [125, 526], [126, 525], [127, 524], [128, 524]] +``` + +`max_discount = 524` + +#### Pairing check operation + +The cost of the pairing check operation is `32600*k + 37700` where `k` is a number of pairs. + +#### Fp-to-G1 mapping operation + +Fp -> G1 mapping is `5500` gas. + +#### Fp2-to-G2 mapping operation + +Fp2 -> G2 mapping is `23800` gas + +#### Gas schedule clarifications for the variable-length input + +For MSM and pairing functions, the gas cost depends on the input length. The current state of how the gas schedule is implemented in major clients (at the time of writing) is that the gas cost function does *not* perform any validation of the length of the input and never returns an error. So we present a list of rules how the gas cost functions **must** be implemented to ensure consistency between clients and safety. + +##### Gas schedule clarifications for G1/G2 MSM + +Define a constant `LEN_PER_PAIR` that is equal to `160` for G1 operation and to `288` for G2 operation. Define a function `discount(k)` following the rules in the corresponding section, where `k` is number of pairs. + +The following pseudofunction reflects how gas should be calculated: + +``` +k = floor(len(input) / LEN_PER_PAIR); +if k == 0 { + return 0; +} +gas_cost = k * multiplication_cost * discount(k) // multiplier; +return gas_cost; +``` + +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error. Also, the case when `k = 0` is safe: `CALL` or `STATICCALL` cost is non-zero, and the case with formal zero gas cost is already used in `Blake2f` precompile. In any case, the main precompile routine **must** produce an error on such an input because it violated encoding rules. + +##### Gas schedule clarifications for pairing + +Define a constant `LEN_PER_PAIR = 384`; + +The following pseudofunction reflects how gas should be calculated: + +``` +k = floor(len(input) / LEN_PER_PAIR); +gas_cost = 32600*k + 37700; +return gas_cost; +``` + +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error (the precompile routine **must** produce an error on such an input because it violated encoding rules). + +## Rationale + +The motivation section covers a total motivation to have operations over the BLS12-381 curves available. We also extend a rationale for more specific fine points. + +### MSM as a separate call + +Explicit separate MSM operation that allows one to save execution time (so gas) by both the algorithm used (namely Pippenger's algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negligible overhead if e.g. for MSM of `100` points would have to call the multiplication precompile `100` times and addition for `99` times (roughly `138600` would be saved). + +### No dedicated MUL call + +Dedicated MUL precompiles which perform single G1/G2 point by scalar multiplication have exactly the same ABI as MSM with `k == 1`. +MSM has to inspect the input length to reject inputs of invalid lengths. Therefore, it should recognize the case of `k == 1` and invoke the underlying implementation of single point multiplication to avoid the overhead of more complex multi-scalar multiplication algorithm. + +## Backwards Compatibility + +There are no backward compatibility questions. + +### Subgroup checks + +MSMs and pairings MUST perform a subgroup check. +Implementations SHOULD use the optimized subgroup check method detailed in a dedicated [document](./assets/bep-439/fast_subgroup_checks.md). +On any input that fails the subgroup check, the precompile MUST return an error. +As endomorphism acceleration requires input on the correct subgroup, implementers MAY use endomorphism acceleration. + +### Field to curve mapping + +The algorithms and set of parameters for SWU mapping method are provided by a separate [document](./assets/bep-439/field_to_curve.md) + +## Test Cases + +Due to the large test parameters space, we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. The generator for G1 is labeled as `G`, the generator for G2 is labeled as `H`, otherwise we assume random points on a curve in a correct subgroup. `0` means either scalar zero or point at infinity. `1` means either scalar one or multiplicative identity. `group_order` is the main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. + +Required properties for basic ops (add/multiply): + +- Commutativity: `P + Q = Q + P` +- Identity element: `P + 0 = P` +- Additive negation: `P + (-P) = 0` +- Doubling `P + P = 2*P` +- Subgroup check: `group_order * P = 0` +- Trivial multiplication check: `1 * P = P` +- Multiplication by zero: `0 * P = 0` +- Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` + +Required properties for pairing operation: + +- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` +- Non-degeneracy `e(P, Q) != 1` +- `e(P, 0*Q) = e(0*P, Q) = 1` +- `e(P, -Q) = e(-P, Q)` + +Test vectors can be found [in the test vectors files](./assets/bep-439/test-vectors.md). + +### Benchmarking test cases + +A set of test vectors for quick benchmarking on new implementations is located in a separate [file](./assets/bep-439/bench_vectors.md) + +## Reference Implementation + +There are two fully spec compatible implementations on the day of writing: + +- One in Rust language that is based on the [EIP-196](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-196.md) code and integrated with OpenEthereum for this library +- One implemented specifically for Geth as a part of the current codebase + +## Security Considerations + +Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. + +Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-440.md b/BEPs/BEP-440.md new file mode 100644 index 000000000..63770e7cc --- /dev/null +++ b/BEPs/BEP-440.md @@ -0,0 +1,225 @@ +
+  BEP: 440
+  Title: Implement EIP-2935: Serve historical block hashes from state
+  Status: Enabled
+  Type: Standards
+  Created: 2024-09-24
+  Description: Store and serve last 8192 block hashes as storage slots of a system contract to allow for stateless execution
+
+ + +# BEP-440: Implement EIP-2935: Serve historical block hashes from state + +- [BEP-440: Implement EIP-2935: Serve historical block hashes from state](#bep-440-implement-eip-2935-serve-historical-block-hashes-from-state) + - [Abstract](#abstract) + - [Motivation](#motivation) + - [Specification](#specification) + - [Block processing](#block-processing) + - [EVM Changes](#evm-changes) + - [Block hash history contract](#block-hash-history-contract) + - [`get`](#get) + - [`set`](#set) + - [Bytecode](#bytecode) + - [Deployment](#deployment) + - [EIP-161 handling](#eip-161-handling) + - [Gas costs](#gas-costs) + - [Rationale](#rationale) + - [Inserting the parent block hash](#inserting-the-parent-block-hash) + - [Size of ring buffers](#size-of-ring-buffers) + - [Backwards Compatibility](#backwards-compatibility) + - [Test Cases](#test-cases) + - [Security Considerations](#security-considerations) + - [Copyright](#copyright) + + +## Abstract + +Store last `HISTORY_SERVE_WINDOW` historical block hashes in the storage of a system contract as part of the block processing logic. Furthermore this EIP has no impact on `BLOCKHASH` resolution mechanism (and hence its range/costs etc). + +## Motivation + +EVM implicitly assumes the client has the recent block (hashes) at hand. This assumption is not future-proof given the prospect of stateless clients. Including the block hashes in the state will allow bundling these hashes in the witness provided to a stateless client. This is already possible in the MPT and will become more efficient post-Verkle. + +Extending the range of blocks which `BLOCKHASH` can serve (`BLOCKHASH_SERVE_WINDOW`) would have been a semantics change. Using extending that via this contract storage would allow a soft-transition. Rollups can benefit from the longer history window through directly querying this contract. + +A side benefit of this approach could be that it allows building/validating proofs related to last `HISTORY_SERVE_WINDOW` ancestors directly against the current state. + +## Specification + +| Parameter | Value | +| - | - | +| `BLOCKHASH_SERVE_WINDOW` | `256` | +| `HISTORY_SERVE_WINDOW` | `8191` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `HISTORY_STORAGE_ADDRESS` | `0x0000F90827F1C53a10cb7A02335B175320002935` | + +This EIP specifies for storing last `HISTORY_SERVE_WINDOW` block hashes in a ring buffer storage of `HISTORY_SERVE_WINDOW` length. Note that `HISTORY_SERVE_WINDOW` > `BLOCKHASH_SERVE_WINDOW` (which remains unchanged). + +### Block processing + +At the start of processing any block where this EIP is active (ie. before processing any transactions), call to `HISTORY_STORAGE_ADDRESS` as `SYSTEM_ADDRESS` with the 32-byte input of `block.parent.hash`, a gas limit of `30_000_000`, and `0` value. This will trigger the `set()` routine of the history contract. This is a system operation following the same convention as [EIP-4788](./eip-4788.md) and therefore: + +* the call must execute to completion +* the call does not count against the block's gas limit +* the call does not follow the [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md) burn semantics - no value should be transferred as part of the call +* if no code exists at `HISTORY_STORAGE_ADDRESS`, the call must fail silently + +Note: Alternatively clients can choose to directly write to the storage of the contract but EVM calling the contract remains preferred. Refer to the rationale for more info. + +Note that, it will take `HISTORY_SERVE_WINDOW` blocks after the EIP's activation to completely fill up the ring buffer. The contract will only contain the parent hash of the fork block and no hashes prior to that. + + +### EVM Changes + +The `BLOCKHASH` opcode semantics remains the same as before. + +### Block hash history contract + +The history contract has two operations: `get` and `set`. The `set` operation is invoked only when the `caller` is equal to the `SYSTEM_ADDRESS` as per [EIP-4788](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4788.md). Otherwise the `get` operation is performed. + +#### `get` + +It is used from the EVM for looking up block hashes. + +* Callers provide the block number they are querying in a big-endian encoding. +* If calldata is not 32 bytes, revert. +* For any request outside the range of [block.number-`HISTORY_SERVE_WINDOW`, block.number-1], revert. + +#### `set` + +* Caller provides `block.parent.hash` as calldata to the contract. +* Set the storage value at `block.number-1 % HISTORY_SERVE_WINDOW` to be `calldata[0:32]`. + +#### Bytecode + +Exact evm assembly that can be used for the history contract: + +``` +// https://github.com/lightclient/sys-asm/blob/f1c13e285b6aeef2b19793995e00861bf0f32c9a/src/execution_hash/main.eas +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x46 +jumpi +push1 0x20 +calldatasize +sub +push1 0x42 +jumpi +push0 +calldataload +push1 0x01 +number +sub +dup2 +gt +push1 0x42 +jumpi +push2 0x1fff +dup2 +number +sub +gt +push1 0x42 +jumpi +push2 0x1fff +swap1 +mod +sload +push0 +mstore +push1 0x20 +push0 +return +jumpdest +push0 +push0 +revert +jumpdest +push0 +calldataload +push2 0x1fff +push1 0x01 +number +sub +mod +sstore +stop +``` + + +#### Deployment + +The above bytecode will be deployed at the HISTORY_STORAGE_ADDRESS once the fork is enabled, in a manner similar to the deployment of system contracts. After deployment, the nonce value will be set to 1 immediately. + + +Some activation scenarios: + + * For the fork to be activated at genesis, no history is written to the genesis state, and at the start of block `1`, genesis hash will be written as a normal operation to slot `0`. + * for activation at block `1`, only genesis hash will be written at slot `0`. + * for activation at block `32`, block `31`'s hash will be written to slot `31`. Every other slot will be `0`. + +### [EIP-161](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-161.md) handling + +The bytecode above will be deployed à la [EIP-4788](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4788.md). As such the account at `HISTORY_STORAGE_ADDRESS` will have code and a nonce of 1, and will be exempt from EIP-161 cleanup. + +### Gas costs + +The system update at the beginning of the block, i.e. `process_block_hash_history` (or via system call to the contract with `SYSTEM_ADDRESS` caller), will not warm the `HISTORY_STORAGE_ADDRESS` account or its storage slots as per [EIP-2929](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2929.md) rules. As such the first call to the contract will pay for warming up the account and storage slots it accesses. To clarify further any contract call to the `HISTORY_STORAGE_ADDRESS` will follow normal EVM execution semantics. + +Since `BLOCKHASH` semantics doesn't change, this EIP has no impact on `BLOCKHASH` mechanism and costs. + +## Rationale + +Very similar ideas were proposed before. This EIP is a simplification, removing two sources of needless complexity: + +1. Having a tree-like structure with multiple layers as opposed to a single list +2. Writing the EIP in EVM code +3. Serial unbounded storage of hashes for a deep access to the history + +However after weighing pros and cons, we decided to go with just a limited ring buffer to only serve the requisite `HISTORY_SERVE_WINDOW` as [EIP-4788](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4788.md) and beacon state accumulators allow (albeit a bit more complex) proof against any ancestor since merge. + +Second concern was how to best transition the BLOCKHASH resolution logic post fork by: + +1. Either waiting for `HISTORY_SERVE_WINDOW` blocks for the entire relevant history to persist +2. Storing of all last `HISTORY_SERVE_WINDOW` block hashes on the fork block. + +We choose to go with the former. It simplifies the logic greatly. It will take roughly a day to bootstrap the contract. Given that this is a new way of accessing history and no contract depends on it, it is deemed a favorable tradeoff. + +### Inserting the parent block hash + +Clients have generally two options for inserting the parent block hash into state: + +1. Performing a system call to `HISTORY_STORAGE_ADDRESS` and letting that handle the storing in state. +2. Avoid EVM processing and directly write to the state trie. + +The latter option is as follows: + +```python +def process_block_hash_history(block: Block, state: State): + if block.timestamp >= FORK_TIMESTAMP: // FORK_TIMESTAMP should be definied outside of the EIP + state.insert_slot(HISTORY_STORAGE_ADDRESS, (block.number-1) % HISTORY_SERVE_WINDOW , block.parent.hash) +``` + +The first option is recommended until the Verkle fork, to stay consistent with [EIP-4788](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4788.md) and to issues for misconfigured networks where this EIP is activated but history contract hasn't been deployed. The recommendation may be reconsidered at the Verkle fork if filtering the system contract code chunks is deemed too complex. + +### Size of ring buffers +The ring buffer data structure is sized to hold 8191 hashes. In other system contracts a prime ring buffer size is chosen in because using a prime as the modulus ensures that no value is overwritten until the entire ring buffer has been saturated and thereafter, each value will be updated once per iteration, regardless of if some slot are missing or the slot time changes. However, in this EIP the block number is the value in the modulo operation and it only ever increases by 1 each iteration. Which means we can be confident that the ring buffer will always remain saturated. + +For consistency with other system contracts, we have decided to retain the buffer size of 8191. This also gives users plenty of time to make a transaction with a verification against a specific hash and get the transaction included on-chain. + +## Backwards Compatibility + +This EIP introduces backwards incompatible changes to the block validation rule set. But neither of these changes break anything related to current user activity and experience. + +## Test Cases + +TBD + +## Security Considerations + +Having contracts (system or otherwise) with hot update paths (branches) poses a risk of "branch" poisioning attacks where attacker could sprinkle trivial amounts of eth around these hot paths (branches). But it has been deemed that cost of attack would escalate significantly to cause any meaningful slow down of state root updates. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-441.md b/BEPs/BEP-441.md new file mode 100644 index 000000000..a609ffd9c --- /dev/null +++ b/BEPs/BEP-441.md @@ -0,0 +1,298 @@ +
+  BEP: 441
+  Title: Implement EIP-7702: Set EOA account code
+  Status: Enabled
+  Type: Standards
+  Created: 2024-09-25
+  Description: Add a new tx type that permanently sets the code for an EOA
+
+ + +# BEP-441: Implement EIP-7702: Set EOA account code + +- [BEP-441: Implement EIP-7702: Set EOA account code](#bep-441-implement-eip-7702-set-eoa-account-code) + - [Abstract](#abstract) + - [Motivation](#motivation) + - [Specification](#specification) + - [Parameters](#parameters) + - [Set Code Transaction](#set-code-transaction) + - [Behavior](#behavior) + - [Delegation Designation](#delegation-designation) + - [Gas Costs](#gas-costs) + - [Transaction Origination](#transaction-origination) + - [Rationale](#rationale) + - [Cost of Delegation](#cost-of-delegation) + - [No initcode](#no-initcode) + - [Creation by template](#creation-by-template) + - [Lack of instruction prohibition](#lack-of-instruction-prohibition) + - [Signature structure](#signature-structure) + - [Code pointer](#code-pointer) + - [In-protocol revocation](#in-protocol-revocation) + - [Self-sponsoring: allowing `tx.origin` to set code](#self-sponsoring-allowing-txorigin-to-set-code) + - [Forward-compatibility with future account abstraction](#forward-compatibility-with-future-account-abstraction) + - [Clearing Delegation Designations](#clearing-delegation-designations) + - [Delegation of code execution only](#delegation-of-code-execution-only) + - [Backwards Compatibility](#backwards-compatibility) + - [Security Considerations](#security-considerations) + - [Secure delegation](#secure-delegation) + - [Setting code as `tx.origin`](#setting-code-as-txorigin) + - [Sponsored transaction relayers](#sponsored-transaction-relayers) + - [Front running initialization](#front-running-initialization) + - [Transaction propagation](#transaction-propagation) + - [Storage management](#storage-management) + - [Copyright](#copyright) + + +## Abstract + +Add a new transaction type that adds a list of `[chain_id, address, nonce, y_parity, r, s]` authorization tuples. For each tuple, write a delegation designator `(0xef0100 || address)` to the signing account's code. All code executing operations must load the code pointed to by the designator. + +## Motivation + +There is a lot of interest in adding short-term functionality improvements to EOAs, increasing the usability of applications and in some cases allowing improved security. Three particular applications include: + +* **Batching**: allowing multiple operations from the same user in one atomic transaction. One common example is an [ERC-20](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md) approval followed by spending that approval, a common workflow in DEXes that requires two transactions today. Advanced use cases of batching occasionally involve dependencies: the output of the first operation is part of the input to the second operation. +* **Sponsorship**: account X pays for a transaction on behalf of account Y. Account X could be paid in some other ERC-20 for this service, or it could be an application operator including the transactions of its users for free. +* **Privilege de-escalation**: users can sign sub-keys and give them specific permissions that are much weaker than global access to the account. For example, you could imagine a permission to spend ERC-20 tokens but not ETH, or to spend up to 1% of the total balance per day, or to interact only with a specific application. + +## Specification + +### Parameters + +| Parameter | Value | +| ------------------------ | ------- | +| `SET_CODE_TX_TYPE` | `0x04` | +| `MAGIC` | `0x05` | +| `PER_AUTH_BASE_COST` | `12500` | +| `PER_EMPTY_ACCOUNT_COST` | `25000` | + +### Set Code Transaction + +We introduce a new [EIP-2718](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2718.md) transaction, "set code transaction", where the `TransactionType` is `SET_CODE_TX_TYPE` and the `TransactionPayload` is the RLP serialization of the following: + +``` +rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, value, data, access_list, authorization_list, signature_y_parity, signature_r, signature_s]) + +authorization_list = [[chain_id, address, nonce, y_parity, r, s], ...] +``` + +The fields `chain_id`, `nonce`, `max_priority_fee_per_gas`, `max_fee_per_gas`, `gas_limit`, `destination`, `value`, `data`, and `access_list` of the outer transaction follow the same semantics as [EIP-4844](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md). *Note, this means a null destination is not valid.* + +The `authorization_list` is a list of tuples that store the address to code which the signer desires to execute in the context of their EOA. The transaction is considered invalid if the length of `authorization_list` is zero. + +The transaction is also considered invalid when any field in an authorization +tuple cannot fit within the following bounds: + +```python +assert auth.chain_id < 2**256 +assert auth.nonce < 2**64 +assert len(auth.address) == 20 +assert auth.y_parity < 2**8 +assert auth.r < 2**256 +assert auth.s < 2**256 +``` + +The [EIP-2718](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + +#### Behavior + +At the start of executing the transaction, after incrementing the sender's nonce, for each `[chain_id, address, nonce, y_parity, r, s]` tuple do the following: + +1. Verify the chain id is either 0 or the chain's current ID. +2. Verify the `nonce` is less than `2**64 - 1`. +3. `authority = ecrecover(keccak(MAGIC || rlp([chain_id, address, nonce])), y_parity, r, s)` + * `s` value must be less than or equal to `secp256k1n/2`, as specified in [EIP-2](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md). + * `authority` is not present in the block list defined in the Nano hard fork. +4. Add `authority` to `accessed_addresses` (as defined in [EIP-2929](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2929.md).) +5. Verify the code of `authority` is either empty or already delegated. +6. Verify the nonce of `authority` is equal to `nonce`. In case `authority` does not exist in the trie, verify that `nonce` is equal to `0`. +7. Add `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` gas to the global refund counter if `authority` exists in the trie. +8. Set the code of `authority` to be `0xef0100 || address`. This is a delegation designation. + * As a special case, if `address` is `0x0000000000000000000000000000000000000000` do not write the designation. Clear the account's code and reset the account's code hash to the empty hash `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`. +9. Increase the nonce of `authority` by one. + +If any of the above steps fail, immediately stop processing that tuple and continue to the next tuple in the list. It will in the case of multiple tuples for the same authority, set the code using the address in the last valid occurrence. + +Note that the signer of an authorization tuple may be different than `tx.origin` of the transaction. + +If transaction execution results in failure (any exceptional condition or code reverting), setting delegation designations is *not* rolled back. + +##### Delegation Designation + +The delegation designation uses the banned opcode `0xef` from [EIP-3541](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3541.md) to designate the code has a special purpose. This designator requires all code executing operations to follow the address pointer to get the account's executable code, and requires all other code reading operations to act only on the delegation designator (`0xef0100 || address`). The following reading instructions are impacted: `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, and the following executing instructions are impacted: `CALL`, `CALLCODE`, `STATICCALL`, `DELEGATECALL`, as well as transactions with `destination` targeting the code with delegation designation. + +For example, `EXTCODESIZE` would return `23` (the size of `0xef0100 || address`), `EXTCODEHASH` would return `keccak256(0xef0100 || address)`, and `CALL` would load the code from `address` and execute it in the context of `authority`. + +In case a delegation designator points to a precompile address, retrieved code is considered empty and `CALL`, `CALLCODE`, `STATICCALL`, `DELEGATECALL` instructions targeting this account will execute empty code, i.e. succeed with no execution given enough gas. + +In case a delegation designator points to another designator, creating a potential chain or loop of designators, clients must retrieve only the first code and then stop following the designator chain. + +#### Gas Costs + +The intrinsic cost of the new transaction is inherited from [EIP-2930](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2930.md), specifically `21000 + 16 * non-zero calldata bytes + 4 * zero calldata bytes + 1900 * access list storage key count + 2400 * access list address count`. Additionally, we add a cost of `PER_EMPTY_ACCOUNT_COST * authorization list length`. + +The transaction sender will pay for all authorization tuples, regardless of validity or duplication. + +If a code reading instruction accesses a cold account during the resolution of delegated code, add an additional [EIP-2929](eip-2929.md) `COLD_ACCOUNT_READ_COST` cost of `2600` gas to the normal cost and add the account to `accessed_addresses`. Otherwise, assess a `WARM_STORAGE_READ_COST` cost of `100`. + +#### Transaction Origination + +Modify the restriction put in place by [EIP-3607](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3607.md) to allow EOAs whose code is a valid delegation designation, i.e., `0xef0100 || address`, to continue to originate transactions. Accounts with any other code values may not originate transactions. + +Additionally, if a transaction's `destination` has a delegation designation, add the target of the delegation to `accessed_addresses`. + +## Rationale + +### Cost of Delegation + +The `PER_AUTH_BASE_COST` is the cost to process the authorization tuple and set the delegation destination. We are able to compute a fair cost for this operation by reviewing its impact on the system: + +* ferry 101 bytes of calldata = `101 * non-zero cost (16) = 1616` +* recovering the `authority` address = `3000` +* reading the nonce and code of `authority` = `2600` +* storing values in already warm account = `200` +* cost to deploy code = `200 * 23 = 4600` + +The impact-based assessment leaves us with `12016` gas for the operation. We round up to `12500` to account for miscellaneous costs associated with shuttling data around the state transition. + +### No initcode + +Running initcode is not desirable for many reasons. The chief concern is it's unnatural. Initcode is intended to initialize and deploy contracts. With this EIP, it will take on a new role of determining whether it is appropriate to deploy code to the EOA. Suppose a user only wants code deployed to their account if they also have an operation bundled with the general transaction calldata. This gives EOAs a unique power to control when and what code executes in their account. Although [EIP-7702](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7702.md) as written still allows this to a degree, the lack of programmability in the decision will force wallets to not sign many authorization tuples and instead focus on signing only a tuple pointing to a configurable proxy. This affords EOAs a similar experience to smart contract wallets. + +Additionally, initcode in a transaction tends to be propagated inside the transaction. That means it would need to be included in the authorization tuple and signed over. The minimum initcode would be around 15 bytes, and that would simply copy the contract code from an external address. The total cost would be `16 * 15 = 240` calldata cost, plus the [EIP-3860](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3860.md) cost of `2 * 15 = 30`, plus the runtime costs of around `150`. So nearly `500` additional gas would be spent simply preparing the account; and even more likely, 1200+ gas if not copying from an external account. + +### Creation by template + +Initcode or not, there is a question of how users should specify the code they intend to run in their account. The two main options are to specify the bytecode directly in the transaction or to specify a pointer to the code. The simplest pointer would just be the address of some code deployed on-chain. + +The cost analysis makes the answer clear. The smallest proxy would be around 50 bytes, and an address is 20 bytes. The 30 byte difference provides no useful additional functionality and will be inefficiently replicated billions of times on the chain. + +Furthermore, specifying code directly would again make it possible for EOAs to have a new, unique ability to execute arbitrary code specified in the transaction calldata. + +### Lack of instruction prohibition + +Consistency is a valuable property in the EVM, both from an implementation perspective and a user understanding perspective. Despite considering bans on several families of instructions in the context of EOAs, the authors feel there is not a compelling reason to do so. It will force smart contract wallets and EOA smart contract wallets to proceed down distinct paths of contract development. + +The main families of instructions where a ban was considered were storage related and contract creation related. The decision to not ban storage instructions hinged mostly on their importance to smart contract wallets. Although it's possible to have an external storage contract that the smart contract wallet calls into, it is unnecessarily inefficient. In the future, new state schemes may even allow substantially cheaper access to certain storage slots. This is something smart contract wallets will very much want to take advantage of that a storage contract wouldn't support. + +Creation instructions were considered for a ban on other similar EIPs, however because this EIP allows EOAs to spend value intra-transaction, the concern with bumping the nonce intra-transaction and invalidating pending transactions is not significant. + +### Signature structure + +The signature scheme in this EIP supports flexible design patterns, allowing for both full delegation to `address` and more protected delegations to `address`. + +#### Code pointer + +One consideration when signing a code pointer is what code might that address point to on another chain. For some use cases, it may not be desirable to expend the effort verifying the deployment was deterministic. In such situations, the chain ID can be set to reduce the scope of the authorization. For other situations where universal deployment is preferred, e.g., delegating to a wallet proxy, it's possible to set chain ID to 0 for validity on all EIP-7702 chains. Wallet maintainers will be able to hard code a single EIP-7702 authorization message into their wallet so that cross-chain code malleability never becomes a concern. + +An alternative to adding chain ID could be to sign over the code the address points to. This seems to have the benefit of both minimizing the on-chain size of auth tuples while retaining specificity of the actual code running in the account. One unfortunate issue of this format, though, is that it imposes a database lookup to determine the signer of each auth tuple. This imposition itself seems to create enough complexity in transaction propagation that it is decided to avoid and simply sign over the address directly. + +#### In-protocol revocation + +Unlike previous versions of this EIP and similar EIPs, the delegation designation can be revoked at any time by signing and sending an EIP-7702 authorization to a new target with the account's current nonce. Without such action, a delegation will remain valid in perpetuity. + +### Self-sponsoring: allowing `tx.origin` to set code + +Allowing `tx.origin` to set code enables simple transaction batching, where the sender of the outer transaction would be the signing account. The ERC-20 approve-then-transfer pattern, which currently requires two separate transactions, could be completed in a single transaction with this proposal. + +Once code exists in the EOA, it's possible for self-sponsored EIP-7702 transactions to have `msg.sender == tx.origin` anytime the code in the EOA dispatches a call. Without EIP-7702, this situation can only ever arise in the topmost execution layer of a transaction. Therefore, this EIP breaks that invariant and so it affects smart contracts containing `require(msg.sender == tx.origin)` checks. This check is used for at least three purposes: + + 1. Ensuring that `msg.sender` is an EOA (given that `tx.origin` always has to be an EOA). This invariant does not depend on the execution layer depth and, therefore, is not affected. + 2. Protecting against atomic sandwich attacks like flash loans, which rely on the ability to modify state before and after the execution of the target contract as part of the same atomic transaction. This protection would be broken by this EIP. However, relying on `tx.origin` in this way is considered bad practice, and can already be circumvented by miners conditionally including transactions in a block. + 3. Preventing reentrancy. + +Examples of (1) and (2) can be found in contracts deployed on Ethereum mainnet, with (1) being more common (and unaffected by this proposal). On the other hand, use case (3) is more severely affected by this proposal, but the authors of this EIP did not find any examples of this form of reentrancy protection, though the search was non-exhaustive. + +This distribution of occurrences—many (1), some (2), and no (3)—is exactly what the authors of this EIP expect because: + + * Determining if `msg.sender` is an EOA without `tx.origin` is difficult (if not impossible). + * The only execution context which is safe from atomic sandwich attacks is the topmost context, and `tx.origin == msg.sender` is the only way to detect that context. + * In contrast, there are many direct and flexible ways of preventing reentrancy (e.g., using a transient storage variable). Since `msg.sender == tx.origin` is only true in the topmost context, it would make an obscure tool for preventing reentrancy, rather than other more common approaches. + +There are other approaches to mitigate this restriction which do not break the invariant: + + * Set `tx.origin` to a constant `ENTRY_POINT` address when using the `CALL*` instruction in the context of an EOA. + * Set `tx.origin` to a special address derived from the sender or signer addresses. + * Disallow `tx.origin` from setting code. This would make the simple batching use cases impossible, but could be relaxed in the future. + +### Forward-compatibility with future account abstraction + +This EIP is designed to be very forward-compatible with endgame account abstraction, without over-enshrining any fine-grained details of [ERC-4337](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4337.md) or RIP-7560. + +Specifically: + +* The `address` that users sign could literally point to existing ERC-4337 wallet code. +* The "code pathways" that are used are code pathways that would, in many cases (though perhaps not all), continue to "make sense" in a pure-smart-contract-wallet world. +* Hence, it avoids the problem of "creating two separate code ecosystems" because, to a large extent, they would be the same ecosystem. There would be some workflows that require kludges under this solution that would be better done in some different "more native" under "endgame AA", but this is relatively a small subset. +* It does not require adding any opcodes, that would become dangling and useless in a post-EOA world. +* It allows EOAs to masquerade as contracts to be included in ERC-4337 bundles, in a way that's compatible with the existing `EntryPoint`. + +### Clearing Delegation Designations + +A general design goal of state transition changes is to minimize the number of special cases an EIP has. In early iterations, this EIP resisted a special case for clearing an account's delegation designation. + +For most intents and purposes, an account delegated to `0x0` is indistinguishable from a true EOA. However, one particular unfortunate case is unavoidable. Even if a user has a zeroed out delegation designation, most operations that interact with that account will encounter an additional `COLD_ACCOUNT_READ_COST` upon the first touch. + +This is not ideal and may be a significant enough concern to impact the overall adoption of the EIP. For these reasons, we have opted to include a mechanism which allow users to restore their EOA to its original pureness. + +### Delegation of code execution only + +Other code retrieving operations like `EXTCODEHASH` do not automatically follow delegations, they operate on the delegation designator itself. If instead delegations were followed, an account would be able to temporarily masquerade as having a particular codehash, which would break contracts that rely on codehashes as an indicator of possible account behavior. A change of behavior in a contract is currently only possible if its code explicitly allows it (in particular via `DELEGATECALL`), and a change of codehash is only possible in the presence of `SELFDESTRUCT` (and as of Cancun only in the same transaction as contract creation), so choosing to follow delegations in `EXTCODE*` opcodes would have created a new type of account that broke prior assumptions. + +## Backwards Compatibility + +This EIP breaks the invariant that an account balance can only decrease as a result of transactions originating from that account. It also breaks the invariant that an EOA nonce may not increase after transaction execution has begun. These breakages have consequences for mempool design, and for other EIPs such as inclusion lists. However, because the accounts are listed statically in the outer transaction, it is possible to modify transaction propagation rules so that conflicting transactions are not forwarded. + +## Security Considerations + +### Secure delegation + +The following is a non-exhaustive list of checks/pitfalls/conditions that delegate contracts *should* be wary of and require a signature over from the account's authority: + + * Replay protection (e.g., a nonce) should be implemented by the delegate and signed over. Without it, a malicious actor can reuse a signature, repeating its effects. + * `value` -- without it, a malicious sponsor could cause unexpected effects in the callee. + * `gas` -- without it, a malicious sponsor could cause the callee to run out of gas and fail, griefing the sponsee. + * `target` / `calldata` -- without them, a malicious actor may call arbitrary functions in arbitrary contracts. + +A poorly implemented delegate can *allow a malicious actor to take near complete control over a signer's EOA*. + +### Setting code as `tx.origin` + +Allowing the sender of an EIP-7702 to also set code has the possibility to: + + * Break atomic sandwich protections which rely on `tx.origin`; + * Break reentrancy guards of the style `require(tx.origin == msg.sender)`. + +The authors of this EIP believe the risks of allowing this are acceptable for the reasons outlined in the Rationale section. + +### Sponsored transaction relayers + +It is possible for the `authorized` account to cause sponsored transaction relayers to spend gas without being reimbursed by either invalidating the authorization (i.e., increasing the account's nonce) or by sweeping the relevant assets out of the account. Relayers should be designed with these cases in mind, possibly by requiring a bond to be deposited or by implementing a reputation system. + +### Front running initialization + +Smart contract wallet developers must consider the implications of setting code in an account without execution. Contracts are normally deployed by executing initcode to determine the exact code to be placed in the account. This gives developers the opportunity to initialize storage slots at the same time. The initial values of the account cannot be replaced by an observer, because they are either signed over by an EOA in the case of a creation transaction or they are committed to by computing the contract's address deterministically from the hash of the initcode. + +This EIP does not provide developers the opportunity to run initcode and set storage slots during delegation. To secure the account from an observer front-running the initialization of the delegation with an account they control, smart contract wallet developers must verify the initial calldata to the account for setup purposes be signed by the EOA's key using ecrecover. This ensures the account can only be initialized with desirable values. + +### Transaction propagation + +Allowing EOAs to behave as smart contracts via the delegation designation poses some challenges for transaction propagation. Traditionally, EOAs have only be able to send value via a transaction. This invariant allows nodes to statically determine the validity of transactions for that account. In other words, a single transaction has only been able to invalidate transactions pending from the senders account. + +With this EIP, it becomes possible to cause transactions from other accounts to become stale. This is due to the fact that once an EOA has delegated to code, that code can be called by anyone at any point in a transaction. It becomes impossible to know if the balance of the account has been sweeped in a static manner. + +While there are a few mitigations for this, the authors recommend that clients do not accept more than one pending transaction for any EOA with a non-zero delegation designator. This minimizes the number of transactions that can be invalidated by a single transaction. Another alternative would be to expand the EIP-7702 transaction with a list of accounts the caller wishes to "hydrate" during the transaction. Those accounts behave as the delegated code *only* for EIP-7702 transactions which include them in such a list, thus returning to clients the ability to statically analyze and reason about pending transactions. + +A related issue is that an EOA's nonce maybe incremented more than once per transaction. Because clients already need to be robust in a worse scenario (described above), it isn't a major security concern. However, clients should be aware this behavior is possible and design their transaction propagation accordingly. + +### Storage management + +Changing an account's delegation is a security-critical operation that should not be done lightly, especially if the newly delegated code is not purposely designed and tested as an upgrade to the old one. + +In particular, in order to ensure a safe migration of an account from one delegate contract to another, it's important for these contracts to use storage in a way that avoids accidental collisions among them. For example, using [ERC-7201](https://github.com/ethereum/ercs/blob/master/ERCS/erc-7201.md) a contract may root its storage layout at a slot dependent on a unique identifier. To simplify this, smart contract languages may provide a way of re-rooting the entire storage layout of existing contract source code. + +If all contracts previously delegated to by the account used the approach described above, a migration should not cause any issues. However, if there is any doubt, it is recommended to first clear all account storage, an operation that is not natively offered by the protocol but that a special-purpose delegate contract can be designed to implement. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-466.md b/BEPs/BEP-466.md new file mode 100644 index 000000000..9d5b17572 --- /dev/null +++ b/BEPs/BEP-466.md @@ -0,0 +1,39 @@ +
+  BEP: 466
+  Title: Make the block header format compatible with EIP-7685
+  Status: Enabled
+  Type: Standards
+  Created: 2024-11-25
+
+ +# BEP-466: Make the block header format compatible with EIP-7685 + +- [BEP-466: Make the block header format compatible with EIP-7685](#bep-466-make-the-block-header-format-compatible-with-eip-7685) + - [Abstract](#abstract) + - [Motivation](#motivation) + - [Specification](#specification) + - [Block Header](#block-header) + - [Copyright](#copyright) + + +## Abstract + +[EIP-7685](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7685.md) adds `requests_hash` to the block header. To achieve compatibility, this element must be defined in BNB Smart Chain (BSC). + +## Motivation + +The goal is to make the block header format compatible with EIP-7685. This allows for shared codebases and APIs between implementations, promoting consistency and interoperability. + +## Specification + +### Block Header + +In line with EIP-7685, the header is extended with a new 32-byte commitment value, `requests_hash`. On BSC: + +1. Collecting `requests` or validating their correspondence with `requests_hash` is not required. +2. After the Prague hard fork, `requests_hash` must not be nil to ensure compatibility with EIP-7685. +3. Include `requests_hash` in the computation when calculating the header signature. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-496.md b/BEPs/BEP-496.md new file mode 100644 index 000000000..cd1147571 --- /dev/null +++ b/BEPs/BEP-496.md @@ -0,0 +1,112 @@ +
+  BEP: 496
+  Title: Implement EIP-7623: Increase calldata cost
+  Status: Enabled
+  Type: Standards
+  Created: 2024-12-18
+  Description: Increase calldata cost to reduce maximum block size.
+
+ + +# BEP-496: Implement EIP-7623: Increase calldata cost + +- [BEP-496: Implement EIP-7623: Increase calldata cost](#bep-496-implement-eip-7623-increase-calldata-cost) + - [Abstract](#abstract) + - [Motivation](#motivation) + - [Specification](#specification) + - [Rationale](#rationale) + - [Backwards Compatibility](#backwards-compatibility) + - [Security Considerations](#security-considerations) + - [Copyright](#copyright) + +## Abstract + +The current calldata pricing permits EL payloads of up to 7.15 MB, while the average size is much smaller at around 100 KB. +This EIP proposes adjusting the calldata cost to reduce the maximum possible block size and its variance without negatively impacting regular users. +This is achieved by increasing calldata costs for transactions that predominantly post data. + +## Motivation + +The block gas limit has not been increased since [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559), while the average size of blocks has continuously increased due to the growing number of rollups posting data to Ethereum. Moreover, calldata costs have remained unchanged since [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028). +[EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) introduces blobs as a preferred method for data availability (DA). +This transition demands a reevaluation of calldata pricing, especially in order to address the disparity between average and maximum block sizes. +By introducing a floor cost dependent on the ratio of gas spent on EVM operations to calldata, this proposal aims to reduce the maximum block size to make room for additional blobs or potential block gas limit increases. + +## Specification + +| Parameter | Value | +|------------------------------|-------| +| `STANDARD_TOKEN_COST` | `4` | +| `TOTAL_COST_FLOOR_PER_TOKEN` | `10` | + + +Let `tokens_in_calldata = zero_bytes_in_calldata + nonzero_bytes_in_calldata * 4`. + +Let `isContractCreation` be a boolean indicating the respective event. + +Let `execution_gas_used` be the gas used for EVM execution with the gas refund subtracted. + +The current formula for determining the total gas used per transaction (`tx.gasUsed`) is equivalent to: + +```python +tx.gasUsed = ( + 21000 + + STANDARD_TOKEN_COST * tokens_in_calldata + + execution_gas_used + + isContractCreation * (32000 + INITCODE_WORD_COST * words(calldata)) +) +``` + +The formula for determining the gas used per transaction changes to: + +```python +tx.gasUsed = ( + 21000 + + + max( + STANDARD_TOKEN_COST * tokens_in_calldata + + execution_gas_used + + isContractCreation * (32000 + INITCODE_WORD_COST * words(calldata)), + TOTAL_COST_FLOOR_PER_TOKEN * tokens_in_calldata + ) +) +``` + +Any transaction with a gas limit below `21000 + TOTAL_COST_FLOOR_PER_TOKEN * tokens_in_calldata` or below its intrinsic gas cost (take the maximum of these two calculations) is considered invalid. This limitation exists because transactions must cover the floor price of their calldata without relying on the execution of the transaction. There are valid cases where `gasUsed` will be below this floor price, but the floor price needs to be reserved in the transaction gas limit. + +## Rationale + +The current maximum EL payload size is approximately 1.79 MB (`30_000_000/16`). It is possible to create payloads filled with zero bytes that expand to 7.15 MB. However, since blocks are typically compressed with Snappy at the P2P layer, zero-byte-heavy EL payloads generally compress to under 1.79 MB. The implementation of [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) increased the maximum possible compressed block size to approximately 2.54 MB. + +This proposal aims to increase the cost of calldata to 10/40 gas for transactions that do not exceed a certain threshold of gas spent on EVM operations relative to gas spent on calldata. This change will significantly reduce the maximum block size by limiting the size of data-heavy transactions that can fit into a single block. By increasing calldata costs from 4/16 to 10/40 gas per byte for data-heavy transactions, this EIP aims to reduce the maximum possible EL payload size to approximately 0.72 MB (`30_000_000/40`) without affecting the majority of users. + +Notably, regular users (e.g. sending ETH/Tokens/NFTs, engaging in DeFi, social media, restaking, bridging, etc.), who do not use calldata predominantly for DA, may remain unaffected. +The calldata cost for transactions involving significant EVM computation remains at 4/16 gas per byte, so those transactions are unaffected. + +## Backwards Compatibility + +This is a backwards incompatible gas repricing that requires a scheduled network upgrade. + +Wallet developers and node operators MUST update gas estimation handling to accommodate the new calldata cost rules. Specifically: + +1. **Wallets**: Wallets using `eth_estimateGas` MUST be updated to ensure that they correctly account for the `TOTAL_COST_FLOOR_PER_TOKEN` parameter. Failure to do so could result in underestimating gas, leading to failed transactions. + +2. **Node Software**: RPC methods such as `eth_estimateGas` MUST incorporate the updated formula for gas calculation. Node developers MUST ensure compatibility with the updated calldata pricing logic. + +Users can maintain their usual workflows without modification, as wallet and RPC updates will handle these changes. + +## Security Considerations + +As the maximum possible block size is reduced, no security concerns have been raised. + +In some cases, it might seem advantageous to combine two transactions into one to reduce costs. For example, bundling a transaction that relies heavily on calldata but minimally on EVM resources with another that does the opposite. However, this is not a significant concern for several reasons: + +1. This type of bundling is already possible today. Merging multiple transactions can save the 21,000 gas cost for each additional transaction beyond the first, a feature explicitly supported in [ERC-4337](https://eips.ethereum.org/EIPS/eip-4337). +2. Such bundling does not compromise the block size reduction objectives of this EIP. +3. In practice, transaction bundling is often impractical due to challenges such as trust and coordination requirements. + +These factors ensure that transaction bundling does not pose a significant issue. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-497.md b/BEPs/BEP-497.md new file mode 100644 index 000000000..82af5559d --- /dev/null +++ b/BEPs/BEP-497.md @@ -0,0 +1,98 @@ +
+  BEP: 497
+  Title: Implement EIP-7691: Blob throughput increase
+  Status: Review
+  Type: Standards
+  Created: 2024-12-18
+  Description: Increase the number of blobs to reach a new target and max of 6 and 9 blobs per block respectively.
+
+ + +# BEP-497: Implement EIP-7691: Blob throughput increase + +- [BEP-497: Implement EIP-7691: Blob throughput increase](#bep-497-implement-eip-7691-blob-throughput-increase) + * [Abstract](#abstract) + * [Motivation](#motivation) + * [Specification](#specification) + + [Parameters](#parameters) + * [Rationale](#rationale) + + [Simplicity](#simplicity) + + [Testable changes](#testable-changes) + + [Update Fraction](#update-fraction) + * [Backwards Compatibility](#backwards-compatibility) + * [Security Considerations](#security-considerations) + * [Copyright](#copyright) + +## Abstract + +This EIP proposes to increase to the number of blobs in a block to provide more scale to Ethereum via L2 solution that rely on L1 data capacity. + +## Motivation + +Ethereum, with its rollup centric roadmap, scales by relying on L2. Since the Dencun fork, the blob gas target and maximum was set to 3/6 respectively. The blob gas limit was arrived at based on a series of big block tests performed on the Ethereum mainnet network as well as a series of testnets. The values were chosen cautiously, as it's extremely hard to predict the exact p2p behaviour of Ethereum mainnet. + +As we now have the Dencun upgrade live, we are able to use monitoring tools to check the network health. Initial monitoring indicates that we have a stable network with the current gas target and the re-org rate is trending downwards. Additionally, analysis on messages in gossipsub indicate that the inclusion of `IDONTWANT` messages could bring us a significant bandwidth savings. This allows us to consider starting a series of big block and blob tests to determine the theoretical headroom we currently have. The EIP specifies a proposed new blob gas target and limit based on the series of tests. + +Additional EIPs such as [EIP-7623](./eip-7623.md) proposes a calldata cost increase which would significantly lower the worst case base block size, thus creating more headroom for a potential blob throughput increase. + +The current long term plan of Ethereum is to implement peerDAS as specified by [EIP-7594](./eip-7594.md), but given the uncertain timelines, this EIP aims to increase the throughput short term to provide some scaling until future solutions are deployed. In order to alleviate valid concerns about solo-stakers, approaches such as the inclusion of a flag indicating the max blobs per block for locally built blocks could be considered. + + +## Specification + +### Parameters + +| Constant | Value | +|------------------------------------------|---------------------| +| `PECTRA_FORK_EPOCH` | `tbd` | +| `MAX_BLOBS_PER_BLOCK_ELECTRA` | `9` | +| `TARGET_BLOBS_PER_BLOCK_ELECTRA` | `6` | +| `MAX_BLOB_GAS_PER_BLOCK` | `1179648` | +| `TARGET_BLOB_GAS_PER_BLOCK` | `786432` | +| `BLOB_BASE_FEE_UPDATE_FRACTION_ELECTRA` | `5007716` | + +`MAX_BLOBS_PER_BLOCK_ELECTRA` and `TARGET_BLOBS_PER_BLOCK_ELECTRA` are consumed by the consensus layer clients, and starting at `PECTRA_FORK_EPOCH` replace the respective old max and target values. + +`MAX_BLOB_GAS_PER_BLOCK`, `TARGET_BLOB_GAS_PER_BLOCK` and `BLOB_BASE_FEE_UPDATE_FRACTION_ELECTRA` are consumed by the execution layer clients, and starting at `PECTRA_FORK_EPOCH` timestamp replace the old max, target and update fraction values. + +## Rationale + +### Simplicity + +A blob limit increase at the fork transition is relatively straightforward from an implementation perspective. We would need to deploy an increased amount of monitoring around the fork epoch, but after a period of stability we can assume that the blob limit increase was successful, reducing any unexpected co-ordination efforts. + +The EIP aims to minimize the amount of testing and implementation effort from the perspective of the client teams, to allow for more resources to be allocated to peerDAS and other scaling research. + +While this EIP may not achieve the new optimal blob limit, it offers a compromise for a short term increase. + +### Testable changes + +Through the use of big block/blob tests on Ethereum mainnet as well as testnets, we can earn a high degree of certainity that the blob limit increase would not negatively impact the network. These tests as well as the associated analysis can be performed mostly by non-client team entities, with minimal input required. Since the changes are quite contained, the EIP should be able to reduce the risk of the blob limit increase. + +### Update Fraction + +The original target and max values from [EIP-4844](./eip-4844.md) were at a 1:2 ratio. As a consequence, responsiveness to full and empty blob sections was symmetrical: + +* full blobs: basefee increases by ~12.5% +* no blobs: basefee decreases by ~11.1% + +The new target and max values from this EIP are at a 2:3 ratio, which breaks that symmetry.As a consequence, the basefee becomes significantly more responsive to empty blob sections (that are 6 blobs under target) than to full ones (that are 3 blobs over target). This is by design, as it takes two blocks with full blobs in a row to make up for a single block with no blobs. However, it creates the challenge of finding a good compromise base fee sensitivity level. + +The `BLOB_BASE_FEE_UPDATE_FRACTION_ELECTRA` value in this EIP is chosen as the mid-point between keeping the responsiveness to full blobs and no blobs constant: + +* full blobs: basefee increases by ~8.2% +* no blobs: basefee decreases by ~14.5% + +## Backwards Compatibility + +The consensus clients would continue to use `MAX_BLOBS_PER_BLOCK` and `TARGET_BLOBS_PER_BLOCK` for the deneb fork and once the `ELECTRA` fork is active, they would use `MAX_BLOBS_PER_BLOCK_ELECTRA` and `TARGET_BLOBS_PER_BLOCK_ELECTRA` respectively. + +The execution clients would continue to use `MAX_BLOB_GAS_PER_BLOCK`, `TARGET_BLOB_GAS_PER_BLOCK` and `BLOB_BASE_FEE_UPDATE_FRACTION` for the cancun fork and once the prague fork is active, they would use `MAX_BLOB_GAS_PER_BLOCK`, `TARGET_BLOB_GAS_PER_BLOCK` and `BLOB_BASE_FEE_UPDATE_FRACTION_ELECTRA` respectively. + +## Security Considerations + +todo + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-520.md b/BEPs/BEP-520.md new file mode 100644 index 000000000..e605132d3 --- /dev/null +++ b/BEPs/BEP-520.md @@ -0,0 +1,152 @@ +
+  BEP: 520
+  Title: Short Block Interval Phase One: 1.5 seconds
+  Status: Enabled
+  Type: Standards
+  Created: 2025-02-10
+  Description: To shorten the block interval from 3 seconds to 1.5 seconds.
+
+ +# BEP-520: Short Block Interval Phase One: 1.5 seconds +- [BEP-520: Short Block Interval Phase One: 1.5 seconds](#bep-520-short-block-interval-phase-one-15-seconds) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Parlia Changes](#41-parlia-changes) + - [4.1.1 Millisecond Representation in Block Header](#411-millisecond-representation-in-block-header) + - [4.1.2 Increase `initialBackOffTime`](#412-increase-initialbackofftime) + - [4.2 Parameter Changes](#42-parameter-changes) + - [4.2.1 Change Table](#421-change-table) + - [5. Rational](#5-rational) + - [5.1 Epoch and TurnLength](#51-epoch-and-turnlength) + - [5.2 GasLimit and GasLimitBoundDivisor](#52-gaslimit-and-gaslimitbounddivisor) + - [5.3 Blob Related](#53-blob-related) + - [5.4 Contract Parameters](#54-contract-parameters) + - [6. Backward Compatibility](#6-backward-compatibility) + - [6.1 MEV](#61-mev) + - [6.2 Layer 2 Solutions](#62-layer-2-solutions) + - [6.3 Quarterly Auto-Burn](#63-quarterly-auto-burn) + - [6.4.DApp Developers And Users](#64dapp-developers-and-users) + - [6.5 Block Finality](#65-block-finality) + - [7. License](#7-license) + +## 1. Summary +Shorten the block interval from 3 seconds to 1.5 seconds to enable faster transaction confirmation and improve user experience. + +## 2. Abstract +Since its inception, BSC has maintained a 3-second block interval. Shortening this interval can provide quicker transaction confirmations, enhancing user experience. However, this modification presents challenges that require adjustments to the consensus mechanism and network parameters. +There would be two phases to shorten block interval from 3 seconds to 0.75 seconds. +- Phase One: shorten block interval from 3 seconds to 1.5 seconds. +- Phase Two: shorten block interval from 1.5 seconds to 0.75 seconds. + +This BEP is mainly for phase one, but it will also include some description of phase two, as they are highly relevant. + +## 3. Motivation +In a competitive blockchain landscape, users demand faster transaction confirmations. Reducing the block interval will make BSC more competitive and meet user expectations for high-performance blockchains. +And the two phases strategy is to avoid one big step to reduce it to 0.75s directly, which could be too risky, as the overall infrastructure may not be fully ready to this change. Phase two(0.75s) would be carried out after phase one(1.5s) has been verified. + +## 4. Specification +### 4.1 Parlia Changes +#### 4.1.1 Millisecond Representation in Block Header +Before the implementation of this BEP, both block intervals and block times were represented with a minimum unit of `second`. Post - BEP, the minimum unit is changed to `millisecond`. + +Regarding the representation of block time, to maintain maximum compatibility, the unit of `Header.Time` remains `second`. The `millisecond` component is stored in the last two bytes of `Header.MixDigest`. The following Go code snippets illustrate how this is achieved: +```Go +// SetMilliseconds can be called once millisecond representation supported +func (h *Header) SetMilliseconds(milliseconds uint64) { + h.MixDigest = common.Hash(uint256.NewInt(milliseconds % 1000).Bytes32()) +} + +// Ensure Milliseconds is less than 1000 when verifying the block header +func (h *Header) MilliTimestamp() uint64 { + milliseconds := uint64(0) + if h.MixDigest != (common.Hash{}) { + milliseconds = uint256.NewInt(0).SetBytes32(h.MixDigest[:]).Uint64() + } + return h.Time*1000 + milliseconds +} +``` + +#### 4.1.2 Increase `initialBackOffTime` +In the Parlia engine, each block height has a designated in-turn validator responsible for producing the block. If the in-turn validator fails to produce the block in time, a second-priority validator will take over after a delay equal to `initialBackOffTime`. +Current settings: +```Go + initialBackOffTime= time.Duration(1)*time.Second +``` +As the block interval decreases, delayed block propagation will result in more blocks being reorganized each time. To mitigate this issue, the `initialBackOffTime` is set to 2 seconds. +```Go + newInitialBackOffTime= time.Duration(2)*time.Second +``` + +### 4.2 Parameter Changes +As mentioned above, phase one and phase two are highly relevant, their parameter changes will be put in one table for easy comparison. But the parameters of phase two here is only for reference, as it could be changed in the future when phase two is finally delivered. + +#### 4.2.1 Change Table +A multitude of system parameters are configured based on the assumption that the default block interval is 3 seconds. Consequently, when the block interval is altered, these parameters must be adjusted accordingly: +|parameter |type |origin(3s) | phase one(1.5s) | phase two(0.75s)| +|--------|--------|--------|--------|--------| +|Epoch |client parameter |200 |500 |1000| +|GasLimit |client parameter |140M |70M |35M| +|GasLimitBoundDivisor |client parameter |256 |1024 |1024| +|Blob Target |client parameter |3 |3 |3 | +|Blob Maximum |client parameter |6 |6 |6 | +|Blob MinBlocksForBlobRequests |client parameter |524288 |1048576 (524288 × 2) |2097152 (524288 × 4)| +|BSCGovernor.votingPeriod |contract parameter |$votingPeriod |$votingPeriod × 2 |$votingPeriod × 4| +|BSCGovernor.minPeriodAfterQuorum |contract parameter |$minPeriodAfterQuorum |$minPeriodAfterQuorum × 2 |$minPeriodAfterQuorum × 4 | +|SlashIndicator.misdemeanorThreshold |contract parameter |$misdemeanorThreshold |$misdemeanorThreshold × 2 |$misdemeanorThreshold × 4| +|SlashIndicator.felonyThreshold |contract parameter |$felonyThreshold |$felonyThreshold × 2 |$felonyThreshold × 4| +|SlashIndicator.felonySlashScope |contract parameter |$felonySlashScope |$felonySlashScope × 2 |$felonySlashScope × 4| +|BSCValidatorSet.TurnLength |contract parameter |4 |8 |16| +## 5. Rational +### 5.1 Epoch and TurnLength +Within an epoch, some validators may fail to produce blocks as scheduled due to maintenance, system failures, or other issues. This can lead to an increased number of low-difficulty blocks, reducing network stability. When a new epoch begins, the validator set is adjusted, replacing validators that have repeatedly failed to produce blocks as scheduled to maintain network stability. Therefore, the epoch duration must not be too long, or the network’s stability will degrade. + +Since validators now produce blocks consecutively, the epoch length should be set so that each validator has an approximately equal number of block production opportunities within an epoch. + +At validator set transition points, a validator can deliberately delay broadcasting its block. As long as the delay does not exceed the predefined `initialBackOffTime`, the delayed block will still be accepted by the network. Increasing `BSCValidatorSet.TurnLength` effectively mitigates this issue. + +Considering these factors, the epoch length is set to 500, and `TurnLength` to 8. When the block interval is reduced to 1.5 seconds, the epoch duration will increase from 600 to 750 seconds. A 500-block epoch roughly allows 21 validators to produce three full rounds of 8 blocks each. + +### 5.2 GasLimit and GasLimitBoundDivisor +As the block interval shortens, the gas limit per block must decrease accordingly. The gas limit is initially set to decrease to 70M in the phase one hard fork and to 35M in phase two hard fork. + +GasLimitBoundDivisor represents the rate of change in GasLimit. Since the block interval will be reduced by a factor of four after phase two, GasLimitBoundDivisor is increased by the same factor to maintain a consistent rate of GasLimit adjustment to avoid sharp gas limit fluctuation if some validators use a too small or too large gas limit value. + +As GasLimit is not part of consensus, it is calculated based on validators' configuration. So need validators's support to downgrade their gas limit configuration before each hard fork. + +### 5.3 Blob Related +This BEP implementation aims to maintain or enhance the network’s capacity to handle blobs. According to the table, before phase one hard fork, the network handles a target of 1 blob per second (3 blobs/3 seconds). After phase one hard fork, it will be 2 blobs per second(3 blobs/1.5seconds). So there will be 100% improvement in blob processing capacity. + +### 5.4 Contract Parameters +The six parameters—`BSCGovernor.votingPeriod`, `BSCGovernor.minPeriodAfterQuorum`, `BSCValidatorSet.misdemeanorThreshold`, `BSCValidatorSet.felonyThreshold`, `BSCValidatorSet.felonySlashScope`, and `Blob MinBlocksForBlobRequests`—are all measured in block numbers and used to calculate time. Therefore, when the block interval is reduced, the block numbers must be increased proportionally to maintain the same time representation. + +## 6. Backward Compatibility +### 6.1 MEV +After phase one, the block interval will be reduced to 1.5 seconds, a single validator will produce 8 consecutive blocks per turn, keeping the total block production time at 12 seconds (1.5 × 8). However, the shorter block time significantly reduces the collaboration window for searchers, builders, and validators, impacting the current process and requiring adjustments. + +### 6.2 Layer 2 Solutions +In the first phase, `Blob Target` and `Blob Maximum` will not be reduced to avoid impacting existing users. + +### 6.3 Quarterly Auto-Burn +The [Quarterly Auto-Burn](https://www.bnbburn.info/) mechanism also requires adjustment,The block count in the formula is replaced with time, resulting in the new formula: + +$B = (T/3)\*1000/(P+K) \approx (T\*334)/(P+K)$ + +where T represents the number of seconds in the corresponding quarter. + +### 6.4.DApp Developers And Users +**Timing Based on Block Numbers** +The reduction in block intervals affects logic that relies on block numbers for timing, whether in independent services or within smart contracts. A simple solution is to adjust the corresponding block count or avoid using block numbers for timing altogether. + +**Indexing Based on `block.timestamp`** +With the block interval reduced to 0.75 seconds, `block.timestamp`, which has second-level precision, may be the same for consecutive blocks. Therefore, using `block.timestamp` as an index key or for similar purposes requires adjustment. A common solution is to use the block hash instead. + +### 6.5 Block Finality +This BEP will not change the fast finality mechanism, but short block interval could bring some challenges to fast finality, as votes need to be propagated in a shorter time. When fast finality works properly, with this BEP, the average transaction finality time would be reduced from 7.5 seconds to 3.75 seconds. +But if fast finality failed, with TurnLength 8 and ValidatorSize 21, for natural block finality, it will be: +- (with >1/2 validator confirmations): 88(11*8) blocks, that is 132 seconds +- (with >2/3 validator confirmations): 120(15*8) blocks, that is 180 seconds + +## 7. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-524.md b/BEPs/BEP-524.md new file mode 100644 index 000000000..f935c4efb --- /dev/null +++ b/BEPs/BEP-524.md @@ -0,0 +1,109 @@ +
+  BEP: 524
+  Title: Short Block Interval Phase Two: 0.75 seconds
+  Status: Enabled
+  Type: Standards
+  Created: 2025-02-18
+  Description: To shorten the block interval from 1.5 seconds to 0.75 seconds.
+
+ +# BEP-524: Short Block Interval Phase Two: 0.75 seconds +- [BEP-524: Short Block Interval Phase Two: 0.75 seconds](#bep-524-short-block-interval-phase-two-075-seconds) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Parameter Changes](#41-parameter-changes) + - [4.1.1 Change Table](#411-change-table) + - [4.2 Clear MinerHistory Based on Latest Finalized Blocks](#42-clear-minerhistory-based-on-latest-finalized-blocks) + - [5. Rational](#5-rational) + - [5.1 Parameter Changes](#51-parameter-changes) + - [5.2 Clear MinerHistory Based on Latest Finalized Blocks](#52-clear-minerhistory-based-on-latest-finalized-blocks) + - [6. Backward Compatibility](#6-backward-compatibility) + - [6.1 MEV](#61-mev) + - [6.2 Layer 2 Solutions](#62-layer-2-solutions) + - [6.3 Quarterly Auto-Burn](#63-quarterly-auto-burn) + - [6.4 Block Finality](#64-block-finality) + - [7. License](#7-license) + +## 1. Summary +Shorten the block interval from 1.5 seconds to 0.75 seconds to enable faster transaction confirmation and improve user experience. + +## 2. Abstract +BEP-520 is the phase one to reduce the block interval from 3 seconds to 1.5 seconds. And this BEP is the phase two, which would reduce it further to 0.75 seconds. + +## 3. Motivation +Faster transaction confirmation is a critical and long term goal, with 0.75 seconds block interval, it could meet the requirement of some time sensitive applications. + +## 4. Specification +The overall design specification is similar to BEP-520, so only the parameter changes will be covered in this section. + +### 4.1 Parameter Changes +As mentioned above, phase one and phase two are highly relevant, their parameter changes will be put in one table for easy comparison. + +#### 4.1.1 Change Table +A multitude of system parameters are configured based on the assumption of the default block interval. Consequently, when the block interval is altered, these parameters must be adjusted accordingly: +|parameter |type | origin(3s) | phase one(1.5s) | phase two(0.75s)| +|--------|--------|--------|--------|--------| +|Epoch |client parameter |200 |500 |1000| +|GasLimit |client parameter |140M |70M |35M| +|GasLimitBoundDivisor |client parameter |256 |1024 |1024| +|Blob Target |client parameter |3 |3 |3| +|Blob Maximum |client parameter |6 |6 |6| +|Blob MinBlocksForBlobRequests |client parameter |524288 |1048576 (524288 × 2) |2097152 (524288 × 4)| +|BSCGovernor.votingPeriod |contract parameter |$votingPeriod |$votingPeriod × 2 |$votingPeriod × 4| +|BSCGovernor.minPeriodAfterQuorum |contract parameter |$minPeriodAfterQuorum |$minPeriodAfterQuorum × 2 |$minPeriodAfterQuorum × 4 | +|BSCValidatorSet.misdemeanorThreshold |contract parameter |$misdemeanorThreshold |$misdemeanorThreshold × 2 |$misdemeanorThreshold × 4| +|BSCValidatorSet.felonyThreshold |contract parameter |$felonyThreshold |$felonyThreshold × 2 |$felonyThreshold × 4| +|BSCValidatorSet.felonySlashScope |contract parameter |$felonySlashScope |$felonySlashScope × 2 |$felonySlashScope × 4| +|BSCValidatorSet.TurnLength |contract parameter |4 |8 |16| + +### 4.2 Clear MinerHistory Based on Latest Finalized Blocks +Under the current block producer selection algorithm, if a validator fails to produce a block during its assigned slot, another validator may take over. However, due to the restrictions imposed by `MinerHistory`(as defined in [BEP-404](./BEP-404.md)), the replacement validator may also be ineligible during its own slot, which reduces the overall rate of in-turn block production. + +[BEP-404](./BEP-404.md) introduced logic to clear `MinerHistory` when the validator set changes, preventing this issue from accumulating over time. However, since this BEP will increase the `epochLength` to 1000, such off-schedule production issues can now persist and accumulate within a single epoch. + +To mitigate this, this BEP proposes clearing outdated entries in `MinerHistory` based on the latest finalized block. Any entry with a block number less than or equal to the finalized block number will be removed: + +```Go +MinerHistory map[uint64]Address +latestFinalizedBlockNumber uint64 + +// Clear entries up to the latest finalized block +for blockNumber := range MinerHistory { + if blockNumber <= latestFinalizedBlockNumber { + delete(MinerHistory, blockNumber) + } +} + +``` + +## 5. Rational +### 5.1 Parameter Changes +Refer [BEP-520](./BEP-520.md) +### 5.2 Clear MinerHistory Based on Latest Finalized Blocks +This feature leverages Fast Finality to optimize the selection of block producers, improving the overall rate of in-turn block production. As a result, interactions with the in-turn block producer can be further optimized—for example, in terms of block production, voting, transactions, and the propagation of builder-generated bids to the next in-turn block producer. + +## 6. Backward Compatibility +### 6.1 MEV +After phase two, the block interval will be reduced to 0.75 seconds, a single validator will produce 16 consecutive blocks per turn, keeping the total block production time at 12 seconds (0.75 × 16). However, the shorter block time significantly reduces the collaboration window for searchers, builders, and validators, impacting the current process and requiring adjustments. + +### 6.2 Layer 2 Solutions +`Blob Target` and `Blob Maximum` remain unchanged to preserve compatibility with existing users. At the same time, the increased blob capacity lowers the cost of submitting blob data. + + +### 6.3 Quarterly Auto-Burn +The [Quarterly Auto-Burn](https://www.bnbburn.info/) mechanism also requires adjustment,The block count in the formula is replaced with time, resulting in the new formula: + +$B = (T/3)\*1000/(P+K) \approx (T\*334)/(P+K)$ + +where T represents the number of seconds in the corresponding quarter. + +### 6.4 Block Finality +This BEP will not change the fast finality mechanism, but short block interval could bring some challenges to fast finality, as votes need to be propagated in a shorter time. When fast finality works properly, with this BEP, the average transaction finality time would be reduced from 3.75 seconds to 1.875 seconds. +But if fast finality failed, with TurnLength 16 and ValidatorSize 21, for natural block finality, it will be: +- (with >1/2 validator confirmations): 176(11*16) blocks, that is 132 seconds +- (with >2/3 validator confirmations): 240(15*16) blocks, that is 180 seconds + +## 7. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-525.md b/BEPs/BEP-525.md new file mode 100644 index 000000000..735a7f7dc --- /dev/null +++ b/BEPs/BEP-525.md @@ -0,0 +1,203 @@ +
+  BEP: 525
+  Title: Validator Dedicated Network
+  Status: Withdrawn
+  Type: Standards
+  Created: 2025-02-19
+  Discussions(optional): https://forum.bnbchain.org/t/call-for-feedbacks-bsc-short-block-interval-validator-dedicated-network-and-direct-mempool/3348
+
+ +# BEP-525: Validator Dedicated Network +- [BEP-525: Validator Dedicated Network](#bep-525-validator-dedicated-network) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1.Validator Dedicated Network(VDN)](#31validator-dedicated-networkvdn) + - [3.2.Messages](#32messages) + - [a.Handshake v1](#ahandshake-v1) + - [b.ContactInfo v1](#bcontactinfo-v1) + - [c.Block v1](#cblock-v1) + - [d.RequestBlockByRange v1](#drequestblockbyrange-v1) + - [e.Vote v1](#evote-v1) + - [f.Transactions v1](#ftransactions-v1) + - [4.Rational](#4rational) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [5.1 Validator Operator](#51-validator-operator) + - [5.2.RPC Providers And Other Full Nodes Operators](#52rpc-providers-and-other-full-nodes-operators) + - [6. License](#6-license) + +## 1. Summary +This is a new network topology that only accepts validators or nodes authorized by validators. + +## 2. Motivation +- For low network latency between validators: as BSC targets to short its block interval to sub-second, it is quite crucial to reduce the network latency between validators. Current P2P gossip based network is good at broadcasting blocks/transactions to the whole network, but it is not efficient enough, i.e. it would take lots of network bandwidth and also cost non-negligible latency. +- For low transaction latency: transaction latency is one of the key user experiences. Directed TxPool can provide a straight-forward path to deliver transactions to validators, whcih could be much faster comparing to the current gossip based public p2p network. +## 3. Specification +### 3.1.Validator Dedicated Network(VDN) +The general network topology can be described by the following diagram: + +![overview](./assets/BEP-525/3-1-2.png) + +Basically validators would be able to find and connect with each other to reduce the network latency. + +Here is the description of these roles in VDN: +- **VDN-BootNode**: It helps validators discover each other and establish connections, and only validators registered with the staking contract are allowed to connect. +- **Validator**: joins the network through the VDN-BootNode, discover and connect with other validators in the VDN, and exchange messages. +- **Validator-Sentry**(optional): it acts as a bridge between the public network and a validator. Transactions can be sent to this sentry node through RPC calls or through the current P2P protocol, then it will forward transactions to the corresponding validator nodes. It will also broadcast blocks produced by validators to public network. This sentry node is optional, validator can have none, one or even more than one sentry nodes. If validator does not have the sentry node, it will receive RPC call or P2P messages directly from public network, exposing the validator to public network directly could have some security risks. Validator can setup 1 or more sentry nodes, which could make it more robust. The sentry node is quite flexible, validators can even share sentry nodes with other validators to share the network security and also save maintenance effort. +- **Validator-Proxy**(optional): in case validator doesn’t want to expose itself to VDN directly, it could authorise one or more proxy nodes to connect to the VDN. It mainly helps on transmitting messages like blocks/votes/transactions between validators in VDN. + +### 3.2.Messages +There would be a new protocol to define the messages that are broadcasted within VDN. These messages would be transmitted with QUIC protocol and will be based on the pubsub mechanism. All messages are `RLP encoded`. + +#### a.Handshake v1 +Protocol ID: `/bsc/vdn/v1/handshake` + +Request & Response Content: + +``` +( + chainID: uint64 + forkID: [4]byte + genesis_hash: Hash + node_version: string + extend: []byte + pub_key: PublicKey + sign: Signature +) +``` + +`chainID`, `forkID`, `genesis_hash` should be valid value, and `extend` is empty now which is reserved for future usage. Only validators registered with the staking contract are allowed to connect. + +Once the validator connects to any node, it will initiate a handshake. If the verification fails, it will disconnect. + +After the connection is successful, it will periodically send handshakes. Once it finds that the validator is no longer active, it will disconnect. + +#### b.ContactInfo v1 +Protocol ID: `/bsc/vdn/v1/contact_info` + +Request Content: + +``` +( + peer_id: string + pub_key: PublicKey + listen_p2p_addrs: []Address // validator can connect it by the addresses. + cache: []Concact // max 8 cache node's contact + create_time: Time +) +``` + +Response Content: + +``` +( + code: StatusCode +) +``` + +After the validator joins the network, it will periodically send its contact info and also the cached contact info to the network. + +Once it connects to most nodes, it will reduce the sending frequency. + +#### c.Block v1 +Protocol ID: `/bsc/vdn/v1/block` + +Request Content: + +``` +( + block: Block + create_time: Time +) +``` + +Response Content: + +``` +( + code: StatusCode +) +``` + +After the inturn validator packs a block, it will immediately send the block to the next N inturn validators. + +> N refers to the number of validators that produce blocks in the current epoch. + +#### d.RequestBlockByRange v1 +Protocol ID: `/bsc/vdn/v1/req/block_by_range` + +Request Content: + +``` +( + start_height: uint64 + count: uint64 +) +``` + +Response Content: + +``` +( + code: StatusCode + blocks: []Block +) +``` + +When the validator receives the future block, it requests the missing block from the source node. + +#### e.Vote v1 +Protocol ID: `/bsc/vdn/v1/vote` + +Request Content: + +``` +( + vote: Vote + create_time: Time +) +``` + +Response Content: + +``` +( + code: StatusCode +) +``` + +When the validator successfully verifies the block, it sends FF vote to the next N inturn validators. + +#### f.Transactions v1 +Protocol ID: `/bsc/vdn/v1/transactions` + +Request Content: + +``` +( + txs: []Transaction // not exceed 10MB in total msg size +) +``` + +Response Content: + +``` +( + code: StatusCode +) +``` + +When the validator receives the block, it sends the current pending txs to the next inturn validator. + +## 4.Rational +TBD + +## 5. Backwards Compatibility +### 5.1 Validator Operator +Operators would need to change their node's network configuration to integrate VDN. They would need fully understand the new topology and may setup the validator-sentry and validator-proxy node respectively. They may also need to monitor their network quality to provide good network quality. + +### 5.2.RPC Providers And Other Full Nodes Operators +Depends on the strategy of the RPC providers and other full nodes, they may connect to validator-sentry nodes directly, so it would have lower latency and user's transaction would be protected as these transaction would not be leaked to public txpool. But they can also choose to not connect to validator-sentry nodes directly and forward transactions to validators through a different route path. The public network composed by these full nodes will mainly help on block syncing, while transaction will not be gossiped in this public network. + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-536.md b/BEPs/BEP-536.md new file mode 100644 index 000000000..71ba7178a --- /dev/null +++ b/BEPs/BEP-536.md @@ -0,0 +1,48 @@ +
+  BEP: 536
+  Title: Directed TxPool
+  Status: Withdrawn
+  Type: Standards
+  Created: 2025-02-19
+  Discussions(optional): https://forum.bnbchain.org/t/call-for-feedbacks-bsc-short-block-interval-validator-dedicated-network-and-direct-mempool/3348
+
+ +# BEP-536: Directed TxPool +- [BEP-536: Directed TxPool](#bep-536-directed-txpool) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1.Directed TxPool](#31directed-txpool) + - [4.Rational](#4rational) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [5.1 MEV and PBS](#51-mev-and-pbs) + - [6. License](#6-license) + +## 1. Summary +Transactions will be forwarded directly to a few validators who are most likely to produce the next block. + +## 2. Motivation +- For MEV protection: validators are the key role in the network, it is reasonable that validators have the highest priority to get the transactions. Directed txpool means transactions would be forwarded to a small subset of validators that are most likely to produce the next block. It could avoid exposing users transactions directly to public txpool, so users would less likely to face malicious MEV attacks. +## 3. Specification + +### 3.1.Directed TxPool +It is another key aspect of VDN, transactions that are broadcasted in VDN would no long be gossip based, on the opposite, they will only be broadcasted to next {N} validators which have the highest priority to propose the next block. The value of {N} is configurable, by default {N} could be three, which means one in-turn validator, one next-in-turn validator and first backup validator which has the highest priority to produce the block in case the in-turn validator failed to generate it in time. + +![overview](./assets/BEP-536/3-2.png) + +## 4.Rational +TBD + +## 5. Backwards Compatibility + +### 5.1 MEV and PBS +This BEP would have great impact to the Proposer-Builder-Separation(PBS) mechanism and MEV(Maximum-Extractable-Value) ecosystem. + +As the public txpool would be gradually replaced by directed txpool, which means transactions would be forwarded to validators directly, consequently: +- MEV searchers would have to get the transactions from validators, which would be more difficult. +- MEV builders can still act as a bridge between searchers and validators, but the impact to searchers would impact builders indirectly. + +The PBS architecture was introduced in [BEP-322: Builder API Specification for BNB Smart Chain](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP322.md), which tries to make MEV more transparent and fully competed. But due to the MEV impact by this BEP, current PBS mechanism would be weaken as well. PBS is useful, as none malicious MEV activities are good for the chain ecosystem, community will try to find a solution to sustain or upgrade the PBS mechanism, so builders will be less impacted. + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-543.md b/BEPs/BEP-543.md new file mode 100644 index 000000000..fe2ad4669 --- /dev/null +++ b/BEPs/BEP-543.md @@ -0,0 +1,154 @@ +
+  BEP: 543
+  Title: opBNB Shorter Block Interval
+  Status: Draft
+  Type: Standards
+  Created: 2025-03-14
+  Description: To shorten opBNB block interval from 1 second to 500 milliseconds.
+
+ +# BEP-543: opBNB Short Block Interval +- [BEP-543: opBNB Short Block Interval](#bep-543-opbnb-short-block-interval) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Millisecond Representation in opBNB Block Header](#41-millisecond-representation-in-opbnb-block-header) + - [4.2 Timestamp of RawSpanBatch](#42-timestamp-of-rawspanbatch) + - [4.3 Parameter Changes](#43-parameter-changes) + - [5. Rational](#5-rational) + - [5.1 SeqWindowSize and MaxSequencerDrift](#51-seqwindowsize-and-maxsequencerdrift) + - [5.2 ChannelTimeout and MaxChannelDuration](#52-channeltimeout-and-maxchannelduration) + - [5.3 op-Proposer propose interval](#53-op-proposer-propose-interval) + - [5.4 op-Batcher submit Blob data](#54-op-batcher-submit-blob-data) + - [6. Backward Compatibility](#6-backward-compatibility) + - [6.1 DApp Developers And Users](#61-dapp-developers-and-users) + - [7. License](#7-license) + +## 1. Summary +Shorten the block interval from 1 second to 500 milliseconds to adapt BSC shorter block interval change and also enable faster transaction confirmation, improving user experience. + +## 2. Abstract +BSC has started to shorten block intervals [(BEP-524)](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-524.md) to sub-seconds. As the L2 of BSC, opBNB needs to adapt to the change. As design opBNB’s block interval should be less than BSC’s. +Lower block time intervals can provide quicker transaction confirmation and better user experience. +This BEP is mainly to reduce the opBNB block time from 1 second to 500 milliseconds. + +## 3. Motivation +After BSC network moves to the 750 milliseconds block time interval, opBNB will never be able to sync to the latest cross-chain messages and stop producing blocks. +It is required that opBNB reduces the block time interval to adapt. And besides this, reducing block time intervals will make opBNB more competitive and better meet users’ expectations. + +## 4. Specification + +### 4.1 Millisecond Representation in opBNB Block Header +Referencing [BEP-520](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-520.md), the millisecond time for opBNB is also stored in the `Header.MixDigest`. This field is populated by the value from the `Header.MixDigest` of the BSC. Consequently, +the last two bytes of opBNB's `Header.MixDigest` are utilized to store the BSC millisecond time. To prevent any potential conflicts, opBNB has reserved the first two bytes specifically for its own millisecond time. +After the hard fork, all modules of opBNB will switch from second-level timestamps to millisecond-level timestamps, and a flag will be set in the `Header.MixDigest` field to indicate that it has started storing milliseconds. +This careful structuring ensures compatibility while optimizing both chains' functionality. +The opBNB BlockTime is calculated by op-node and distributed to op-geth through `PayloadAttributes`. Therefore, the millisecond timestamp will be written into `PayloadAttributes` and then copied to the opBNB Block Header. + +```Go +// SetMillisecondTimestamp is used to set millisecond timestamp. +// [32]byte PrevRandao +// [0][1] represent l2 millisecond's mill part. +func (pa *PayloadAttributes) SetMillisecondTimestamp(ts uint64, updateMilliSecond bool) { + pa.Timestamp = hexutil.Uint64(ts / 1000) + if updateMilliSecond { + milliPartBytes := uint256.NewInt(ts % 1000).Bytes32() + pa.PrevRandao[0] = milliPartBytes[30] + pa.PrevRandao[1] = milliPartBytes[31] + + // It is just a marker byte to ensure that the whole is not empty; + // op-geth relies on non-empty to determine that the passed in millisecond timestamp. + pa.PrevRandao[2] = 1 + } +} + +// millisecondes returns milliseconds of header +unc (h *Header) millisecondes() uint64 { + if h.MixDigest == (common.Hash{}) { + return 0 + } + return uint256.NewInt(0).SetBytes2(h.MixDigest[:2]).Uint64() +} + +// MilliTimestamp returns timestamp in milliseconds +func (h *Header) MilliTimestamp() uint64 { + return h.Time*1000 + h.millisecondes() +} + +// SecondsTimestamp returns timestamp in seconds +func (h *Header) SecondsTimestamp() uint64 { + return h.Time +} + +// NextMilliTimestamp returns next block's timestamp in milliseconds +func (h *Header) NextMilliTimestamp() uint64 { + if h.MixDigest == (common.Hash{}) { + return h.Time*1000 + 1000 + } + return h.MilliTimestamp() + 500 +} + +// NextSecondsTimestamp returns next block's timestamp in seconds +func (h *Header) NextSecondsTimestamp() uint64 { + return h.NextMilliTimestamp() / 1000 +} +``` + +To ensure forward compatibility, millisecond timestamps can be identified by checking `h.MixDigest == (common.Hash{})`; if not enabled, the timestamps will continue to be in second-level format. + +* `MilliTimestamp` returns the millisecond-level block timestamp to enable opBNB to support sub-second block production. +* `NextMilliTimestamp` may be called when verifying the time relationship between parent and child blocks. +* `NextSecondsTimestamp` and `SecondsTimestamp` will be called when checking for forks, as forks still use second-level timestamps. + + +### 4.2 Timestamp of RawSpanBatch +`RawSpanBatch` serves as a streamlined storage format for L2Block on opBNB and does not have reserved unused fields for storing millisecond timestamps. The timestamps within `RawSpanBatch` + are converted from second-level timestamps to millisecond timestamps after the hard fork. + +### 4.3 Parameter Changes +A multitude of system parameters are configured based on the assumption that the default block interval is 1 second. Consequently, when the block interval is altered, these parameters must be adjusted accordingly: + + +|parameter |type | origin(1s) | new(500ms)| +|--------|--------|--------|--------| +|L1EpochPollInterval |op-node parameter |3s |1.5s/750ms | +|BlockTime |op-node parameter |1s |500ms | +|MaxSequencerDrift |op-node parameter |1800 |3600/7200 | +|SeqWindowSize |op-node parameter |14400 |28800/57600 | +|ChannelTimeout |op-node parameter |1200 |2400/4800 | +|MaxChannelDuration |op-batcher parameter |32 |64/128 | +|TargetNumFrames |op-batcher parameter |6 |3/2 | + +The items in the list that depend on BSC's block time will have two new values, primarily relying on the timing of the BSC hard forks for [BEP-520](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-520.md) and [BEP-524](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-524.md). + +The BlockTime configuration, which was previously specified in seconds, will transition to a millisecond-based unit. For instance, if it was originally set to 1 to represent 1 second, +it must now be adjusted to 1000 post-upgrade to preserve the same functionality. Additionally, it is advisable to avoid configuring block times shorter than 100 milliseconds. + +## 5. Rational +### 5.1 SeqWindowSize and MaxSequencerDrift +SeqWindowSize and MaxSequencerDrift are measured in block numbers. +SeqWindowSize origin value 14400 means that if opBNB fails and does not recover within 14400 * 3s (BSC BlockTime) = 24 hours, opBNB will be permanently irrecoverable. +MaxSequencerDrift origin value 1800 means that after BSC stops producing blocks, opBNB can still produce blocks, but if it exceeds 1800 * 1s (opBNB BlockTime) = 30 minutes, it will stop producing blocks. +Therefore, although both are measured in block numbers, they indeed reflect a measurement of time. With the forks of BSC and opBNB, the time for handling exceptional situations cannot be shortened, +so these parameters need to be adjusted proportionally. + +### 5.2 ChannelTimeout and MaxChannelDuration +ChannelTimeout and MaxChannelDuration are both measured in BSC block numbers, representing the timeout periods for uploading and downloading L2 blocks in the channel. As the BSC BlockTime shortens, +the configuration for storing the same amount of data in the pipeline needs to be increased proportionally. + +### 5.3 op-Proposer propose interval +The interval for op-proposer to propose the state root remains 3600(30min), instead of 7200(1h), primarily considering the following three points: +* The recovery time after a sequencer restart remains the same or even becomes faster. +* Compatibility for users obtaining withdrawal proofs based on the Block Number (the most recent Block Number divisible by 3600). +* The waiting time for users to prove a withdrawal initiated in opBNB has been reduced from 1 hour to 30 minutes. + +### 5.4 op-Batcher submit Blob data +As [BEP-520](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-520.md) describes, the block handles 1 blob per second, blob maximum is 2. Op-batcher will adjust the configuration item TargetNumFrames accordingly. + +## 6. Backward Compatibility +### 6.1 DApp Developers And Users +The impact on DApp developers and users is similar to that of [BEP-520](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP-524.md), primarily affecting **Timing Based on Block Numbers** and **Indexing Based on block.timestamp**. ​A common solution is to use the block hash instead. + +## 7. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-563.md b/BEPs/BEP-563.md new file mode 100644 index 000000000..e30a2a112 --- /dev/null +++ b/BEPs/BEP-563.md @@ -0,0 +1,129 @@ +
+  BEP: 563
+  Title: Enhanced Validator Network
+  Status: Enabled
+  Type: Standards
+  Created: 2025-04-16
+  Description: To make network more efficient between validators.
+
+ +# BEP-563: Enhanced Validator Network +- [BEP-563: Enhanced Validator Network](#bep-563-enhanced-validator-network) + * [1. Summary](#1-summary) + * [2. Status](#2-status) + * [3. Motivation](#3-motivation) + * [4. Specification](#4-specification) + + [4.1 Clarification](#41-clarification) + - [4.1.1 Sentry Node](#411-sentry-node) + - [4.1.2 NodeID](#412-nodeid) + + [4.2 NodeID Registration](#42-nodeid-registration) + - [4.2.1 Update on web page](#421-update-on-web-page) + - [4.2.2 Update on node start](#422-update-on-node-start) + + [4.3 NodeID Verification](#43-nodeid-verification) + + [4.4 Message Propagation](#44-message-propagation) + * [5. Rationale](#5-rationale) + + [5.1 Why add validator’s NodeID](#51-why-add-validators-nodeid) + + [5.2 Why use system contract](#52-why-use-system-contract) + * [6. Backward Compatibility](#6-backward-compatibility) + * [7. License](#7-license) + +## 1. Summary + +This BEP supports adding validator’s NodeID on the system contract, so the validators can identify each other in the p2p network and forward messages more efficiently. + +## 2. Status + +Draft + +## 3. Motivation + +The current BSC P2P network runs well with a 3-second block interval, but after BEP-520 and BEP-524, BSC will achieve a subsecond block interval, which has higher requirements for low message latency. + +The current public P2P network is a permissionless network on a large scale, anyone can join the network. Permissionless is necessary for a decentralized network, but it has several challenges, especially on network latency and efficiency. + +To satisfy the network requirement of subsecond block interval, it is very helpful to have validators recognize each other in the network and be close enough to each other. Meanwhile, core consensus messages, such as Block Message and Vote Message, can be propagated under the new network topology with better network quality. + +## 4. Specification + +### 4.1 Clarification + +Before diving deep into the design doc, try to introduce some common concepts first. + +#### 4.1.1 Sentry Node + +For security purposes, most validators work on the intranet. The Sentry Node is a full node that acts as the validator's public network protection node. It connects to the public network P2P Node and forwards P2P messages. + +Since the sentry node is the proxy node of the validator on the public network, the validator needs to register the sentry's NodeID on the chain. + +#### 4.1.2 NodeID + +NodeID is the public key that's used for encrypting communication. A connection can be established with any P2P peer through IP+Port+NodeID. + +### 4.2 NodeID Registration + +This BEP will upgrade the StakeHub contract; it needs to add new storage slots to save the validator's NodeIDs. + +And there are some rules: + +- NodeIDs update can only be conducted with operatorAddress, agentAddress or consensusAddress. +- Only validators created in stakeHub can add multiple NodeIDs. +- The maximum number of NodeIDs that each validator can register can be changed through governance, 5 by default. + +There are two approaches to update the nodes: + +#### 4.2.1 New Interfaces of StakeHub contract + +The StakeHub system contract will provide two new interfaces to add and remove NodeIDs respectively: + +```solidity + function addNodeIDs(bytes32[] calldata newNodeIDs) external; + function removeNodeIDs(bytes32[] calldata targetNodeIDs) external; +``` + +As mentioned above, only three specific addresses of the validator: `operatorAddress`, `agentAddress`, and `consensusAddress` are permitted to call the two interfaces. Calls from any other address will be reverted. + +#### 4.2.2 Tips for Updating NodeIDs + +To simplify the process of updating NodeIDs, several approaches can be considered: + +- The BNB Chain Staking page can offer a user-friendly interface, allowing users to connect their wallets with operator or agent accounts to easily update NodeIDs. +- The BSC client can provide configuration options for adding or removing NodeIDs. + +It’s important to note that this process is not part of the consensus mechanism, and detailed instructions will be provided later. + +### 4.3 NodeID Verification + +- Retrieve the Latest Validator Node IDs: This can be achieved by subscribing to the NodeIDAdded and NodeIDRemoved events for each block, or by periodically querying the interface getNodeIDs(address[] calldata validatorsToQuery). +- P2P Connection Handling: During the P2P connection process, verify if the connected node matches any of the registered validator Node IDs. If it does, it will be classified as a validator’s sentry node; otherwise, it will be considered a normal node. + +### 4.4 Message Propagation + +Some connection features will be enabled between validators to optimize network congestion and reduce message latency. + +- Transaction: it will not be propagated between validators. +- Block: it will prioritize broadcasting directly to all other connected validators in the network. The specific implementation depends on the client and needs to balance latency and bandwidth. +- Vote: same as block. + +## 5. Rationale + +### 5.1 Why add validator’s NodeID + +Currently, validators often connect to the P2P Network through public full nodes. When producing blocks or sending votes, the connected full nodes may forward the block through multiple hops before reaching other validators. + +By adding validator’s NodeID on the chain, validators can be identified, so the validator/sentry can choose to connect to validators first, and keep a small number of full nodes. + +At the same time, a more efficient message forwarding mechanism can be enabled between validators, better traffic control can be implemented, and the delay of message reception can be further reduced. + +### 5.2 Why use system contract + +The update of the system contract depends on the hardfork, which can maintain consistent registration and query logic for all nodes. + +At the same time, registering the NodeID in the system contract can also maximize decentralization. Any active validator can be updated at any time and can quickly establish an efficient P2P connection with other validators. + +## 6. Backward Compatibility + +This BEP requires a hard fork to upgrade the system contract and keep the logic of all nodes consistent. + +## 7. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-564.md b/BEPs/BEP-564.md new file mode 100644 index 000000000..53df0181c --- /dev/null +++ b/BEPs/BEP-564.md @@ -0,0 +1,96 @@ +
+  BEP: 564
+  Title: bsc/2 - New Block Fetching Messages
+  Status: Enabled
+  Type: Standards
+  Created: 2025-04-16
+  Description: To accelerate block fetching for shorter block interval.
+
+ +# BEP-564: bsc/2 - New Block Fetching Messages +- [BEP-564: bsc/2 - New Block Fetching Messages](#bep-564-bsc2---new-block-fetching-messages) + * [1. Summary](#1-summary) + * [2. Status](#2-status) + * [3. Motivation](#3-motivation) + * [4. Specification](#4-specification) + + [4.1 Block Fetching Message](#41-block-fetching-message) + * [5. Rationale](#5-rationale) + + [5.1 Why new block fetching messages](#51-why-new-block-fetching-messages) + * [6. Forward Compatibility](#6-forward-compatibility) + + [6.1 eth/69 protocol](#61-eth69-protocol) + * [7. Backward Compatibility](#7-backward-compatibility) + + [7.1 eth/68 protocol](#71-eth68-protocol) + * [8. License](#8-license) + +## 1. Summary + +This BEP introduces new block fetching messages to speed up the import of newly generated blocks, prevent nodes from lagging at subsecond block intervals, and especially improve validator consensus efficiency. + +## 2. Status + +Draft + +## 3. Motivation + +With the future activation of BEP-520 and BEP-524, BSC will achieve a subsecond block interval, which has higher requirements for faster block fetching. + +However, the eth/68 protocol is very inefficient when processing NewBlockHash messages, and it requires multiple queries before a new block can be imported. + +This BEP introduces a New Block Fetching Message, which greatly reduces the number of queries, supports fast fetching of newly generated blocks, avoids validators and full nodes from lagging behind in the subsecond block interval, and especially improves the validator consensus efficiency, which can produce the next block or send vote faster. + +## 4. Specification + +### 4.1 Block Fetching Message + +Current block querying is inefficient, requiring multiple requests for both block headers and block bodies. This BEP will add the following messages to reduce the delay in obtaining blocks. + +```go +const ( + GetBlocksByRangeMsg = 0x02 // it can request (Head-n, Head] range blocks from remote peer + BlocksByRangeMsg = 0x03 // the replied blocks from remote peer +) + +type GetBlocksByRangePacket struct { + RequestId uint64 + StartBlockHeight uint64 // The start block height expected to be obtained from + StartBlockHash common.Hash // The start block hash expected to be obtained from + Count uint64 // Get the number of blocks from the start +} + +type BlocksByRangePacket struct { + RequestId uint64 + Blocks []*types.Block +} +``` + +The peer can request a range of blocks, specifying the starting block using either StartBlockHeight or StartBlockHash. If StartBlockHash is not equal to the empty hash (0x0000000000000000000000000000000000000000000000000000000000000000), the starting block will be determined by StartBlockHash. Otherwise, it will default to StartBlockHeight. + +When specifying a StartBlockHeight or StartBlockHash and a Count, the blocks will be returned in reverse order, starting from the given block and going backward. + +This method is used to synchronize the latest small range of blocks quickly. Historical block synchronization still uses the eth/68 protocol. + +![](assets/BEP-564/image1.png) + +## 5. Rationale + +### 5.1 Why new block fetching messages + +The eth/68 protocol fetches the block header and body from the remote separately and assembles them locally. These messages are also applicable to full sync and snap sync processes, and it can save bandwidth when fetching the fork or bad blocks. + +However, multiple queries will multiply the latency between nodes. After subsecond block interval, fetching the block quickly is the key. New block fetching messages simplify the process of fetching blocks and support requesting a range of blocks with only one round trip. + +## 6. Forward Compatibility + +### 6.1 eth/69 protocol + +The bsc/2 is completely independent of the ETH series of protocols, so future upgrades to eth/69 are fully compatible. + +## 7. Backward Compatibility + +### 7.1 eth/68 protocol + +There should be no impact on eth/68. When obtaining the block announced by NewBlockHash, bsc/2 can work simultaneously with eth/68. Due to the low efficiency of eth/68 fetch, bsc/2 will fetch the block first. After the client marks the current block as known, eth/68 will no longer continue to request. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-590.md b/BEPs/BEP-590.md new file mode 100644 index 000000000..779a97bff --- /dev/null +++ b/BEPs/BEP-590.md @@ -0,0 +1,94 @@ +
+  BEP: 590
+  Title: Extended Voting Rules for Fast Finality Stability
+  Status: Enabled
+  Type: Standards
+  Created: 2025-06-25
+  Description: Enhance the robustness of Fast Finality by extending aggregate vote inclusion rules.
+
+ +# BEP-590: Extended Voting Rules for Fast Finality Stability + +- [BEP-590: Extended Voting Rules for Fast Finality Stability](#bep-590-extended-voting-rules-for-fast-finality-stability) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Aggregate Vote Rule Changes](#41-aggregate-vote-rule-changes) + - [5. Security](#5-security) + - [6. Backward Compatibility](#6-backward-compatibility) + - [7. License](#7-license) + +## 1. Summary + +This BEP proposes an extension to the aggregate vote inclusion rules in the Fast Finality (FF) protocol of the BNB Smart Chain. The change aims to improve the stability and liveness of Fast Finality under adverse network conditions and support further reductions in block interval. + +## 2. Abstract + +[BEP-126](./BEP126.md) introduced Fast Finality as a mechanism for deterministic block finalization in BNB Smart Chain. Under the original design: + +* Proposers (miners) may only aggregate votes for their direct parent block. + +Formally, if `KAncestorGenerationDepth` defines the inclusion scope, then in the original design: + +``` +KAncestorGenerationDepth = 1 +``` + +This BEP extends the scope by allowing `KAncestorGenerationDepth > 1`: + +* **Aggregate Vote Inclusion Extension** — Proposers may include votes for up to `KAncestorGenerationDepth` recent ancestor blocks, improving tolerance to vote propagation latency. + +This adjustment enhances the resilience of Fast Finality during periods of network congestion, without modifying the core consensus model or cryptographic assumptions. + +## 3. Motivation + +Validators can experience latency in receiving, verifying, and casting votes for blocks. Such delays may lead to missing justifications, which in turn hinders finalization. + +Additionally, as block intervals shorten, inter-region network latency becomes a more prominent bottleneck in vote propagation. + +This BEP addresses these issues by introducing: + +* **More flexible vote aggregation** — to increase the chances of including valid votes despite network delays. + +## 4. Specification + +This BEP introduces modifications to the **Aggregate Vote Inclusion Rules**. + +### 4.1 Aggregate Vote Rule Changes + +To improve vote inclusion under delayed network conditions, proposers are allowed to aggregate votes for recent ancestor blocks. The process follows this priority sequence: + +1. Attempt to aggregate votes for the **immediate parent block**. +2. If unavailable, try the **grandparent block**. +3. Continue iteratively up to `KAncestorGenerationDepth` recent ancestors. + +The process **terminates immediately** once any valid vote is included. At most **one ancestor block’s votes** may be aggregated in a single proposal. + +This rule gives validators up to `KAncestorGenerationDepth` block intervals to propagate their votes, improving the success rate of vote inclusion and reducing justification gaps during periods of network latency. + +With [the block interval reduced to 0.45s](./BEP-619.md), the parameter `KAncestorGenerationDepth` is set to 3. +``` + KAncestorGenerationDepth = 3 +``` + +## 5. Security + +This BEP does **not** alter the core safety assumptions or mechanisms of Fast Finality defined in [BEP-126](./BEP126.md). Specifically, it **does not change**: + +* **Validator Vote Rules** — which govern when and how validators may issue votes. +* **Finality Rules** — including thresholds for justification and finalization. +* **Longest Chain Rule** — the fork-choice rule determining canonical chain selection. + +This proposal only modifies the **vote aggregation scope** to improve vote inclusion flexibility. +All original safety guarantees, including one-block finality under an honest super majority, remain **intact**. + +## 6. Backward Compatibility + +This BEP is **not backward compatible** with older clients, as it changes vote aggregation behavior. However, it introduces no changes to protocol-level message formats or user-facing APIs. + +A full client upgrade across validators and block producers is required to activate the changes and maintain consensus. + +## 7. License + +The content is licensed under [Creative Commons CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-592.md b/BEPs/BEP-592.md new file mode 100644 index 000000000..01dd18a0f --- /dev/null +++ b/BEPs/BEP-592.md @@ -0,0 +1,141 @@ +
+  BEP: 592
+  Title: Non-Consensus Based Block-Level Access List
+  Status: Candidate
+  Type: Standards
+  Created: 2025-06-30
+  Description: A non-consensus block-level access list mechanism that preloads storage data to accelerate block execution and improve network throughput.
+
+ +# BEP-592: Non-Consensus Based Block-Level Access List + +## Table of Contents +- [BEP-592: Non-Consensus Based Block-Level Access List](#bep-592-non-consensus-based-block-level-access-list) + - [Table of Contents](#table-of-contents) + - [1. Summary](#1-summary) + - [2. Status](#2-status) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Parameters](#41-parameters) + - [4.2 Data Structure](#42-data-structure) + - [4.3 BAL Generation](#43-bal-generation) + - [4.4 BAL Propagation and bsc/3 P2P Protocol](#44-bal-propagation-and-bsc3-p2p-protocol) + - [4.5 BAL Storage](#45-bal-storage) + - [4.6 BAL Execution](#46-bal-execution) + - [5. Rationale](#5-rationale) + - [5.1 Why not include the slot value in BAL?](#51-why-not-include-the-slot-value-in-bal) + - [5.2 Why not define a new block header element for BAL?](#52-why-not-define-a-new-block-header-element-for-bal) + - [5.3 Any incentive/slash for a validator to generate BAL?](#53-any-incentiveslash-for-a-validator-to-generate-bal) + - [6. Forward Compatibility](#6-forward-compatibility) + - [7. Backward Compatibility](#7-backward-compatibility) + - [8. License](#8-license) + +## 1. Summary + +This BEP introduces Block-Level Access Lists (BAL) - metadata attached to blocks that enables concurrent preloading of storage data during block import. By caching frequently accessed accounts and storage slots, BAL reduces block execution latency and improves overall network throughput. + +## 2. Status + +Draft + +## 3. Motivation + +The primary objective is to enhance BSC's performance by providing access lists during the mining phase. With shorter block intervals and increasing throughput demands, faster block importing becomes crucial for several key stakeholders. + +BAL addresses this by enabling concurrent data preloading, benefiting key network participants: + +- **MEV Builders**: Earlier bid simulation with reduced latency +- **Fast Finality**: Accelerated validator voting improves stability +- **Validators**: More time for block mining, espcially the first consecutive block +- **Full Nodes**: Faster chain synchronization and catch-up + +## 4. Specification + +### 4.1 Parameters + +The following constants define the operational parameters for BAL: + +| Constant | Value | Description | +|----------|-------|-------------| +| `MAX_BAL_BYTES` | `1048576` | Maximum BAL size in bytes (1MB) | +| `DEFAULT_HISTORICAL_BAL` | `360000` | Default blocks to persist BAL data (~3.1 days) | + +### 4.2 Data Structure + +BAL preserves existing block structures by attaching as an optional component at the block's end, maintaining full backward/forward compatibility. The layout of the block content with BAL can be described by the fowllowing diagram: + +Block layout with BAL + +The BAL data structure is defined as follows: + +```go +// StorageAccessItem is a single storage key that is accessed in a block. +type StorageAccessItem struct { + TxIndex uint32 // index of the first transaction in the block that accessed the storage + Dirty bool // true if the storage was modified in the block, false if it was read only + Key common.Hash +} + +// AccountAccessListEncode & BlockAccessListEncode are for BAL serialization. +type AccountAccessListEncode struct { + TxIndex uint32 // index of the first transaction in the block that accessed the account + Address common.Address + StorageItems []StorageAccessItem +} + +type BlockAccessListEncode struct { + Version uint32 // Version of the access list format + Number uint64 // number of the block that the BAL is for + Hash common.Hash // hash of the block that the BAL is for + SignData []byte // sign data for BAL + Accounts []AccountAccessListEncode +} + +``` +Key components: +- `SignData`: 65-byte validator signature using consensus key +- `Version`: Protocol upgrade support (starts at zero) +- Encoding: RLP format following BSC standards (SSZ considered for future versions) + +### 4.3 BAL Generation + +Validators are responsible for generating BAL content during block creation. As validators execute transactions sequentially to create a block, they have complete knowledge of the accounts and storage slots that the block will access. Validators maintain these access lists, sign, encode and attach the result to the end of the block. BAL may contain partial access information due to size constraints, the size of RLP encoded BAL content should not exceed `MAX_BAL_BYTES`. + +### 4.4 BAL Propagation and bsc/3 P2P Protocol + +BAL data will be propagated along with the block as an optional part. But the BAL will only be propagated to peers which supports bsc/3 p2p protocol. The bsc/3 protocol extends bsc/2 with BAL processing capabilities, ensuring backward compatibility. + +### 4.5 BAL Storage + +BAL storage is optional due to its size and primary use for block import acceleration. Nodes may choose retention policies, with a default of `DEFAULT_HISTORICAL_BAL` blocks. + +### 4.6 BAL Execution + +BAL v0 operates as a non-consensus optimization - no validation required. Nodes parse incoming BAL data and preload specified accounts/storage into cache concurrently with block processing, accelerating execution without affecting consensus safety. + +## 5. Rationale + +### 5.1 Why not include the slot value in BAL? + +Excluding slot values maintains size efficiency. A typical block with 200 transactions accessing 50 slots each would require 320KB just for keys. Including values would also require MPT proofs for verification, dramatically increasing BAL size and negating performance benefits. + +### 5.2 Why not define a new block header element for BAL? + +The current approach prioritizes simplicity and compatibility. While header integration remains possible for future versions, attaching BAL as optional data maintains backward compatibility while delivering immediate performance benefits. + +### 5.3 Any incentive/slash for a validator to generate BAL? + +No incentive or penalty mechanisms exist initially - BAL generation is voluntary. Malicious BAL construction has limited impact due to its non-consensus nature, size constraints, and use solely for optimization. The design relies on validators' natural incentive to improve network performance. + +## 6. Forward Compatibility + +BAL's version field enables seamless protocol evolution. Future versions can introduce new features, encoding schemes (like SSZ), or structural enhancements while maintaining compatibility with v0 implementations. + +## 7. Backward Compatibility + +BAL maintains complete backward compatibility by operating as optional block metadata. Non-supporting nodes continue normal operation without consensus or validation impact, ensuring smooth network-wide deployment. + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + diff --git a/BEPs/BEP-593.md b/BEPs/BEP-593.md new file mode 100644 index 000000000..fd17d2ee3 --- /dev/null +++ b/BEPs/BEP-593.md @@ -0,0 +1,118 @@ +
+  BEP: 593
+  Title: Incremental Snapshot
+  Status: Enabled
+  Type: Standards
+  Created: 2025-07-02
+  Description: To make easier for users to start and run BSC nodes.
+
+ +# BEP-593: Incremental Snapshot + +- [BEP-593: Incremental Snapshot](#bep-593-incremental-snapshot) +- [1. Summary](#1-summary) +- [2. Status](#2-status) +- [3. Motivation](#3-motivation) +- [4. Specification](#4-specification) + - [4.1 Incremental Snapshot Schema](#41-incremental-snapshot-schema) + - [4.2 Incremental Snapshot Generation](#42-incremental-snapshot-generation) + - [4.3 Incremental Snapshot Merge](#43-incremental-snapshot-merge) +- [5. Rational](#5-rational) + - [5.1 Incremental Snapshot Size](#51-incremental-snapshot-size) + - [5.2 Safety](#52-safety) +- [6. Backward Compatibility](#6-backward-compatibility) +- [7. License](#7-license) + +# 1. Summary + +This BEP proposes an incremental snapshot mechanism to make it easier for users to start and run BSC nodes with reduced data requirements. By implementing this feature, users will be able to bootstrap their nodes more efficiently while maintaining the necessary functionality for participating in the BSC network. + +Incremental snapshots store incremental block and state data, allowing users to quickly approach the latest block by merging incremental snapshots on top of a [monthly snapshot](https://github.com/bnb-chain/bsc-snapshots?tab=readme-ov-file#mainnetmonthly-update). Compared to the newest prune-ancient snapshot, whose size is greater than 1.0 TB, the monthly incremental snapshot is about 120GB, so users can download some incremental snapshots and merge them can start BSC nodes quickly. + +# 2. Status + +Draft + +# 3. Motivation + +The snapshot of BSC is released monthly, and it usually takes users about 13 hours to download, decompress the snapshot(3 hours), and catch up to the newest block(10 hours). + +

+ storage_compare +

+ +Comparing the full snapshot from June 2025 (total size of 3.72TB) with the one from December 2023 (total size of 2.49TB) reveals that the snapshot has grown significantly, reaching an increase of 49.35%. This will result in longer download and decompression times for users, as well as higher demands on machine disk space and bandwidth usage. This becomes a barrier for users who want to participate in the BSC network. + +To address these challenges, this BEP proposes the incremental snapshot solution. This approach will allow users to more easily catch up with the latest BSC data by downloading smaller, incremental updates rather than a single large snapshot. This will improve the user experience and make it more accessible for new participants to join the BSC network. + +# 4. Specification + +

+ storage_compare +

+ +Execute blocks based on a base snapshot, with a separate backup of the incremental data for each block. Periodically aggregate these incremental data(e.g., fixed at 1000 blocks). + +## 4.1 Incremental Snapshot Schema + +This section describes which data needs to be recorded during block execution for Incremental Snapshot aggregation. The data can be divided into two categories: Block data and State data. + +- Block data mainly includes: BlockHeader, BlockHash, BlockBody, TxReceipt, Difficulty, and BlobSidecar. +- State data includes: StateHistory, which is used for PBSS rollback, and StateTrieNodes, which are used to generate the latest state data during Merge Incremental Snapshot. + +After the Maxwell hard fork, there will be approximately 3,456,000 blocks in one month, with an average size of about 100KB. The total size is roughly 345.6GB. The state trie nodes updated by each block amount to about 2MB, with a total size of approximately 6.92TB. Due to the large volume of data, the download speed for users will be slow. + +Therefore, the following adjustments have been made: + +- Block data only needs to store the most recent several tens of thousands of blocks, similar to pruning ancient snapshots, less than 10GB. +- State data can be aggregated, keeping the size around 100GB. + +## 4.2 Incremental Snapshot Generation + +During startup, add the `--incr.enable` flag. The system will asynchronously generate incremental snapshots in a separate directory, and when the data volume reaches a certain threshold, it will automatically switch to a new directory. Generally, regular users do not need to run nodes with the `-- incr.enable` flag. The official nodes are configured with the `--incr.enable` flag and periodically upload incremental snapshots to remote storage for download by users. + +Additional incremental snapshot generation flags: + +- `--incr.datadir` is used to set data directory for storing generated incremental snapshot data. +- `--incr.block-interval` can be used to set how many blocks interval are stored into one incremental snapshot. Default value is `100_000`. +- `--incr.state-buffer` is used to set the incr state memory buffer to aggregate MPT trie nodes. The larger the setting, the smaller the incr snapshot size, it also needs large memory. The default value is `6GB`. +- `--incr.kept-blocks` is used to set how many blocks are kept in incr snapshot. At least and default value is `1024` blocks. + +## 4.3 Incremental Snapshot Merge + +Add the `--incr.use-remote` flag, and also set the remote incremental snapshot URL using the `--incr.remote-url` flag with `--incr.datadir` to store the downloaded incremental snapshots. After startup, the system will automatically download the required incremental snapshots and perform merging. The incremental snapshots are downloaded sequentially, and the download and merge processes run in a pipeline manner, which significantly improves efficiency. + +During the merge, both block data and state data are written into PebbleDB, and necessary metadata such as `HeadHeader`, `HeadBlock`, etc., are updated to ensure continuity from the latest merged block. Once all incremental snapshots are merged, the client switches to full mode to continue block synchronization from P2P. + +# 5. Rational + +## 5.1 Incremental Snapshot Size + +Prune ancient snapshots to only keep the most recent 360,000 blocks of block data. Keeping the last 10,000 blocks of incremental snapshots is sufficient, around 1GB. + +State data can be aggregated. According to testing, 10GB of space can accommodate the state data for 300,000 blocks, after the hard fork on Maxwell. The total size of the state data can be reduced to ~120GB per month. + +An incremental snapshot is generated once a week. Each incremental snapshot contains the latest 10,000 blocks of block data, approximately 1 GB, and the corresponding state data, with the state data size being approximately 30GB per month (around 120GB per month). Total size approximately 31GB. + +For example, an incremental snapshot representing the block range from 50,000,000 to 50,806,400(one week) would only retain the latest 10,000 blocks of data, covering from 50,796,400 to 50,806,400, ~1GB. The state data must fully include all the change data within the 50,000,000 to 50,806,400 range, but it will be aggregated into several files, each around 10GB in size. It will generate three 10GB state data files. An incremental snapshot is about 31 GB, and it is expected to have 4 incremental snapshots per month, total size of about 124 GB. + +Currently, the size of pruned ancient snapshots is around 1TB. Users' local data is less than one year behind the latest block, so using the “--syncmode snap.increment” mode is worthwhile. + +## 5.2 Safety + +Incremental snapshots allow the local data to quickly jump to a relatively recent state before starting synchronization, thereby reducing the distance to the latest block and improving synchronization speed. The reason why merging incremental snapshots is faster than P2P is mainly because it bypasses the execution and validation phases, essentially only involving the commit phase. + +Incremental snapshots essentially allow the user's local data to quickly chang to a recent pruned ancient snapshot through a centralized method. Its security is equivalent to downloading pruned ancient snapshots. + +# 6. Backward Compatibility + +This BEP maintains full backward compatibility with existing BSC node implementations. Users have the flexibility to choose between two approaches: + +1. Traditional full snapshot: Users can continue to use the complete snapshot as before, which contains all historical data. +2. Incremental snapshot: Users can opt to use the new incremental snapshot mechanism, which provides smaller, more manageable updates. + +The implementation ensures that both methods are fully supported, allowing users to select the approach that best suits their needs and resources. This dual-support system ensures a smooth transition for existing users while providing new options for those who prefer the incremental approach. + +# 7. License + +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-594.md b/BEPs/BEP-594.md new file mode 100644 index 000000000..abeb6c2b7 --- /dev/null +++ b/BEPs/BEP-594.md @@ -0,0 +1,115 @@ +
+  BEP: 594
+  Title: L2 Fast Withdrawal by TEE
+  Status: Draft
+  Type: Standards
+  Created: 2025-07-10
+  Description: Reduce the L2 withdrawal finalization time from 7 days to seconds-level.
+
+ +# BEP-594: L2 Fast Withdrawal by TEE +- [BEP-594: L2 Fast Withdrawal by TEE](#bep-594-l2-fast-withdrawal-by-tee) + * [1. Summary](#1-summary) + * [2. Status](#2-status) + * [3. Motivation](#3-motivation) + * [4. Specification](#4-specification) + + [4.1 Fast withdrawal workflow](#41-fast-withdrawal-workflow) + + [4.2 Architecture changes](#42-architecture-changes) + + [4.3 Contract Interface changes](#43-contract-interface-changes) + * [5. Rational](#5-rational) + + [5.1 Why choose the TEE solution](#51-why-choose-the-tee-solution) + + [5.2 Security](#52-security) + * [6. Backward Compatibility](#6-backward-compatibility) + * [7. License](#7-license) + +## 1. Summary + +This BEP proposes a solution by TEE to reduce the L2 withdrawal finalization time from 7 days to seconds-level. + +## 2. Status + +Draft + +## 3. Motivation + +Asset withdrawals from opBNB to BSC, implemented via an optimistic rollup approach, typically rely on a challenge period (often 7 days) to verify state transitions, resulting in significant delays that cause a poor user experience. + +Referencing the [Base Fast Withdrawal solution](https://blog.base.dev/scaling-with-base-appchains), opBNB proposes an approach leveraging AWS Nitro TEE technology, which reduces the L2 withdrawal finalization time on L1 from several days to just seconds. In the future, our solution will be able to integrate with other standard TEE solutions, providing users with more choices. + +## 4. Specification + +### 4.1 Fast withdrawal workflow + +The following diagram shows the fast withdrawal workflow from a user’s perspective. + +

+ workflow +

+ +User submits an initial withdrawal tx to L2 in step1, and submits a prove & finalize withdrawal tx to L1 in step9. This workflow takes about 30 seconds in total, of which step 4 takes up most of the time. To reduce the time consumption of the whole workflow, the following was included: +* When the op-batcher detects a withdrawal transaction on the L2 unsafe block, it will immediately upload the L2 batches to L1 in step3, rather than waiting until the L2 block data is full. +* When the op-proposer detects a withdrawal transaction on the L2 safe block, it will immediately aggregate, rather than waiting for a certain number of proposals to aggregate, and then send the transaction to update the L2OutputOracle contract. + +### 4.2 Architecture changes + +The following diagram illustrates the overall architecture, primarily explaining the changes made to the architecture and highlighting the location of the newly added op-enclave module within the opBNB system. + +

+ arch +

+ +* op-enclave: It runs the stateless clients in AWS Nitro TEE, passing all the information required for the OP Stack to execute a given block. + +* op-proposer: It interfaces with the TEE running the op-enclave. It maintains an up-to-date proven state and, upon detecting a withdrawal, ensures the proof includes that block before submitting the proposal to L1. op-proposer only proposes safe blocks (post-batch submission), and if no withdrawals occur, it submits a proof every 30 minutes to keep the state current. + +* op-batcher: It posts transaction batches for deriving the L2 state. The batcher is modified such that if a block contains a withdrawal event, the batcher immediately treats the current channel as full and submits the batch to L2. This prioritizes withdrawal transactions for rapid processing. The batcher will also submit a batch every 15 seconds if no withdrawals are seen. + +### 4.3 Contract Interface changes + +The op-proposer produces a verifiable proposal for each block by TEE stateless execution(op-enclave). It aggregates periodically to merge these verifiable proposals to reduce submission frequency and gas fees, and then submits the result to the L2OutputOracle contract for withdrawal proofs. + +The structure of the Proposal is as follows: +```go +type Proposal struct { + OutputRoot common.Hash + Signature hexutil.Bytes + L1OriginHash common.Hash + L2BlockNumber *hexutil.Big +} +``` + +The Signature is generated by signing the Proposal with an ECDSA private key that belongs to TEE. During initialization, TEE registers the ECDSA public key to the L1 L2OutputOracle contract. Before updating the Proposal to L1, the L2OutputOracle contract verifies that the signature originates from a registered op-enclave’s ECDSA.PrivateKey. + +## 5. Rational + +### 5.1 Why choose the TEE solution + +In the opstack rollup, L2 state crosses the chain to L1. There are two finalized solutions: + +* Optimistic Rollups: These rely on a challenge period (often 7 days) to validate state transitions, delaying withdrawals. +* ZK Rollups: ZK rollups offer the promise of fast finality and withdrawals without a challenge period. However, generating ZK validity proofs for the EVM is computationally intensive and expensive. + +While Zero-Knowledge (ZK) solutions are ideal for their minimal trust assumptions, the significant computational cost and complexity of generating proofs make them economically unviable for many applications. + +This BEP therefore proposes a solution using Trusted Execution Environments (TEEs) as a more cost-effective compromise. This TEE-based approach delivers the necessary performance at a fraction of the cost, in exchange for introducing a hardware-based trust assumption. + +### 5.2 Security + +The following table illustrates the trust assumptions of different solutions. + +| |Optimistic | TEE | ZK| +|--------|--------|--------|--------| +|Trust assumptions |Fraud proving |The TEE provider and proposer |Cryptographic proofs, minimal trust| + +The TEE solution adds a new trust relationship with the TEE provider. However, to successfully attack the system, one needs to control both the proposer and the TEE provider, which is very difficult at present. However, TEE is indeed an important part of the cross-chain, and its stability affects the behavior of our system. It has not yet been practiced on a large scale in the blockchain industry. + +## 6. Backward Compatibility + +This BEP maintains full backward compatibility with existing opBNB Stack L2s implementations. It is optional, and even possible to roll back to previous versions. + +Moreover, the TEE architecture code is completely non-intrusive to the opBNB repo. Leveraging opBNB's modular plugin design, the new architecture's code(op-enclave repo) is entirely independent of the opBNB repo. By implementing new plugins, it enables customized special functionalities without affecting the existing code or features of the previous architecture. + +Existing opBNB Stack L2s do not need to worry about the side effects brought by TEE. + +## 7. License +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-610.md b/BEPs/BEP-610.md new file mode 100644 index 000000000..18b6239a5 --- /dev/null +++ b/BEPs/BEP-610.md @@ -0,0 +1,120 @@ +
+  BEP: 610
+  Title: Implement EVM Super Instruction
+  Status: Candidate
+  Type: Standards
+  Created: 2025-08-12
+  Description: It defines several customized super instruction opcodes to replace high frequency EVM opcode sequences to improve performance
+
+ +# BEP-610: Implement EVM Super Instruction + +- [BEP-610: Implement EVM Super Instruction](#bep-610-implement-evm-super-instruction) + - [1. Abstract](#1-abstract) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 Super Instruction opcode definition](#31-super-instruction-opcode-definition) + - [3.2 Optimized Bytecode Generation (Background)](#32-optimized-bytecode-generation-background) + - [3.3 Super-Instruction Execution (Foreground)](#33-super-instruction-execution-foreground) + - [3.4 Super-Instruction Set Generation](#34-super-instruction-set-generation) + - [3.5 Compatibility \& Safety](#35-compatibility--safety) + - [3.6 Security Considerations](#36-security-considerations) + - [4. Backwards Compatibility](#4-backwards-compatibility) + - [5. License](#5-license) + +## 1. Abstract +This BEP introduces several customized super instruction opcodes to replace high frequency EVM opcode sequences to improve performance. Contract byte code is pre-processed to convert some sequence of EVM opcodes to super instruction opcodes and the EVM interpreter executes these super instruction opcode atomically. The approach yields significant execution-layer efficiency without altering consensus rules or requiring a hard-fork. + +## 2. Motivation + +On BSC mainnet, repeated execution of identical compiler-generated instruction patterns dominates gas consumption. By fusing these hot paths into single interpreter dispatches, we: + +- Reduce opcode dispatch overhead +- Minimise stack shuffling +- Achieve measurable throughput gains without protocol change. + +## 3. Specification + +### 3.1 Super Instruction opcode definition + +| Index (Hex) | Super Instruction | +|-------------|-----------------------------------------------------| +| 0xb1 | AndSwap1PopSwap2Swap1 | +| 0xb2 | Swap2Swap1PopJump | +| 0xb3 | Swap1PopSwap2Swap1 | +| 0xb4 | PopSwap2Swap1Pop | +| 0xb5 | Push2Jump | +| 0xb6 | Push2JumpI | +| 0xb7 | Push1Push1 | +| 0xb8 | Push1Add | +| 0xb9 | Push1Shl | +| 0xba | Push1Dup1 | +| 0xbb | Swap1Pop | +| 0xbc | PopJump | +| 0xbd | Pop2 | +| 0xbe | Swap2Swap1 | +| 0xbf | Swap2Pop | +| 0xc0 | Dup2LT | +| 0xc1 | JumpIfZero | +| 0xc2 | IsZeroPush2 | +| 0xc3 | Dup2MStorePush1Add | +| 0xc4 | Dup1Push4EqPush2 | +| 0xc5 | Push1CalldataloadPush1ShrDup1Push4GtPush2 | +| 0xc6 | Push1Push1Push1SHLSub | +| 0xc7 | AndDup2AddSwap1Dup2LT | +| 0xc8 | Swap1Push1Dup1NotSwap2AddAndDup2AddSwap1Dup2LT | +| 0xc9 | Dup3And | +| 0xca | Swap2Swap1Dup3SubSwap2Dup3GtPush2 | +| 0xcb | Swap1Dup2 | +| 0xcc | SHRSHRDup1MulDup1 | +| 0xcd | Swap3PopPopPop | +| 0xce | SubSLTIsZeroPush2 | +| 0xcf | Dup11MulDup3SubMulDup1 | + +### 3.2 Optimized Bytecode Generation (Background) + +| Aspect | Design | +|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Feature Toggle | Node flag `--vm.opcode.optimize` (default false). When disabled, the optimisation pipeline becomes a no-op. | +| Workflow | codeHash lookup -> LRU cache hit -> use optimised code. Cache miss -> (codeHash, rawCode) pushed to lock-free queue. | +| Basic-Block Construction | Split at PC==0 or any JUMPDEST; terminate before {JUMP, JUMPI, STOP, RETURN, REVERT, INVALID}. | +| Pattern Matching & Fusion | Sliding window (1-15 bytes) matches curated patterns; first byte replaced by custom opcode 0xb0–0xcf, trailing bytes overwritten with NOP(0x5b) to preserve length. | +| Cache | (codeHash -> fusedCode) stored in in-memory LRU (64 k entries default). Auxiliary static-analysis bitvectors stored in a side-cache. | + +### 3.3 Super-Instruction Execution (Foreground) + +| Phase | Description | +|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Loading | Before execution, interpreter queries cache with codeHash. Hit -> contract flagged optimized = true, fused bytecode loaded. Miss -> original bytecode executed. | +| Dispatch | Main loop processes opcodes as usual. For newly added superinstruction opcodes, jump directly to Super-Instruction handler. | +| Semantics | Handler emulates entire sequence (e.g., AND DUP2 ADD SWAP1 DUP2 LT) in one step, adjusts PC by original length, validates jump targets when applicable. | +| Safety | If custom opcode appears in non-optimised contract, throw ErrIllegalSuperInst and revert. | + +### 3.4 Super-Instruction Set Generation + +| Process | Description | +|---------|-------------| +| Data-Driven Mining | Trace production traffic, extract opcode sequences, compress with Re-Pair to obtain non-repetitive string. | +| Scoring | `score = len(sequence) × frequency` | +| Overlap Resolution | Greedy graph algorithm adjusts scores when super-instructions overlap (A ⊂ B). | +| Selection | Choose Top-K sequences (32 by default) as canonical super-instruction sets. | + +### 3.5 Compatibility & Safety +| Aspect | Guarantee | +|--------|--------------------------------------------------------------------------------| +| Switchable | Runtime flag permits instant enable/disable without restart. | +| Length-Preserving | Fused bytecode matches original size; all offset-based tooling remains intact. | +| Consensus Neutral | Only local execution changes; on-chain code unmodified -> no consensus impact. | +| Graceful Fallback | Failure in generation/execution reverts to original code path. | + +### 3.6 Security Considerations + +- **Validator Nodes**: Opt-in optimisation must not diverge state; test-suite includes differential fuzzing against vanilla EVM. +- **Custom Opcode Collision**: Range 0xb0–0xcf currently unused by London EVM; future EIPs allocating these bytes must be gated by network governance before activation. +- **DoS Risk**: Background optimiser bounded by worker pool and queue length to avoid unbounded memory/CPU spikes. + +## 4. Backwards Compatibility +Because bytecode length and on-chain contents remain unchanged, no tooling or contract migration is necessary. Nodes that disable the flag continue to operate identically, ensuring a smooth opt-in rollout. + +## 5. License +All the content are licensed under CC0. diff --git a/BEPs/BEP-619.md b/BEPs/BEP-619.md new file mode 100644 index 000000000..497f44712 --- /dev/null +++ b/BEPs/BEP-619.md @@ -0,0 +1,105 @@ +
+  BEP: 619
+  Title: Short Block Interval Phase Three: 0.45 Seconds
+  Status: Enabled
+  Type: Standards
+  Created: 2025-09-11
+  Description: To shorten the block interval from 0.75 seconds to 0.45 seconds.
+
+ +# BEP-619: Short Block Interval Phase Three: 0.45 Seconds +- [BEP-619: Short Block Interval Phase Three: 0.45 Seconds](#bep-619-short-block-interval-phase-three-045-seconds) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Parameter Changes](#41-parameter-changes) + - [4.1.1 Change Table](#411-change-table) + - [4.2 Extended Voting Rules for Fast Finality Stability](#42-extended-voting-rules-for-fast-finality-stability) + - [5. Rationale](#5-rationale) + - [5.1 Parameter Changes](#51-parameter-changes) + - [6. Backward Compatibility](#6-backward-compatibility) + - [6.1 MEV](#61-mev) + - [6.2 Quarterly Auto-Burn](#62-quarterly-auto-burn) + - [6.3 Block Finality](#63-block-finality) + - [7. License](#7-license) + +## 1. Summary + +This proposal shortens the block interval from 0.75 seconds to 0.45 seconds, further improving transaction confirmation speed and enhancing user experience. + +## 2. Abstract + +* **BEP-520** (Phase One): reduced the block interval from 3 seconds to 1.5 seconds. +* **BEP-524** (Phase Two): reduced it further to 0.75 seconds. +* **BEP-619** (Phase Three, this proposal): reduces it to 0.45 seconds. + +## 3. Motivation + +Reducing the block interval is a long-term goal of BNB Smart Chain. A 0.45-second block interval will support time-sensitive applications by providing significantly faster confirmation times. + +## 4. Specification + +The overall design follows BEP-524, with modifications only to the relevant parameters. + +### 4.1 Parameter Changes + +Phases one, two, and three are closely related. For clarity, their parameter changes are consolidated into the following table. + +#### 4.1.1 Change Table + +Many system parameters are tied to the default block interval. When the interval is adjusted, related parameters must also be updated: + +| Parameter | Type | Origin (3s) | Phase One (1.5s) | Phase Two (0.75s) | Phase Three (0.45s) | +| ------------------------------------ | -------- | ---------------------- | ---------------- | ----------------- | ------------------- | +| Epoch | client | 200 | 500 | 1000 | 1000 | +| GasLimit | client | 140M | 100M | 75M | 55M | +| GasLimitBoundDivisor | client | 256 | 1024 | 1024 | 1024 | +| FullImmutabilityThreshold | client | 90,000 | 180,000 | 360,000 | 600,000 | +| receiveRateLimitPerSecond | client | 10 | 20 | 40 | 68 | +| Blob Target | client | 3 | 3 | 3 | 3 | +| Blob Maximum | client | 6 | 6 | 6 | 6 | +| Blob MinBlocksForBlobRequests | client | 524,288 | 1,048,576 (×2) | 2,097,152 (×4) | 3,495,254 (×3/0.45) | +| BSCGovernor.votingPeriod | contract | \$votingPeriod | ×2 | ×4 | ×(3/0.45) | +| BSCGovernor.minPeriodAfterQuorum | contract | \$minPeriodAfterQuorum | ×2 | ×4 | 172800(maximum) | +| BSCValidatorSet.misdemeanorThreshold | contract | \$misdemeanorThreshold | ×2 | ×4 | ×(3/0.45) | +| BSCValidatorSet.felonyThreshold | contract | \$felonyThreshold | ×2 | ×4 | ×(3/0.45) | +| BSCValidatorSet.felonySlashScope | contract | \$felonySlashScope | ×2 | ×4 | ×(3/0.45) | + +`receiveRateLimitPerSecond` is the max number of received votes per second from one peer, used to avoid of DDOS attack. + +### 4.2 Extended Voting Rules for Fast Finality Stability + +With a shorter block interval, network fluctuations and node performance issues have a larger impact on stability. To improve finality robustness, the adjustments defined in [BEP-590: Extended Voting Rules for Fast Finality Stability](./BEP-590.md) will also be applied. + +## 5. Rationale + +### 5.1 Parameter Changes + +* **GasLimit**: In phases one and two, GasLimit did not decrease proportionally with block interval reductions, due to hardware and software optimizations. In phase three, GasLimit is adjusted proportionally to match the reduced interval. +* **Epoch**: Epoch remains at 1000 blocks, reducing epoch time from 750s to 450s. Validator rotation becomes more frequent but is expected to have no negative impact. This also allows more equitable participation opportunities for candidates within a day. + + +## 6. Backward Compatibility + +### 6.1 MEV + +With a 0.45s block interval, each validator still produces 16 consecutive blocks per turn, reducing total turn time to 7.2s (0.45 × 16). This narrows the collaboration window for searchers, builders, and validators, requiring adjustments to current MEV strategies. + +### 6.2 Quarterly Auto-Burn + +*TBD.* + +### 6.3 Block Finality + +The fast finality mechanism remains unchanged. However, shorter intervals reduce the time available for vote propagation. + +* **With fast finality working correctly**: transaction finality improves from \~1.875s to \~1.125s. +* **If fast finality fails** (natural finality with TurnLength=16, ValidatorSize=21): + + * > 1/2 validator confirmations: 176 blocks (11×16) ≈ 79.2s + * > 2/3 validator confirmations: 240 blocks (15×16) ≈ 108s + +## 7. License + +This document is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-640.md b/BEPs/BEP-640.md new file mode 100644 index 000000000..1af7e1019 --- /dev/null +++ b/BEPs/BEP-640.md @@ -0,0 +1,63 @@ +
+    BEP: 640
+    Title: Optional Transaction Gas Limit Cap
+    Status: Candidate
+    Type: Standards
+    Created: 2025-12-10
+    Description: Reduces network reorgs by limiting excessively large transactions.
+
+ +# BEP-640: Optional Transaction Gas Limit Cap + +- [BEP-640: Optional Transaction Gas Limit Cap](#bep-640-optional-transaction-gas-limit-cap) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [Community Autonomy and Soft Cap Enforcement](#community-autonomy-and-soft-cap-enforcement) + - [Smooth Transition Towards EIP-7825](#smooth-transition-towards-eip-7825) + - [5. Backward Compatibility](#5-backward-compatibility) + - [6. License](#6-license) + +## 1. Summary + +This BEP proposes an **optional, community-driven, non-protocol-level mechanism** to cap the maximum Gas Limit for individual transactions. The core objective is to **mitigate network reorganizations (reorgs)** caused by transactions with excessively long execution times, thereby enhancing BSC network **stability**. + +## 2. Abstract + +I/O-intensive transactions (e.g., using **$> 16,777,216$ gas**) exploit the underpricing of EVM I/O operations (like `SSTORE`). Their prolonged execution time often exceeds the block interval, leading to frequent **reorgs**. This BEP introduces **optional tooling and recommendation** to limit the per-transaction gas limit, serving as a **temporary, soft measure** before the potential implementation of a protocol-level solution like [**EIP-7825**](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7825.md). + +## 3. Motivation + +The primary motivation is to **improve the stability and reliability** of the BSC network. + +**Excessive execution time** for single, large transactions is the root cause of network instability. By shortening the block processing time, a soft cap on the maximum gas usage per transaction will significantly **reduce the frequency of destabilizing reorg events**, ensuring better network health. This solution is designed to be **lightweight** and deployable without a hard fork. + +## 4. Specification + +This BEP specifies a **recommended, off-chain** mechanism for limiting per-transaction gas usage, maintaining compatibility with the current **MEV-Boost/Auction mechanism**. + +### Community Autonomy and Soft Cap Enforcement + +Enforcement is at the full discretion of Validators. + + * **Validator Implementation:** Validators **SHOULD** implement an optional **client-side flag** to specify a max gas limit cap when building **blocks**. + +### Smooth Transition Towards EIP-7825 + +The cap aligns with the EIP-7825 limit to prepare the network for a future protocol update. + +* **Default Cap Value:** The default transaction gas limit cap implemented in the client **SHOULD be set to a sufficiently high value** to allow P2P nodes to continue propagating large transactions without restriction. +* **Validator Recommendation:** Validators are **recommended** to similarly cap the maximum gas limit of individual transactions they include in their **internally built blocks** at **$16,777,216$ ($2^{24}$)**. +* **Builder Recommendation:** Builders are **recommended** to similarly cap the maximum gas limit of individual transactions they include in their bids at **$16,777,216$ ($2^{24}$)**. + + +## 5. Backward Compatibility + +The impact is minimal, as transactions exceeding $16,777,216$ gas are a **very small percentage (approx. 0.3%%)** of all on-chain activity. + + * **Mitigation & Flexibility:** Validators **always have the option to opt-out** and maintain an unlimited gas limit cap. The non-protocol nature of this BEP allows for easy adjustment or disabling if community need for larger limits arises. + +## 6. License + +The content is licensed under [Creative Commons CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-648.md b/BEPs/BEP-648.md new file mode 100644 index 000000000..d439777a3 --- /dev/null +++ b/BEPs/BEP-648.md @@ -0,0 +1,71 @@ +
+  BEP: 648
+  Title: Enhanced Fast Finality via In-Memory Voting Pool
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-12
+  Description: Enable faster finality by determining finality through in-memory vote pools, without waiting for votes to be included in block headers.
+
+ +# BEP-648: Enhanced Fast Finality via In-Memory Voting Pool + +- [BEP-648: Enhanced Fast Finality via In-Memory Voting Pool](#bep-648-enhanced-fast-finality-via-in-memory-voting-pool) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Security](#5-security) + - [6. Backward Compatibility](#6-backward-compatibility) + - [7. License](#7-license) + +## 1. Summary + +This BEP proposes an optimization to the Fast Finality mechanism introduced in [BEP-126](./BEP126.md), enabling nodes to collect attestations directly from in-memory vote pools rather than waiting for them to be packaged into block headers, thereby achieving faster finality determination. + +## 2. Abstract + +[BEP-126](./BEP126.md) introduced Fast Finality on BNB Smart Chain. Under the current design, a block is justified when its attestation appears in the next block's header, and finalized when both it and its direct child are justified. This requires at least 2 subsequent blocks. + +This BEP extends the justification rule to allow nodes to determine justification directly from in-memory vote pools when ⅔+ validators' votes are received, without waiting for attestations to be included in block headers. This significantly reduces finality latency while maintaining all BEP-126 security guarantees. + +Attestations continue to be included in block headers as per BEP-126, ensuring validator rewards and enabling on-chain consensus verification. + +## 3. Motivation + +Under BEP-126, finality determination is unnecessarily coupled to block production. Validators complete voting quickly, but finality cannot be determined until attestations are included in block headers. Once ⅔+ validators have voted, their votes already provide sufficient cryptographic proof—waiting for block inclusion introduces artificial delay. + +This BEP decouples finality determination from block production by allowing nodes to determine finality directly from in-memory vote pools. + +## 4. Specification + +This BEP extends the Finality Rules from [BEP-126](./BEP126.md) Section 4.1.3. + +There are two steps to finalize a block, the first step we call justify, the second step we call finalize. + +1. A block is called justified if +* (1) it is the root, or +* (2) there exists attestation for this block ~~in its direct child's header~~, we call this block **justified**. +2. A block is called finalized if +* (1) it is the root, or +* (2) it is justified and its direct child is justified. + +All other aspects of BEP-126 remain unchanged, including validator vote rules, aggregate vote rules, and the longest chain rule. + +## 5. Security + +This BEP does **not** alter the core safety assumptions or mechanisms of Fast Finality. It does not change validator vote rules, aggregate vote rules, finalization thresholds, or the longest chain rule. + +The only modification is allowing nodes to determine justification from in-memory vote pools in addition to on-chain attestations. Both approaches rely on the same cryptographic foundation: ⅔+ valid validator votes. Since the underlying cryptographic proof is unchanged, all [BEP-126](./BEP126.md) safety guarantees—including accountable safety and plausible liveness—remain intact. + +## 6. Backward Compatibility + +This BEP is **fully backward compatible**. It does not change consensus rules, block validation, block headers, or vote aggregation. + +Finality determination is a client-side optimization. Upgraded nodes observe faster finality via in-memory vote pools, while non-upgraded nodes continue using header-based finality. Network stability is unaffected. + +This can be deployed as a client upgrade without requiring network-wide coordination or hard fork activation. + +## 7. License + +The content is licensed under [Creative Commons CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/). + diff --git a/BEPs/BEP-651.md b/BEPs/BEP-651.md new file mode 100644 index 000000000..17aa7d9ea --- /dev/null +++ b/BEPs/BEP-651.md @@ -0,0 +1,132 @@ +
+  BEP: 651
+  Title: Implement EIP-7823 – Set upper bounds for MODEXP
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-20
+  Description: Each input field is restricted to a maximum of 8192 bits
+
+ +# BEP-651: Implement EIP-7823 – Set upper bounds for MODEXP + +- [BEP-651: Implement EIP-7823 – Set upper bounds for MODEXP](#bep-651-implement-eip-7823--set-upper-bounds-for-modexp) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [Limit](#limit) + - [EVMMAX](#evmmax) + - [Analysis](#analysis) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + +## 1. Summary + +This BEP introduces an upper bound on each input field of the MODEXP precompile on BSC. + +## 2. Abstract + +Introduce an upper bound on the inputs of the MODEXP precompile. This can reduce the number of potential bugs, because the testing surface is not infinite anymore, and makes it easier to be replaced using EVMMAX. + +## 3. Motivation + +The MODEXP precompile has been a source of numerous consensus bugs. Many of them were due to specifically crafted cases using impractical input lengths. + +Its pricing function is also quite complex given its nature of unbounded inputs. While we don't suggest to rework the pricing function, it may be possible in a future upgrade once the limits are in place. + +Furthermore this limitation makes it more feasible to have the precompile replaced with EVM code through features like EVMMAX. + +## 4. Specification + +Recap from [EIP-198](https://eips.ethereum.org/EIPS/eip-198): +> At address `0x00……05`, add a precompile that expects input in the following format: +> +> ` ` + +We introduce an upper bound to the inputs of the precompile, each of the length inputs (`length_of_BASE`, `length_of_EXPONENT` and `length_of_MODULUS`) MUST be less than or equal to 8192 bits (1024 bytes). + +If any of these inputs are larger than the limit, the precompile execution stops, returns an error, and consumes all gas. + +## 5. Rationale + +### Limit + +This upper bound allows the existing use cases of MODEXP: + +1. RSA verification with up to 8192 bit keys. Commonly used ones are 1024/2048/4096 bits. +2. Elliptic curve related use cases are usually less than 384 bits. + +### EVMMAX + +Replacing the precompile with EVM code using an instruction set like EVMMAX would be made simpler with this limit: Common cases (256, 381, 1024, 2048) could be implemented in special fast paths, while a slow fallback could be provided for the rest. Or even special, frequently used, moduli could have their own paths. + +Furthermore one could consider limiting the lengths to certain inputs only. + +### Analysis + +Since MODEXP was introduced in the Byzantium hard fork, an analysis has been conducted between block 5472266 (April 20, 2018) and block 21550926 (January 4th, 2025). All lengths of inputs are expressed in bytes. + +#### Base length occurrences + +| `input_of_BASE` | count | +|-----------------|-------| +| 32 | 2439595 | +| 128 | 4167 | +| 256 | 2969 | +| 160 | 436 | +| 512 | 36 | +| 0 | 13 | +| 64 | 7 | +| 78 | 2 | +| 513 | 2 | +| 129 | 1 | +| 385 | 1 | + +#### Exponent length occurrences + +| `input_of_EXPONENT` | count | +|---------------------|-------| +| 32 | 2442255 | +| 3 | 4771 | +| 1 | 159 | +| 128 | 29 | +| 0 | 13 | +| 5 | 2 | + +#### Modulo length occurrences + +| `input_of_MODULUS` | count | +|--------------------|-------| +| 32 | 2439594 | +| 128 | 4167 | +| 256 | 2968 | +| 160 | 436 | +| 512 | 38 | +| 0 | 13 | +| 64 | 8 | +| 78 | 2 | +| 129 | 1 | +| 384 | 1 | +| 257 | 1 | + +This shows that no past successful use case exceeded an input length of 513 bytes, and the majority uses 32/128/256 byte inputs. + +Besides these, there were a few invocations with invalid inputs: + +- Empty inputs +- Inputs consisting of only `0x9e5faafc` or `0x85474728` +- A large, but invalid input: `0x9e281a98000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000021e19e0c9bab2400000` + +## 6. Backwards Compatibility + +This is a backwards incompatible change. However, based on analysis until block 21550926 (see above), no past transaction would have behaved differently after this change. + +## 7. Security Considerations + +Since only the accepted input range is reduced, no new security surface area is expected. + +## 8. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-652.md b/BEPs/BEP-652.md new file mode 100644 index 000000000..771119f08 --- /dev/null +++ b/BEPs/BEP-652.md @@ -0,0 +1,108 @@ +
+  BEP: 652
+  Title: Implement EIP-7825 Transaction Gas Limit Cap
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-20
+  Description: Introduce a protocol-level cap on the maximum gas used by a transaction to 16,777,216 (2^24)
+
+ +# BEP-652: Implement EIP-7825 Transaction Gas Limit Cap + +- [BEP-652: Implement EIP-7825 Transaction Gas Limit Cap](#bep-652-implement-eip-7825-transaction-gas-limit-cap) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [Gas Cap](#gas-cap) + - [Changes to EVM Behavior](#changes-to-evm-behavior) + - [Protocol Adjustment](#protocol-adjustment) + - [Builder and MEV Bid Validation](#builder-and-mev-bid-validation) + - [5. Rationale](#5-rationale) + - [Why 16,777,216 (2^24)?](#why-16777216-224) + - [Compatibility with Current Gas Dynamics](#compatibility-with-current-gas-dynamics) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + +## 1. Summary + +This BEP proposes to introduce a protocol-level cap on the maximum gas usage +per transaction to **16,777,216 (2^24)** on BSC. Previously, **BEP-640** introduced +an optional soft cap mechanism where validators could voluntarily limit per-transaction +gas. This BEP upgrades it to a **mandatory protocol-level enforcement**, ensuring all +nodes uniformly reject transactions exceeding the limit, which can better improve +network stability and reliability compared to the previous approach. + +## 2. Abstract + +This proposal introduces a protocol-level cap on the maximum gas usage per transaction to 16,777,216 (2^24) gas. By implementing this limit, BSC can enhance its resilience against certain DoS vectors, improve network stability, and provide more predictability to transaction processing costs, especially in the context of increasing the gas limit. + +## 3. Motivation + +Currently, transactions can theoretically consume up to the entire block gas limit, which poses several risks: + +1. **DoS Attacks**: A single transaction consuming most or all of the block gas can result in uneven load distribution and impact network stability. +2. **State Bloat Risks**: High-gas transactions often result in larger state changes, increasing the burden on nodes and exacerbating the state growth problem. +3. **Validation Overhead**: High-gas transactions can lead to longer block verification times, negatively impacting user experience and network decentralization. + +By limiting individual transactions to a maximum of 16,777,216 gas, we aim to: + +- Reduce the risks of single-transaction DoS attacks. +- Promote fairer gas allocation across transactions within a block. +- Ensure better synchronization among nodes by mitigating extreme block validation times. + +## 4. Specification + +### Gas Cap + +- Enforce a protocol-level maximum of **16,777,216 gas (2^24)** for any single transaction. +- This cap applies regardless of the block gas limit set by miners or validators. +- Transactions specifying gas limits higher than 16,777,216 gas will be rejected with an appropriate error code (e.g., `MAX_GAS_LIMIT_EXCEEDED`). + +### Changes to EVM Behavior + +1. **Txpool Validation**: During transaction validation, if the `gasLimit` specified by the sender exceeds 16,777,216, the transaction is invalidated (not included in the txpool). +2. **Block Validation**: As part of block validation before processing, any block having a transaction with `gasLimit` > 16,777,216 is deemed invalid and rejected. + +### Protocol Adjustment + +- The `GAS_LIMIT` parameter for transactions will be capped in client implementations at 16,777,216. +- This cap is **independent** of the block gas limit, which exceeds this value. + +### Builder and MEV Bid Validation + +- **Bid Transaction Validation**: When validators receive bids from builders, + each transaction in the bid is validated against the 16,777,216 gas cap. + Bids containing any transaction with `gasLimit` > 16,777,216 are rejected. + +- **Builder Compliance**: Builders must ensure that all transactions included + in their bids have `gasLimit` ≤ 16,777,216. Bids violating this constraint + will be rejected by validators. + +## 5. Rationale + +### Why 16,777,216 (2^24)? + +The proposed cap of 16,777,216 gas (2^24) provides a clean power-of-two boundary that simplifies implementation while still being large enough to accommodate most complex transactions, including contract deployments and advanced DeFi interactions. This value represents approximately half of typical block sizes (30-40 million gas), ensuring multiple transactions can fit within each block. + +### Compatibility with Current Gas Dynamics + +- **Backward Compatibility**: Transactions with gas usage below 16,777,216 remain unaffected. Existing tooling and dApps need only minor updates to enforce the new cap. +- **Impact on Validators**: Validators can continue to process blocks with a gas limit exceeding 16,777,216, provided individual transactions adhere to the cap. + +## 6. Backwards Compatibility + +This change is **not backward-compatible** with transactions that specify gas limits exceeding 16,777,216. Transactions with such high limits will need to be split into smaller operations. This adjustment is expected to impact a minimal number of users and dApps, as most transactions today fall well below the proposed cap. + +An [empirical analysis](https://github.com/bnb-chain/BEPs/blob/master/BEPs/assets/BEP-652/analysis.md) has been conducted to assess the potential impact of this change. + +## 7. Security Considerations + +1. **DoS Mitigation**: A fixed cap reduces the risk of DoS attacks caused by excessively high-gas transactions. +2. **Block Verification Stability**: By capping individual transactions, the validation of blocks becomes more predictable and uniform. +3. **Edge Cases**: Certain highly complex transactions, such as large contract deployments, may require re-architecting to fit within the 16,777,216 gas cap. + +## 8. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-653.md b/BEPs/BEP-653.md new file mode 100644 index 000000000..356b37e1f --- /dev/null +++ b/BEPs/BEP-653.md @@ -0,0 +1,174 @@ +
+  BEP: 653
+  Title: Implement EIP-7883 ModExp Gas Cost Increase
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-20
+  Description: Increases cost of ModExp precompile
+
+ +# BEP-653: Implement EIP-7883 ModExp Gas Cost Increase + +- [BEP-653: Implement EIP-7883 ModExp Gas Cost Increase](#bep-653-implement-eip-7883-modexp-gas-cost-increase) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [Increased minimal and general price](#1-increased-minimal-and-general-price) + - [Increase cost for exponents larger than 32 bytes](#2-increase-cost-for-exponents-larger-than-32-bytes) + - [Assume the minimal base / modulus length to be 32 and increase the cost when it is larger than 32 bytes](#3-assume-the-minimal-base--modulus-length-to-be-32-and-increase-the-cost-when-it-is-larger-than-32-bytes) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#7-test-cases) + - [8. Security Considerations](#8-security-considerations) + - [9. License](#9-license) + +## 1. Summary + +This BEP increases the gas cost of the ModExp precompile on BSC. + +## 2. Abstract + +This BEP is modifying the `ModExp` precompile pricing algorithm introduced in [EIP-2565](https://eips.ethereum.org/EIPS/eip-2565). + +## 3. Motivation + +Currently the `ModExp` precompile is underpriced in certain scenarios relative to its resource consumption. By adjusting the pricing formula, this BEP aims to address these discrepancies, making `ModExp` sufficiently efficient to enable potential increases in the block gas limit. + +## 4. Specification + +Upon activation of this BEP, the gas cost of calling the precompile at address `0x0000000000000000000000000000000000000005` will be calculated as follows: + +```python +def calculate_multiplication_complexity(base_length, modulus_length): + max_length = max(base_length, modulus_length) + words = math.ceil(max_length / 8) + multiplication_complexity = 16 + if max_length > 32: multiplication_complexity = 2 * words**2 + return multiplication_complexity + +def calculate_iteration_count(exponent_length, exponent): + iteration_count = 0 + if exponent_length <= 32 and exponent == 0: iteration_count = 0 + elif exponent_length <= 32: iteration_count = exponent.bit_length() - 1 + elif exponent_length > 32: iteration_count = (16 * (exponent_length - 32)) + ((exponent & (2**256 - 1)).bit_length() - 1) + return max(iteration_count, 1) + +def calculate_gas_cost(base_length, modulus_length, exponent_length, exponent): + multiplication_complexity = calculate_multiplication_complexity(base_length, modulus_length) + iteration_count = calculate_iteration_count(exponent_length, exponent) + return max(500, math.floor(multiplication_complexity * iteration_count)) +``` + +The specific changes from the algorithm defined in [EIP-2565](https://eips.ethereum.org/EIPS/eip-2565): + +### 1. Increased minimal and general price + +The gas cost calculation is modified from: + +```python + return max(200, math.floor(multiplication_complexity * iteration_count / 3)) +``` + +to: + +```python + return max(500, math.floor(multiplication_complexity * iteration_count)) +``` + +This change increases the minimum gas cost from 200 to 500 and triples the general cost by removing the division by 3. + +### 2. Increase cost for exponents larger than 32 bytes + +The gas cost calculation is modified from: + +```python + elif exponent_length > 32: iteration_count = (8 * (exponent_length - 32)) + ((exponent & (2**256 - 1)).bit_length() - 1) +``` + +to: + +```python + elif exponent_length > 32: iteration_count = (16 * (exponent_length - 32)) + ((exponent & (2**256 - 1)).bit_length() - 1) +``` + +The multiplier for exponents larger than 32 bytes is increased from 8 to 16, doubling its impact. + +### 3. Assume the minimal base / modulus length to be 32 and increase the cost when it is larger than 32 bytes + +The gas cost calculation is modified from: + +```python +def calculate_multiplication_complexity(base_length, modulus_length): + max_length = max(base_length, modulus_length) + words = math.ceil(max_length / 8) + return words**2 +``` + +to: + +```python +def calculate_multiplication_complexity(base_length, modulus_length): + max_length = max(base_length, modulus_length) + words = math.ceil(max_length / 8) + multiplication_complexity = 16 + if max_length > 32: multiplication_complexity = 2 * words**2 + return multiplication_complexity +``` + +This change introduces a minimal multiplication complexity of 16 and doubles the complexity if the base or modulus length exceeds 32 bytes. + +## 5. Rationale + +Benchmarking the `ModExp` precompile revealed several scenarios where its gas cost was significantly underestimated. Pricing adjustments are designed to rectify underpriced edge cases by modifying the existing `ModExp` pricing formula parameters. Specifically, the minimum cost for `ModExp` will rise from 200 to 500 (a 150% increase), the general cost will triple (a 200% increase), a minimum base/modulus length of 32 bytes will be assumed and the cost will scale more aggressively when the base, modulus, or exponent exceed 32 bytes. These modifications aim to ensure that the `ModExp` precompile's performance, even in its most resource-intensive edge cases across all execution layer clients, no longer impedes potential increases to the block gas limit. + +## 6. Backwards Compatibility + +This BEP introduces a backwards-incompatible change. However, similar gas repricings have occurred multiple times in the Ethereum ecosystem, and their effects are well understood. + +An empirical analysis of this proposal is available [here](https://github.com/ethereum/EIPs/blob/master/assets/eip-7883/call_analysis.md), with a separate breakdown by affected entities provided [here](https://github.com/ethereum/EIPs/blob/master/assets/eip-7883/entity_analysis.md). + +## 7. Test Cases + +The most common usages (approximately 99.69% of historical `Modexp` calls as of January 4th, 2025) will experience either a 150% increase (from 200 to 500 gas) or a 200% increase (tripling from approximately 1360 gas). +No changes are made to the underlying interface or arithmetic algorithms, allowing existing test vectors to be reused. The table below presents the updated gas costs for these test vectors: + +| Test Case | [EIP-2565](https://eips.ethereum.org/EIPS/eip-2565) Pricing | EIP-7883 Pricing | Increase | +|------------------------------|-----|-----|----| +| modexp_nagydani_1_square | 200 | 500 | 150% | +| modexp_nagydani_1_qube | 200 | 500 | 150% | +| modexp_nagydani_1_pow0x10001 | 341 | 2048 | 501% | +| modexp_nagydani_2_square | 200 | 512 | 156% | +| modexp_nagydani_2_qube | 200 | 512 | 156% | +| modexp_nagydani_2_pow0x10001 | 1365 | 8192 | 501% | +| modexp_nagydani_3_square | 341 | 2048 | 501% | +| modexp_nagydani_3_qube | 341 | 2048 | 501% | +| modexp_nagydani_3_pow0x10001 | 5461 | 32768 | 500% | +| modexp_nagydani_4_square | 1365 | 8192 | 501% | +| modexp_nagydani_4_qube | 1365 | 8192 | 501% | +| modexp_nagydani_4_pow0x10001 | 21845 | 131072 | 500% | +| modexp_nagydani_5_square | 5461 | 32768 | 500% | +| modexp_nagydani_5_qube | 5461 | 32768 | 500% | +| modexp_nagydani_5_pow0x10001 | 87381 | 524288 | 500% | +| modexp_marius_1_even | 2057 | 45296 | 2102% | +| modexp_guido_1_even | 2298 | 51136 | 2125% | +| modexp_guido_2_even | 2300 | 51152 | 2124% | +| modexp_guido_3_even | 5400 | 32400 | 500% | +| modexp_guido_4_even | 1026 | 94448 | 9105% | +| modexp_marcin_1_base_heavy | 200 | 1152 | 476% | +| modexp_marcin_1_exp_heavy | 215 | 16624 | 7632% | +| modexp_marcin_1_balanced | 200 | 1200 | 500% | +| modexp_marcin_2_base_heavy | 867 | 5202 | 500% | +| modexp_marcin_2_exp_heavy | 852 | 16368 | 1821% | +| modexp_marcin_2_balanced | 996 | 5978 | 500% | +| modexp_marcin_3_base_heavy | 677 | 2032 | 200% | +| modexp_marcin_3_exp_heavy | 765 | 4080 | 433% | +| modexp_marcin_3_balanced | 1360 | 4080 | 200% | + +## 8. Security Considerations + +This BEP does not introduce any new functionality or make existing operations cheaper, therefore there are no direct security concerns related to new attack vectors or reduced costs. The primary security consideration for this BEP is the potential for `ModExp` scenarios to be overpriced, though this is deemed a lesser risk compared to the current underpricing issues. + +## 9. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-654.md b/BEPs/BEP-654.md new file mode 100644 index 000000000..be0644a34 --- /dev/null +++ b/BEPs/BEP-654.md @@ -0,0 +1,203 @@ +
+  BEP: 654
+  Title: Implement EIP-7939: Count Leading Zeros (CLZ) Opcode
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-21
+  Description: Add CLZ opcode to count the number of leading zero bits in a 256-bit word
+
+ +# BEP-654: Implement EIP-7939: Count Leading Zeros (CLZ) Opcode + +- [BEP-654: Implement EIP-7939: Count Leading Zeros (CLZ) Opcode](#bep-654-implement-eip-7939-count-leading-zeros-clz-opcode) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [4. Rationale](#4-rationale) + - [The Special Zero Case](#the-special-zero-case) + - [Preference over `CTZ` (Count Trailing Zeros)](#preference-over-ctz-count-trailing-zeros) + - [Gas Cost](#gas-cost) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [6. Test Cases](#6-test-cases) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + +## 1. Summary + +Introduce a new opcode, `CLZ(x)`, which pops `x` from the stack and pushes the number of leading zero bits in `x` to the stack. If `x` is zero, pushes 256. + +## 2. Motivation + +Count leading zeros (CLZ) is a native opcode in many processor architectures (even in RISC architectures like ARM). + +It is a basic building block used in math operations, byte operations, compression algorithms, data structures: + +- lnWad +- powWad +- lambertW0Wad +- sqrt +- cbrt +- byte string comparisons +- generalized calldata compression/decompression +- bitmaps (for finding the next/previous set/unset bit) +- post quantum signature schemes + +Adding a `CLZ` opcode will: + +- Lead to cheaper compute. +- Lead to cheaper ZK proving costs. The fastest known Solidity implementation uses several dynamic bitwise right shifts `shr`, which are very expensive to prove. In SP1 rv32im, a 32-bit right shift costs 1.6x more than a 32-bit mul. +- Lead to smaller bytecode size. The fastest known Solidity implementation contains several large constants and is often inlined for performance. + +## 3. Specification + +A new opcode is introduced: `CLZ` (`0x1e`). + +- Pops 1 value from the stack. +- Pushes a value to the stack, according to the following code: + +```solidity +/// @dev Count leading zeros. +/// Returns the number of zeros preceding the most significant one bit. +/// If `x` is zero, returns 256. +/// This is the fastest known `CLZ` implementation in Solidity and uses about 184 gas. +function clz(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // forgefmt: disable-next-item + r := add(xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), + 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)), iszero(x)) + } +} +``` + +Or in Python, + +```python +def clz(x): + """Returns the number of zeros preceding the most significant one bit.""" + if x < 0: + raise ValueError("clz is undefined for negative numbers") + if x > 2**256 - 1: + raise ValueError("clz is undefined for numbers larger than 2**256 - 1") + if x == 0: + return 256 + # Convert to binary string and remove any '0b' prefix. + bin_str = bin(x).replace('0b', '') + return 256 - len(bin_str) +``` + +Or in C++, + +```c++ +inline uint32_t clz(uint32_t x) { + uint32_t r = 0; + if (!(x & 0xFFFF0000)) { r += 16; x <<= 16; } + if (!(x & 0xFF000000)) { r += 8; x <<= 8; } + if (!(x & 0xF0000000)) { r += 4; x <<= 4; } + if (!(x & 0xC0000000)) { r += 2; x <<= 2; } + if (!(x & 0x80000000)) { r += 1; } + return r; +} + +// `x` is a uint256 bit number represented with 8 uint32 limbs. +// This implementation is optimized for SP1 proving via rv32im. +// For regular compute, it performs similarly to `ADD`. +inline uint32_t clz(uint32_t x[8]) { + if (x[7] != 0) return clz(x[7]); + if (x[6] != 0) return 32 + clz(x[6]); + if (x[5] != 0) return 64 + clz(x[5]); + if (x[4] != 0) return 96 + clz(x[4]); + if (x[3] != 0) return 128 + clz(x[3]); + if (x[2] != 0) return 160 + clz(x[2]); + if (x[1] != 0) return 192 + clz(x[1]); + if (x[0] != 0) return 224 + clz(x[0]); + return 256; +} +``` + +The cost of the opcode is 5, matching MUL (raised from 3 to avoid under-pricing DoS risk). + +## 4. Rationale + +### The Special Zero Case + +256 is the smallest number after 255. Returning a small number allows the result to be compared with minimal additional bytecode. + +For byte scanning operations, one can get the number of bytes to be skipped for a zero word by simply computing `256 >> 3`, which gives 32. + +### Preference over `CTZ` (Count Trailing Zeros) + +Computing the least significant bit can be easily implemented with `CLZ` by isolating the smallest bit via `x & -x`. + +However, it is not possible to implement `CLZ` with `CTZ`. + +### Gas Cost + +We have benchmarked the `CLZ` implementation against the `ADD` implementation in the intx library. `CLZ` uses approximately the same amount of compute cycles as `ADD`. + +The SP1 rv32im optimized variant uses less compute cycles than `ADD`, in the average and worst cases. + +In SP1 rv32im, a 256-bit `CLZ` is cheaper to prove than `ADD`. + +## 5. Backwards Compatibility + +This is a new opcode not present prior. + +## 6. Test Cases + +``` +PUSH32 0x000000000000000000000000000000000000000000000000000000000000000 +CLZ +--- +0x0000000000000000000000000000000000000000000000000000000000000100 +``` + +``` +PUSH32 0x8000000000000000000000000000000000000000000000000000000000000000 +CLZ +--- +0x0000000000000000000000000000000000000000000000000000000000000000 +``` + +``` +PUSH32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +CLZ +--- +0x0000000000000000000000000000000000000000000000000000000000000000 +``` + +``` +PUSH32 0x4000000000000000000000000000000000000000000000000000000000000000 +CLZ +--- +0x0000000000000000000000000000000000000000000000000000000000000001 +``` + +``` +PUSH32 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +CLZ +--- +0x0000000000000000000000000000000000000000000000000000000000000001 +``` + +``` +PUSH32 0x0000000000000000000000000000000000000000000000000000000000000001 +CLZ +--- +0x00000000000000000000000000000000000000000000000000000000000000ff +``` + +## 7. Security Considerations + +`CLZ` is a stateless opcode that has a low worst-case constant cost in memory usage, compute and proving costs. It is therefore safe from being exploited for denial of service attacks. + +## 8. License + +All content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + + diff --git a/BEPs/BEP-655.md b/BEPs/BEP-655.md new file mode 100644 index 000000000..4587c2938 --- /dev/null +++ b/BEPs/BEP-655.md @@ -0,0 +1,80 @@ +
+  BEP: 655
+  Title: Implement EIP-7934 RLP Execution Block Size Limit
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-20
+  Description: Introduce a protocol-level cap on the maximum RLP-encoded block size to 8 MiB
+
+ +# BEP-655: Implement EIP-7934 RLP Execution Block Size Limit + +- [BEP-655: Implement EIP-7934 RLP Execution Block Size Limit](#bep-655-implement-eip-7934-rlp-execution-block-size-limit) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [Block Size Cap](#block-size-cap) + - [Changes to Protocol Behavior](#changes-to-protocol-behavior) + - [Protocol Adjustment](#protocol-adjustment) + - [5. Backwards Compatibility](#6-backwards-compatibility) + - [6. Security Considerations](#7-security-considerations) + - [7. License](#8-license) + +## 1. Summary + +This BEP introduces a protocol-level cap on the maximum RLP-encoded execution block size to 8 MiB on BSC, since the blob sidecar is not counted as part of the block size. + +## 2. Abstract + +This proposal introduces a protocol-level cap on the maximum RLP-encoded execution block size. The Ethereum community sets this limit to 10 megabytes (MiB), which includes a margin of 2 MiB to account for beacon block sizes. BSC adopts a limit of 8 MiB for the execution block size. + +## 3. Motivation + +Currently, BSC does not enforce a strict upper limit on the encoded size of blocks. This lack of constraint can result in: + +1. **Network Instability**: Extremely large blocks slow down propagation and increase the risk of temporary forks and reorgs. +2. **DoS Risks**: Malicious actors could generate exceptionally large blocks to disrupt network performance. + +Additionally, blocks exceeding 10 MiB are not propagated by the consensus layer's (CL) gossip protocol, potentially causing network fragmentation or denial-of-service (DoS) conditions. + +By imposing a protocol-level limit on the RLP-encoded block size, BSC can ensure enhanced resilience against targeted attacks on block validation times. Adding an additional margin of 2MiB explicitly accommodates beacon block sizes, ensuring compatibility across network components. + +## 4. Specification + +### Block Size Cap + +- Introduce constants: + - `MAX_RLP_BLOCK_SIZE` set to **8 MiB (8,388,608 bytes)** +- Any RLP-encoded block exceeding `MAX_RLP_BLOCK_SIZE` must be considered invalid. + +Thus add the following check to the protocol: + +```python + +# if true, the block is invalid and should be rejected/not get built +def exceed_max_rlp_block_size(block: Block) -> bool: + return len(rlp.encode(block)) > MAX_RLP_BLOCK_SIZE +``` + +### Changes to Protocol Behavior + +1. **Block Creation**: Validators must ensure the total RLP-encoded size of any produced block does not exceed `MAX_RLP_BLOCK_SIZE`. +2. **Block Validation**: Nodes must reject blocks whose RLP-encoded size exceeds `MAX_RLP_BLOCK_SIZE`. + +### Protocol Adjustment + +- All BSC client implementations must integrate this size check as part of block validation and propagation. +- This limit applies independently of gas-related metrics. + +## 5. Backwards Compatibility + +This change is **not backward-compatible** with any blocks larger than the newly specified size limit. Validators and miners will need to ensure their block construction logic strictly respects this limit. + +## 6. Security Considerations + +Restricting maximum block size provides inherent protection against deliberate oversized-block attacks. + +## 7. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP-656.md b/BEPs/BEP-656.md new file mode 100644 index 000000000..938d95620 --- /dev/null +++ b/BEPs/BEP-656.md @@ -0,0 +1,346 @@ +
+  BEP: 656
+  Title: Implement EIP-7910: eth_config JSON-RPC Method
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-21
+  Description: A JSON-RPC method that describes the configuration of the current and next fork
+
+ +# BEP-656: Implement EIP-7910: eth_config JSON-RPC Method + +- [BEP-656: Implement EIP-7910: eth_config JSON-RPC Method](#bep-656-implement-eip-7910-eth_config-json-rpc-method) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [Target Audience and Use Cases](#target-audience-and-use-cases) + - [3. Specification](#3-specification) + - [Configuration RPC](#configuration-rpc) + - [Result Object Structure](#result-object-structure) + - [Members of the Configuration Object](#members-of-the-configuration-object) + - [`activationTime`](#activationtime) + - [`blobSchedule`](#blobschedule) + - [`chainId`](#chainid) + - [`forkId`](#forkid) + - [`precompiles`](#precompiles) + - [`systemContracts`](#systemcontracts) + - [4. Rationale](#4-rationale) + - [5. Backwards Compatibility](#5-backwards-compatibility) + - [6. Test Cases](#6-test-cases) + - [With Future Fork Scheduled](#with-future-fork-scheduled) + - [Without Future Fork Scheduled](#without-future-fork-scheduled) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + +## 1. Summary + +This document describes an RPC method that provides node-relevant configuration data for the current, next, and last known forks. + +## 2. Motivation + +By providing an RPC method that allows clients to report key configuration variables before the next hard fork, operations teams can gain greater confidence that clients are correctly configured and prepared for upcoming forks. + +### Target Audience and Use Cases + +This method is intended for node operators, validator teams, and network monitoring tools to verify client readiness for upcoming forks. Use cases include: + +- Automated pre-fork validation scripts comparing `eth_config` outputs across nodes. +- Manual checks by validator operators to ensure alignment with fork specifications. +- Debugging by client developers to identify configuration mismatches. +- Automated checks by Consensus Layer counterparties. + +## 3. Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Clients MUST expose a new RPC method to report the current functional configuration and the expected next configuration via the standard JSON-RPC port. + +Clients MAY also expose this method through the Engine API. + +Clients MAY use these configuration objects to manage their per-fork configurations, though they SHOULD NOT simply return unprocessed configuration data. + +When reporting the current, next and last configurations, clients MUST include every configuration parameter specified in this BEP. + +Clients MUST return up-to-date configuration values, reflecting the most recent block header they provide. If clients cache the configuration, they MUST ensure such caches are purged when fork boundaries are crossed. + +### Configuration RPC + +A new JSON-RPC API, `eth_config`, is introduced. It takes no parameters and returns the result object specified in the next section. + +### Result Object Structure + +The RPC response contains three members: "current", "next", and "last". These members contain the configuration object currently in effect, the next configuration, and the last known configuration, respectively. "next" and "last" will be `null` if the client is not configured to support a future fork. "next" and "last" members will contain the same configuration in the case where the next configured fork is also the last configured fork. + +### Members of the Configuration Object + +Each configuration object MUST contain the following members, presented in alphabetical order. This RPC assumes the network is post-merge, and no accommodations are specified for proof-of-work-related issues. + +Future forks may add, adjust, remove, or update members. The respective changes MUST be defined in either their BEPs or their respective meta-BEPs. Added members MUST be alphabetically sorted, so simply naming the new members is sufficient definition. + +#### `activationTime` + +The fork activation timestamp, represented as a JSON number in Unix epoch seconds (UTC). For the "current" configuration, this reflects the actual activation time; for "next" and "last", it is the scheduled time. + +Activation time is required. If a fork is activated at genesis, the value `0` is used. If the fork is not scheduled to be activated or its activation time is unknown, it should not be in the RPC results. + +#### `blobSchedule` + +The blob configuration parameters for the specific fork, as defined in the genesis file. This is a JSON object with three members—`baseFeeUpdateFraction`, `max`, and `target`—all represented as JSON numbers. + +#### `chainId` + +The chain ID of the current network, presented as a string with an unsigned `0x`-prefixed hexadecimal number, with all leading zeros removed, in lower case. This specification does not support chains without a chain ID or with a chain ID of zero. + +For purposes of canonicalization, this value must always be a string. + +#### `forkId` + +The `FORK_HASH` value as specified in [EIP-6122](https://eips.ethereum.org/EIPS/eip-6122) of the specific fork, presented as an unsigned `0x`-prefixed hexadecimal number, with zeros left-padded to a four-byte length, in lower case. + +#### `precompiles` + +A representation of the active precompile contracts for the fork. If a precompiled contract is replaced by an on-chain contract—or removed—then it is not included. + +This is a JSON object where the members are the agreed-upon names for each contract, typically specified in the BEP defining that contract, and the values are the 20-byte `0x`-prefixed hexadecimal addresses of the precompiles (with zeros preserved), in lower case. + +#### `systemContracts` + +A JSON object representing system-level contracts relevant to the fork, as introduced in their defining BEPs. Keys are the contract names (e.g., `HISTORY_STORAGE_ADDRESS`) from the first BEP where they appeared, sorted alphabetically. Values are 20-byte addresses in `0x`-prefixed hexadecimal form, with leading zeros preserved, in lower case. Omitted for forks before Cancun. + +For Prague, the system contracts are (in order): `HISTORY_STORAGE_ADDRESS`. + +## 4. Rationale + +### Why Three Time Horizons? + +Providing three configurations—current, next, and last—allows clients to: +- **current**: Immediately validate active fork parameters against operational expectations. +- **next**: Verify readiness for the immediately upcoming fork. +- **last**: Confirm long-term configuration alignment. + +This approach balances operational needs (near-term validation) with strategic planning (long-term roadmap verification). + +### Why Not Include All Future Forks? + +Limiting the response to "next" and "last" reduces payload size and simplifies validation logic. Most operational issues arise from misconfiguration of the immediate next fork. Including all future forks would add complexity without proportional benefit, as far-future forks often lack finalized parameters. + +### Standardization and Consistency + +By mandating that all configuration parameters follow a consistent alphabetical ordering and naming convention, this method ensures: +- **Interoperability**: Different client implementations can be easily compared. +- **Predictability**: Tooling can parse responses without client-specific logic. +- **Extensibility**: New forks can add parameters without breaking existing parsers. + +## 5. Backwards Compatibility + +This BEP introduces a new RPC method without modifying existing ones. Clients that do not implement `eth_config` will simply not expose the endpoint, causing no disruption to existing infrastructure. + +Monitoring tools and scripts should gracefully handle the absence of `eth_config` on older clients. + +## 6. Test Cases + +### With Future Fork Scheduled + +An example request and response when a future fork (Prague) is configured: + +```JSON +{ + "jsonrpc": "2.0", + "id": 1, + "method": "eth_config", + "params": [] +} +``` + +Response: + +```JSON +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "current": { + "activationTime": 0, + "blobSchedule": { + "baseFeeUpdateFraction": 3338477, + "max": 6, + "target": 3 + }, + "chainId": "0x38", + "forkId": "0xbef71d30", + "precompiles": { + "BLAKE2F": "0x0000000000000000000000000000000000000009", + "BLS12_G1ADD": "0x000000000000000000000000000000000000000b", + "BLS12_G1MSM": "0x000000000000000000000000000000000000000c", + "BLS12_G2ADD": "0x000000000000000000000000000000000000000d", + "BLS12_G2MSM": "0x000000000000000000000000000000000000000e", + "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011", + "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010", + "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f", + "BLS_SIGNATURE_VERIFY": "0x0000000000000000000000000000000000000066", + "BN254_ADD": "0x0000000000000000000000000000000000000006", + "BN254_MUL": "0x0000000000000000000000000000000000000007", + "BN254_PAIRING": "0x0000000000000000000000000000000000000008", + "COMET_BFT_LIGHT_BLOCK_VALIDATE_HERTZ": "0x0000000000000000000000000000000000000067", + "ECREC": "0x0000000000000000000000000000000000000001", + "HEADER_VALIDATE": "0x0000000000000000000000000000000000000064", + "IAVL_MERKLE_PROOF_VALIDATE_PLATO": "0x0000000000000000000000000000000000000065", + "ID": "0x0000000000000000000000000000000000000004", + "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a", + "MODEXP": "0x0000000000000000000000000000000000000005", + "P256VERIFY": "0x0000000000000000000000000000000000000100", + "RIPEMD160": "0x0000000000000000000000000000000000000003", + "SECP256K1_SIGNATURE_RECOVER": "0x0000000000000000000000000000000000000069", + "SHA256": "0x0000000000000000000000000000000000000002", + "VERIFY_DOUBLE_SIGN_EVIDENCE": "0x0000000000000000000000000000000000000068" + }, + "systemContracts": { + "HISTORY_STORAGE_ADDRESS": "0x0000f90827f1c53a10cb7a02335b175320002935" + } + }, + "next": { + "activationTime": 1742999832, + "blobSchedule": { + "baseFeeUpdateFraction": 5007716, + "max": 9, + "target": 6 + }, + "chainId": "0x38", + "forkId": "0x0929e24e", + "precompiles": { + "BLAKE2F": "0x0000000000000000000000000000000000000009", + "BLS12_G1ADD": "0x000000000000000000000000000000000000000b", + "BLS12_G1MSM": "0x000000000000000000000000000000000000000c", + "BLS12_G2ADD": "0x000000000000000000000000000000000000000d", + "BLS12_G2MSM": "0x000000000000000000000000000000000000000e", + "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011", + "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010", + "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f", + "BLS_SIGNATURE_VERIFY": "0x0000000000000000000000000000000000000066", + "BN254_ADD": "0x0000000000000000000000000000000000000006", + "BN254_MUL": "0x0000000000000000000000000000000000000007", + "BN254_PAIRING": "0x0000000000000000000000000000000000000008", + "COMET_BFT_LIGHT_BLOCK_VALIDATE_HERTZ": "0x0000000000000000000000000000000000000067", + "ECREC": "0x0000000000000000000000000000000000000001", + "HEADER_VALIDATE": "0x0000000000000000000000000000000000000064", + "IAVL_MERKLE_PROOF_VALIDATE_PLATO": "0x0000000000000000000000000000000000000065", + "ID": "0x0000000000000000000000000000000000000004", + "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a", + "MODEXP": "0x0000000000000000000000000000000000000005", + "P256VERIFY": "0x0000000000000000000000000000000000000100", + "RIPEMD160": "0x0000000000000000000000000000000000000003", + "SECP256K1_SIGNATURE_RECOVER": "0x0000000000000000000000000000000000000069", + "SHA256": "0x0000000000000000000000000000000000000002", + "VERIFY_DOUBLE_SIGN_EVIDENCE": "0x0000000000000000000000000000000000000068" + }, + "systemContracts": { + "HISTORY_STORAGE_ADDRESS": "0x0000f90827f1c53a10cb7a02335b175320002935" + } + }, + "last": { + "activationTime": 1742999832, + "blobSchedule": { + "baseFeeUpdateFraction": 5007716, + "max": 9, + "target": 6 + }, + "chainId": "0x38", + "forkId": "0x0929e24e", + "precompiles": { + "BLAKE2F": "0x0000000000000000000000000000000000000009", + "BLS12_G1ADD": "0x000000000000000000000000000000000000000b", + "BLS12_G1MSM": "0x000000000000000000000000000000000000000c", + "BLS12_G2ADD": "0x000000000000000000000000000000000000000d", + "BLS12_G2MSM": "0x000000000000000000000000000000000000000e", + "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011", + "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010", + "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f", + "BLS_SIGNATURE_VERIFY": "0x0000000000000000000000000000000000000066", + "BN254_ADD": "0x0000000000000000000000000000000000000006", + "BN254_MUL": "0x0000000000000000000000000000000000000007", + "BN254_PAIRING": "0x0000000000000000000000000000000000000008", + "COMET_BFT_LIGHT_BLOCK_VALIDATE_HERTZ": "0x0000000000000000000000000000000000000067", + "ECREC": "0x0000000000000000000000000000000000000001", + "HEADER_VALIDATE": "0x0000000000000000000000000000000000000064", + "IAVL_MERKLE_PROOF_VALIDATE_PLATO": "0x0000000000000000000000000000000000000065", + "ID": "0x0000000000000000000000000000000000000004", + "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a", + "MODEXP": "0x0000000000000000000000000000000000000005", + "P256VERIFY": "0x0000000000000000000000000000000000000100", + "RIPEMD160": "0x0000000000000000000000000000000000000003", + "SECP256K1_SIGNATURE_RECOVER": "0x0000000000000000000000000000000000000069", + "SHA256": "0x0000000000000000000000000000000000000002", + "VERIFY_DOUBLE_SIGN_EVIDENCE": "0x0000000000000000000000000000000000000068" + }, + "systemContracts": { + "HISTORY_STORAGE_ADDRESS": "0x0000f90827f1c53a10cb7a02335b175320002935" + } + } + } +} +``` + +### Without Future Fork Scheduled + +When no future forks are configured, the same RPC command would return: + +```JSON +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "current": { + "activationTime": 0, + "blobSchedule": { + "baseFeeUpdateFraction": 3338477, + "max": 6, + "target": 3 + }, + "chainId": "0x38", + "forkId": "0xbef71d30", + "precompiles": { + "BLAKE2F": "0x0000000000000000000000000000000000000009", + "BLS12_G1ADD": "0x000000000000000000000000000000000000000b", + "BLS12_G1MSM": "0x000000000000000000000000000000000000000c", + "BLS12_G2ADD": "0x000000000000000000000000000000000000000d", + "BLS12_G2MSM": "0x000000000000000000000000000000000000000e", + "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011", + "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010", + "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f", + "BLS_SIGNATURE_VERIFY": "0x0000000000000000000000000000000000000066", + "BN254_ADD": "0x0000000000000000000000000000000000000006", + "BN254_MUL": "0x0000000000000000000000000000000000000007", + "BN254_PAIRING": "0x0000000000000000000000000000000000000008", + "COMET_BFT_LIGHT_BLOCK_VALIDATE_HERTZ": "0x0000000000000000000000000000000000000067", + "ECREC": "0x0000000000000000000000000000000000000001", + "HEADER_VALIDATE": "0x0000000000000000000000000000000000000064", + "IAVL_MERKLE_PROOF_VALIDATE_PLATO": "0x0000000000000000000000000000000000000065", + "ID": "0x0000000000000000000000000000000000000004", + "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a", + "MODEXP": "0x0000000000000000000000000000000000000005", + "P256VERIFY": "0x0000000000000000000000000000000000000100", + "RIPEMD160": "0x0000000000000000000000000000000000000003", + "SECP256K1_SIGNATURE_RECOVER": "0x0000000000000000000000000000000000000069", + "SHA256": "0x0000000000000000000000000000000000000002", + "VERIFY_DOUBLE_SIGN_EVIDENCE": "0x0000000000000000000000000000000000000068" + }, + "systemContracts": { + "BEACON_ROOTS_ADDRESS": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02" + } + }, + "next": null, + "last": null + } +} +``` + +## 7. Security Considerations + +- **Exposure Risks**: Incorrect configurations could leak operational details. Operators SHOULD restrict `eth_config` to trusted interfaces (e.g., local access or authenticated endpoints). +- **Dishonest Nodes**: Clients may report false configurations. Peers or monitoring tools MAY cross-check `eth_config` outputs against known fork specifications or other nodes' responses to detect anomalies. +- **DDoS Mitigation**: Clients MAY cache configuration objects internally and rate-limit `eth_config` requests to prevent resource exhaustion. Implementations MAY impose a minimum response interval (e.g., 1 second). + +## 8. License + +All content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + + diff --git a/BEPs/BEP-657.md b/BEPs/BEP-657.md new file mode 100644 index 000000000..4bddab695 --- /dev/null +++ b/BEPs/BEP-657.md @@ -0,0 +1,75 @@ +
+  BEP: 657
+  Title: Limit Blob Transaction Inclusion by Block Number
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-21
+  Description: Restrict blob transactions to blocks where block number modulo N equals zero. Initial N=5.
+
+ +# BEP-657: Limit Blob Transaction Inclusion by Block Number + +- [BEP-657: Limit Blob Transaction Inclusion by Block Number](#bep-657-limit-blob-transaction-inclusion-by-block-number) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [4. Rationale](#4-rationale) + - [5. Backward Compatibility](#5-backward-compatibility) + - [6. License](#6-license) + +## 1. Summary + +This BEP restricts blob transaction inclusion to blocks where the block number modulo N equals zero. **The initial value of N is set to 5**, allowing blob transactions in blocks 0, 5, 10, 15, etc. Non-eligible blocks preserve blob fee state from their parent to maintain market continuity. + +## 2. Motivation + +BSC's block time has been reduced from 3 seconds to 0.45 seconds, yet blob transaction volume has remained relatively constant at approximately one per 7-8 blocks. This mismatch has resulted in severe blob space oversupply. + +**Blob Fee Market Dysfunction**: The ~6.7x increase in blob capacity with unchanged demand has caused the blob base fee to consistently remain at its minimum floor price. This prevents the EIP-4844 fee market mechanism from functioning properly, as it relies on supply-demand dynamics for price discovery. + +By restricting blob transactions to every Nth block (blocks where `blockNumber % N == 0`), this BEP concentrates demand to restore proper fee market dynamics while maintaining adequate capacity for current usage patterns. **The initial value of N is set to 5**, meaning blob transactions can only be included in blocks 0, 5, 10, 15, etc. With 0.45s block times, the maximum inclusion delay of 2.25 seconds has minimal impact on L2 operations. + +## 3. Specification + +### 3.1 Blob Transaction Inclusion Rules + +Define a parameter N that determines the frequency of eligible blocks. **The initial value of N is 5.** + +For any block with block number `blockNumber`: +- If `blockNumber % N == 0`: The block MAY contain blob transactions +- If `blockNumber % N != 0`: The block MUST NOT contain any blob transactions + +Blocks violating this rule MUST be rejected as invalid. + +With N=5, eligible blocks are: 0, 5, 10, 15, 20, 25, 30, etc. + +### 3.2 Blob Fee Calculation Modification + +**For blocks where `blockNumber % N == 1`:** +- Normal EIP-4844 blob fee calculation applies + +**For blocks where `blockNumber % N != 1`:** +- `header.ExcessBlobGas` MUST equal `parent.ExcessBlobGas` + +This ensures the blob fee is calculated once after each eligible block, then preserved across subsequent blocks until the next calculation. + +## 4. Rationale + +The modulo N restriction (1 in every N blocks) aligns with current demand patterns. **This BEP sets N=5 as the initial value.** + +* **Fee Market Alignment**: Current usage (~1 blob tx per 7-8 blocks) naturally fits within the 1-in-5 schedule, enabling proper EIP-4844 fee mechanism operation while providing room for demand growth. +* **Minimal User Impact**: With 0.45s block time, maximum inclusion delay is 2.25 seconds, negligible for L2 sequencers posting data every 30-60 seconds. +* **Fee Continuity**: Non-eligible blocks inherit blob fee state from their parent, preserving market state across the 4-block gap and enabling proper price discovery at the next eligible block. +* **Adjustable Parameter**: N can be adjusted in future upgrades to adapt to changing demand patterns without requiring fundamental changes to the mechanism. + +## 5. Backward Compatibility + +This is a consensus-breaking change requiring a hard fork. All validators and full nodes must upgrade before activation. + +Transaction submitters must ensure blob transactions target eligible blocks (blocks where `blockNumber % N == 0`). **With N=5, eligible blocks are 0, 5, 10, 15, 20, etc.** Blob-related MEV opportunities will concentrate in these eligible blocks. + +## 6. License + +This document is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + + diff --git a/BEPs/BEP-658.md b/BEPs/BEP-658.md new file mode 100644 index 000000000..807a3232e --- /dev/null +++ b/BEPs/BEP-658.md @@ -0,0 +1,71 @@ +
+  BEP: 658
+  Title: BEP-658: Hardfork Meta-Osaka/Mendel
+  Status: Draft
+  Type: Information
+  Created: 2026-01-22
+  Description: BEPs included in the Osaka/Mendel BSC network upgrade.
+
+ + +## 1. Summary + +This Meta BEPs lists the BEPs formally Scheduled for Inclusion in the Osaka/Mendel network upgrade. + +## Specification + +The Mendel network upgrade comprises a total of 9 BEPs. Out of the 13 EIPs introduced in Ethereum's Fusaka scope, BSC has adopted 7 EIPs (6 requiring a hard fork and 1 as a client-side RPC update) while rejecting the remaining 6 EIPs due to architectural differences. Furthermore, the upgrade introduces two BSC-exclusive enhancements: BEP-657, which limits blob transaction inclusion by block number, and BEP-648, designed to reduce latency for Fast Finality. + +### BEPs Scheduled for Inclusion + +#### BEPs need hard fork + +* [BEP-651](./BEP-651.md): Implement EIP-7823 Set upper bounds for MODEXP + * follow the raw specification in [EIP-7823](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7823.md) +* [BEP-652](./BEP-652.md): Implement EIP-7825 Transaction Gas Limit Cap + * follow the raw specification in [EIP-7825](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7825.md) +* [BEP-653](./BEP-653.md): Implement EIP-7883 ModExp Gas Cost Increase + * follow the raw specification in [EIP-7883](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7883.md) +* [BEP-654](./BEP-654.md): Implement EIP-7939 Count Leading Zeros (CLZ) Opcode + * follow the raw specification in [EIP-7939](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7939.md) +* [BEP-655](./BEP-655.md): Implement EIP-7934 RLP Execution Block Size Limit + * there is no beacon client in BSC, so just limit RLP Execution Block Size to 8M to by following the raw specification in [EIP-7934](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7934.md) +* [BEP-657](./BEP-657.md): Limit Blob Transaction Inclusion by Block Number + * BSC Only +* [BEP-659](./BEP-659.md): Implement EIP-7951 Precompile for secp256r1 Curve Support + * have implement by [BEP-381](./BEP-381.md) in BSC Haber hard fork, now change the gas cost by following the raw specification in [EIP-7951](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7951.md) + + +#### BEPs without hard fork + +* [BEP-648](./BEP-648.md): Enhanced Fast Finality via In-Memory Voting Pool + * BSC Only +* [BEP-656](./BEP-656.md): Implement EIP-7910: eth_config JSON-RPC Method + * Client teams MUST support this JSON-RPC method by the activation of Osaka/Mendel network upgrade. + +#### Rejected EIPs defined in [Fusaka](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7607.md) + +* [EIP-7642](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7642.md): eth/69 - Drop pre-merge fields + * eth/69 is not supported in BSC +* [EIP-7594](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7594.md): PeerDAS - Peer Data Availability Sampling + * not need in BSC +* [EIP-7892](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7892.md): Blob Parameter Only Hardforks + * not need in BSC +* [EIP-7917](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7917.md): Deterministic proposer lookahead + * proposer in BSC is already deterministic +* [EIP-7918](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7918.md): Blob base fee bounded by execution cost + * base fee in BSC is always 0 +* [EIP-7935](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7935.md): Set default gas limit to 60M + * not really need in BSC + +## Rationale + +This Meta EIP provides a global view of all changes included in the Osaka/Mendel network upgrade, as well as links to full specification. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP-659.md b/BEPs/BEP-659.md new file mode 100644 index 000000000..3bdb71dcd --- /dev/null +++ b/BEPs/BEP-659.md @@ -0,0 +1,267 @@ +
+  BEP: 659
+  Title: Implement EIP-7951 Precompile for secp256r1 Curve Support
+  Status: Draft
+  Type: Standards
+  Created: 2026-01-20
+  Description: Add precompiled contract for secp256r1 ECDSA signature verification with proper security checks
+
+ +# BEP-659: Implement EIP-7951 Precompile for secp256r1 Curve Support + +- [BEP-659: Implement EIP-7951 Precompile for secp256r1 Curve Support](#bep-659-implement-eip-7951-precompile-for-secp256r1-curve-support) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [Precompile](#precompile) + - [Curve Parameters](#curve-parameters) + - [Fields and Groups](#fields-and-groups) + - [Points and Encoding](#points-and-encoding) + - [Field Elements Encoding](#field-elements-encoding) + - [Encoding of Points in G](#encoding-of-points-in-g) + - [Point of Infinity Encoding](#point-of-infinity-encoding) + - [Encoding of Scalars](#encoding-of-scalars) + - [Behavior on Invalid Inputs](#behavior-on-invalid-inputs) + - [ABI for P256VERIFY Operation](#abi-for-p256verify-operation) + - [Input](#input) + - [Output](#output) + - [Input Validation](#input-validation) + - [Signature Verification Algorithm](#signature-verification-algorithm) + - [Error Cases](#error-cases) + - [Gas Schedule](#gas-schedule) + - [P256VERIFY operation](#p256verify-operation) + - [Gas Burning on Error](#gas-burning-on-error) + - [5. Rationale](#5-rationale) + - [Security Fixes](#security-fixes) + - [Verification vs Recovery](#verification-vs-recovery) + - [Gas Cost Justification](#gas-cost-justification) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [Interface Compatibility](#interface-compatibility) + - [7. Test Cases](#7-test-cases) + - [8. Security Considerations](#8-security-considerations) + - [Cryptographic Security](#cryptographic-security) + - [Malleability](#malleability) + - [Side-Channel Resistance](#side-channel-resistance) + - [9. License](#9-license) + +## 1. Summary + +BSC already supports functionality to efficiently perform ECDSA signature verification over the secp256r1.This BEP adopts the EIP-7951 implementation and updates the gas cost accordingly. + +## 2. Abstract + +Add functionality to efficiently perform ECDSA signature verification over the secp256r1 elliptic curve (also known as P-256 or prime256v1). This precompile enables native support for signatures generated by modern secure hardware including Apple Secure Enclave, Android Keystore, and FIDO2/WebAuthn devices. + +This specification addresses critical security issues discovered in RIP-7212 while maintaining full interface compatibility with existing Layer 2 implementations. + +## 3. Motivation + +The secp256r1 elliptic curve is a NIST-standardized curve widely supported in modern secure hardware and authentication systems. Adding native support for secp256r1 signature verification to BSC enables several important use cases that are currently impossible or prohibitively expensive. + +Modern secure hardware devices, including Apple Secure Enclave, Android Keystore, HSMs, TEEs, and FIDO2/WebAuthn authenticators, use secp256r1 for key storage and signing operations. Native secp256r1 support enables sophisticated account abstraction patterns like device-native signing, multi-factor authentication, and simplified key management - ultimately reducing friction for mainstream adoption through familiar authentication flows. + +The secp256r1 curve is already widely supported across blockchain networks and protocols, including Layer 2 networks, enterprise blockchains, and interoperability protocols. This broad compatibility enables seamless integration with existing infrastructure while maintaining security through hardware-backed signing capabilities. + +This BEP supersedes RIP-7212 by implementing the same functionality with the same interface, but without the vulnerability. + +## 4. Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Precompile + +We introduce `P256VERIFY` a precompile at the address `0x100` which performs ECDSA signature verification over the secp256r1 curve with a gas cost of `6900` gas + +### Curve Parameters + +The secp256r1 curve is fully defined by the following set of parameters: + +```text +Base field modulus = p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff +Curve equation: y^2 = x^3 + ax + b (mod p) +Curve coefficient a = 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc +Curve coefficient b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b +Base point G: + Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 + Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5 +Subgroup order = n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 +Cofactor = h = 0x1 +``` + +These parameters are standardized by NIST in SP 800-186. + +### Fields and Groups + +The field Fp is defined as the finite field of size `p` with elements represented as integers between 0 and p-1 (both inclusive). + +The group G is defined as a set of Fp pairs (points) `(x,y)` such that either `(x,y)` is `(0,0)` (representing the point at infinity) or `x,y` satisfy the curve equation `y^2 = x^3 + ax + b (mod p)`. + +### Points and Encoding + +#### Field Elements Encoding + +A base field element (Fp) is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer **must** be less than the field modulus `p`. + +#### Encoding of Points in G + +Points in G are encoded as byte concatenation of the respective encodings of the `x` and `y` coordinates. Total encoding length for a G point is thus `64` bytes. + +#### Point of Infinity Encoding + +For secp256r1, the point with coordinates `(0, 0)` (zeroes in Fp) is *not* on the curve, so a sequence of `64` zero bytes is used by convention to encode the point of infinity. + +#### Encoding of Scalars + +A scalar is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer is **not** required to be less than or equal to the subgroup order `n`. + +#### Behavior on Invalid Inputs + +On inputs that cannot be valid encodings of field elements or points, the precompile *must* return `` (failure). + +### ABI for P256VERIFY Operation + +#### Input + +`P256VERIFY` call expects `160` bytes as input that is interpreted as byte concatenation of: + +- `32` bytes: message hash `h` +- `32` bytes: signature component `r` +- `32` bytes: signature component `s` +- `32` bytes: public key x-coordinate `qx` +- `32` bytes: public key y-coordinate `qy` + +#### Output + +Output is `32` bytes on successful verification and `0` bytes on failure: + +- `0x0000000000000000000000000000000000000000000000000000000000000001` for valid signatures +- `` for invalid signatures or invalid inputs + +#### Input Validation + +The precompile MUST perform the following validation checks and return `` (failure) if any check fails: + +1. **Input length**: Input MUST be exactly `160` bytes +2. **Signature component bounds**: Both `r` and `s` MUST satisfy `0 < r < n` and `0 < s < n` +3. **Public key bounds**: Both `qx` and `qy` MUST satisfy `0 ≤ qx < p` and `0 ≤ qy < p` +4. **Point validity**: The point `(qx, qy)` MUST satisfy the curve equation `qy^2 ≡ qx^3 + a*qx + b (mod p)` +5. **Point not at infinity**: The point `(qx, qy)` MUST NOT be the point at infinity (represented as `(0, 0)`) + +#### Signature Verification Algorithm + +The verification algorithm follows these steps: + +```text +# Input validation (as specified above) +if input_length != 160: + return +if not (0 < r < n and 0 < s < n): + return +if not (0 ≤ qx < p and 0 ≤ qy < p): + return +if qy^2 ≢ qx^3 + a*qx + b (mod p): + return +if (qx, qy) == (0, 0): + return + +# Signature verification +s1 = s^(-1) (mod n) + +# Recover the random point used during signing +R' = (h * s1) * G + (r * s1) * (qx, qy) + +# Check for point at infinity +if R' is the point at infinity: + return + +# Extract x-coordinate from r +r' = R'.x + +# Compare with modular reduction +if r' ≡ r (mod n): + return 0x0000000000000000000000000000000000000000000000000000000000000001 +else: + return +``` + +#### Error Cases + +- Invalid input length (not exactly 160 bytes) +- Invalid field element encoding (≥ field modulus) +- Invalid signature component bounds (r or s not in range (0, n)) +- Invalid public key (point at infinity or not on curve) +- Signature verification failure + +### Gas Schedule + +#### P256VERIFY operation + +`6900` gas + +This cost is based on benchmarking against the existing `ECRECOVER` precompile (`3000` gas). During benchmarks we found that the actual cost of R1 verification was significantly slower than the `ECRECOVER` precompile and the decision was made to increase the gas cost to `6900` gas. + +#### Gas Burning on Error + +The precompile MUST NOT revert under any circumstances. Invalid inputs or verification failures MUST return `` and consume the same amount of gas had verification succeeded. + +## 5. Rationale + +### Security Fixes + +**Note: BSC’s previous BEP implementation already handled these cases correctly and was not impacted by the two issues described below.** + +1. **Point-at-infinity check**: The original RIP-7212 failed to check if the recovered point R' is the point at infinity. This could lead to non-deterministic behavior where the verification result depends on the underlying implementation's handling of infinity points, potentially causing consensus failures. + +2. **Modular comparison**: The original comparison `r' == r` should be `r' ≡ r (mod n)` to handle cases where the x-coordinate of R' exceeds the curve order n. This ensures mathematically correct verification according to ECDSA standards. + +### Verification vs Recovery + +This specification uses signature verification rather than public key recovery (like `ECRECOVER`) because: + +- Most secp256r1 implementations in hardware and software verify signatures directly +- The NIST FIPS 186-5 standard specifies verification, not recovery +- Verification is more efficient than recovery for this curve +- Existing hardware implementations provide verification interfaces + +### Gas Cost Justification + +The 6900 gas cost does not maintain compatibility with L2s, but it matches closer the benchmarks of actual implementations. + +## 6. Backwards Compatibility + +This BEP maintains full interface compatibility with RIP-7212 implementations deployed on Layer 2 networks. The same contract bytecode that works with RIP-7212 will work with this specification. + +The security fixes are transparent to correctly implemented callers - they only affect edge cases that should have failed verification anyway. No existing valid use cases are broken. + +### Interface Compatibility + +The precompile maintains a similar interface as RIP-7212 to ensure compatibility with existing Layer 2 deployments: + +- Same address: `0x100` +- Same input format: 160 bytes +- Same output format: 32 bytes +- Different gas cost: 3450 gas vs 6900 gas +- Same return values + +## 7. Test Cases + +A set of test vectors for verifying implementations is located in a separate [file](https://github.com/ethereum/EIPs/blob/master/assets/eip-7951/test-vectors.json). + +## 8. Security Considerations + +### Cryptographic Security + +The secp256r1 curve provides approximately 128 bits of security, equivalent to secp256k1 already in use in Ethereum. The curve parameters are standardized by NIST SP 800-186 and have undergone extensive cryptographic analysis by the wider cryptographic community in addition to this curve being deployed to several L2s in the form of RIP-7212. + +### Malleability + +Unlike secp256k1 ECDSA signatures, secp256r1 ECDSA signatures are not required to be non-malleable per NIST FIPS 186-5 standard. Applications requiring non-malleability should implement additional checks at the application layer. + +### Side-Channel Resistance + +We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. + +## 9. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP1.md b/BEPs/BEP1.md new file mode 100644 index 000000000..e4da061bf --- /dev/null +++ b/BEPs/BEP1.md @@ -0,0 +1,92 @@ +
+  BEP: 1
+  Title: Purpose and Guidelines
+  Status: Living
+  Type: Process
+  Created: 2019-04-11
+
+ +# BEP 1: Purpose and Guidelines + + +- [BEP 1: Purpose and Guidelines](#bep-1-purpose-and-guidelines) + - [1. What is BEP?](#1--what-is-bep) + - [2. BEP Rationale](#2--bep-rationale) + - [3. BEP Types](#3--bep-types) + - [4. BEP Workflow](#4--bep-workflow) + - [5. BEP Format](#5--bep-format) + - [6. Reference](#6--reference) + - [7. License](#7--license) + + +## 1. What is BEP? + +BEP stands for BNB Chain Evolution Proposal. Each BEP will be a proposal document providing information to the BNB Chain community, including BNB Beacon Chain, BNB Smart Chain, and opBNB. The BEP should provide a concise technical specification of the feature or improvement and the rationale behind it. Each BEP proposer is responsible for building consensus within the community and documenting dissenting opinions. Each BEP has a unique index number. + +## 2. BEP Rationale + +BEP is the primary mechanism for proposing new features, for collecting community technical input on issues, and for documenting the design decisions that go into BNB Chain. Because BEPs are maintained as text files in a versioned repository, their revisions are the historical records of feature proposals. + +For BNB Chain contributors, it is a convenient way to track the progress of their implementation by BEPs. It will help end users to know the status of a given feature, function or improvement. + +## 3. BEP Types + +There are three types of BEP: + +- **Standards**: A Standards BEP outlines functional changes on the BNB Chain, such as modifications to the network protocol, consensus algorithm, changes in block size, or adjustments to the fee mechanis. These changes will impact the implementation of the BNB Chain. +- **Application**: It defines standards for application layer interactions on BNB Chain, distinguishing it from Standards BEPs which govern core protocol changes. Application proposals are designated as BAPs (BNB Chain Application Proposals) and are stored in the "/BAPs/" folder. For more information, please see the [BAP README](../BAPs/README.md). +- **Information**: An Information BEP will clarify some concepts of the BNB Chain, it may not effect the BNB Chain client implementation. +- **Process**: This kind of proposal will change the workflow of BNB Chain working process, like this BEP itself. + +## 4. BEP Workflow +![overall workflow](./assets/bep-1/workflow.png) + +*Figure 1: BEP workflow* + +- **Idea**: If you have an idea but not sure if it worths a BEP or not, you may discuss with the community first before you put too much effort. You may post your idea in [bnb chain forum](https://forum.bnbchain.org/) and visit the [bep-discussion channel in our discord](https://discord.gg/bnbchain) to let the community know it. +- **Draft**: If your idea is widely accepted or you have the confidence, you can draft a document following the BEP format and raise a PR in this repo. Once the PR is reviewed and merged by the BEP editors, it becomes a legal BEP. The pull request number will be used as the BEP number. And it will be recorded and maintained by the community. The BEP author should keep pushing it forward, the author can update the BEP by creating new pull requests. +- **Review(vote)**: Once the BEP is fully prepared, it proceeds to the Review phase, where it will be assessed by the community. Should the BEP introduce modifications to pivotal elements such as the consensus mechanism, economic framework, or user experience compatibility, a [governance vote](https://docs.bnbchain.org/bnb-smart-chain/governance/overview/) becomes essential. However, if the BEP pertains to a minor fix or a non-fundamental alteration, the governance vote may be bypassed. +- **Candidate**: If review is passed and the BEP is accepted, it will enter Candidate state. +- **Enabled**: This proposal is enabled in BNB Chain mainnet, if it is a hard fork, the fork number has reached. + +Other exceptional statuses include: + +- **Living**: A BEP will be long-term maintained, like this BEP. +- **Stagnant**: A BEP has not been updated for more than 6 months, it will enter Stagnant state. +- **Withdrawn**: A BEP that is dropped and will not be implemented. Usually, it is due to some prerequisite conditions that are not true anymore. + +To make it more flexible, BEP can be updated as long as it is not enabled yet. + +## 5. BEP Format +It is important to keep BEP clear and well organized, BEPs need to follow this format(BEP1 is excepted): +- Preamble: a short metadata about the BEP, it should be put at the top of the BEP. Here is an example: +
+  BEP: 127
+  Title: Temporary Maintenance Mode for Validators
+  Status: Enabled
+  Type: Standards
+  Created: 2022-01-10
+  Author(optional): it can be a name or an email.
+  Description(optional): enabled by BSC Euler upgrade, block height 18907621, Jun-22-2022
+  Discussions(optional): could be a link to the bnb forum, where it is discussed.
+
+- Summary: a very short summary with a single sentence, someone could understand the purpose of the BEP by reading it even without technical background. +- Abstract(optional): a short paragraph to give more introduction about the BEP, could be multi-sentence. Someone could read the abstract to know the general workflow of the BEP. +- Motivation: it is a critical part of the BEP, it should explain very clearly why this proposal is needed. +- Specification: it is another critical part, the detail workflow and configuration need to be provided. Diagrams are needed to make it easy to be understood if it is hard to be described in text. +- Rational(optional): it adds more information to support the specification, i.e. why the design in the specification is preferred. +- Forward Compatibility(optional): if the BEP will introduce compatibility problems in the future, probably because of some scheduled changes in the future that would be broken by the BEP. In such case, this part is a must to describe the detail incompatibilities and how to deal with it. +- Backward Compatibility(optional): similar to Forward Compatibility, if the BEP introduces compatibility problems to the previous or current system, then this part is a must to describe the detail incompatibilities and how to deal with it. +- Reference Implementations(optional): before the BEP enters the Final state, a reference implementation will be needed. However, if the BEP does not need a implementation, it can be omitted. +- Vote Status(optional): A link will be provided to showcase the outcome of the vote if the BEP needs vote. +- License: to show the copyright of the BEP. + +## 6. Reference + +Ethereum Improvement Proposals: [https://github.com/ethereum/EIPs](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1.md) + +Bitcoin Improvement Proposals: + +## 7. License + +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEP10.md b/BEPs/BEP10.md similarity index 83% rename from BEP10.md rename to BEPs/BEP10.md index b7f179776..c00eb1c91 100644 --- a/BEP10.md +++ b/BEPs/BEP10.md @@ -25,8 +25,7 @@ This BEP is already implemented. ## 4. Motivation -Binance Chain is designed to connect with multiple service providers, such as different wallelt providers and trading platforms. By adding an optional field in each transaction message, the origin of any transaction could be tracked. This proposal does not want to deal with assigning the values for various source types. The different sources will claim different value and such a proposition will be assigned afterwards. - +BNB Beacon Chain is designed to connect with multiple service providers, such as different wallet providers and trading platforms. By adding an optional field in each transaction message, the origin of any transaction could be tracked. This proposal does not want to deal with assigning the values for various source types. The different sources will claim different value and such a proposition will be assigned afterwards. ## 5. Specification ### 5.1 Transaction Data Structure @@ -58,8 +57,8 @@ All of these constant values shall be considered hardcoded in client implementat | Identifier | Source Description | | ---------- | ---------------------------- | -| 0 | Default source value, e.g. for Binance Chain Command Line, or SDKs | -| 1 | Binance DEX Web Wallet | +| 0 | Default source value, e.g. for BNB Beacon Chain Command Line, or SDKs | +| 1 | BNB Beacon Chain DEX Web Wallet | | 2 | Trust Wallet | | 3 | CanWork.io Decentralised [Serviceplace App](https://github.com/canyacoin/canwork-web-ui)| | 4 | CanYaDAO [Decentralised Autonomous Organisation](https://github.com/canyacoin/canyadao)| @@ -71,11 +70,11 @@ All of these constant values shall be considered hardcoded in client implementat | 10 | [Equal Wallet](https://equal.tech/)| | 11 | [Infinito Wallet](https://www.infinitowallet.io/)| | 12 | Coinomi| -| 18 | MEET.ONE [Blockchain Wallet Supports Binance DEX](https://meet.one)| +| 18 | MEET.ONE [Blockchain Wallet Supports BNB Beacon Chain DEX](https://meet.one)| | 21 | Vision - [Portfolio & Multi-Chain Wallet](https://vision-crypto.com/)| | 68 | Trubi Wallet| | 82 | [Cosmostation Wallet](https://www.cosmostation.io)| -| 91 | [Frontier Wallet](https://frontierwallet.com/) | +| 91 | [Frontier](https://frontier.xyz/) | | 711 | [CoolWallet S](https://coolwallet.io/)| | 714 | Binance| | 777 | Guarda Wallet [Multi-currency, custody-free wallet](https://guarda.co/) diff --git a/BEP12.md b/BEPs/BEP12.md similarity index 88% rename from BEP12.md rename to BEPs/BEP12.md index f34fc6ed5..5b93f6369 100644 --- a/BEP12.md +++ b/BEPs/BEP12.md @@ -1,6 +1,6 @@ # BEP12: Introduce Customized Scripts and Transfer Memo Validation ## Summary -This BEP describes a new feature that enables addresses to customize scripts, and introduces the a validation script for transfer transaction memo. +This BEP describes a new feature that enables addresses to customize scripts, and introduces a validation script for transfer transaction memo. ## Abstract In some circumstances, users may want to specify some additional functions or/and validations on some transactions. @@ -8,10 +8,9 @@ Taking exchange for example, for Bitcoin and Ethereum, exchanges create unique a However, this user experience change causes a lot of problems for both exchange customer support and clients. Clients may be panic if they forget to input the correct memo and exchange cannot allocate the fund to their account. The exchange support have to verify the client deposit in other ways. -For all transfer transactions which are depositing tokens to exchanges, it would be nice if Binance Chain can reject those that have no valid memo. Thus clients won’t be panic for losing tokens and exchanges supports won’t suffer from the heavy working load. - -Here a script model is introduced into Binance Chain. And each address can add new functions by associate itself with one or more predefined scripts. The memo validation is one first type of the scripts to introduce here. +For all transfer transactions which are depositing tokens to exchanges, it would be nice if BNB Beacon Chain can reject those that have no valid memo. Thus clients won’t be panic for losing tokens and exchanges supports won’t suffer from the heavy working load. +Here is a script model introduced into BNB Beacon Chain. Each address can add new functions by associating itself with one or more predefined scripts. The memo validation is the first type of script to be introduced here. ## Status This BEP is under implementation. ## Motivation diff --git a/BEPs/BEP126.md b/BEPs/BEP126.md new file mode 100644 index 000000000..2b2eb5305 --- /dev/null +++ b/BEPs/BEP126.md @@ -0,0 +1,187 @@ +
+  BEP: 126
+  Title: Fast Finality Mechanism
+  Status: Enabled
+  Type: Standards
+  Created: 2021-12-20
+  Discussions(optional): https://forum.bnbchain.org/t/bep-126-draft-introduce-fast-finality-mechanism/123/3
+
+ +# BEP-126: Introduce Fast Finality Mechanism + +- [BEP-126: Introduce Fast Finality Mechanism](#bep-97-introduce-fast-finality-mechanism) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. License](#5-license) + +## 1. Summary + +This BEP introduces a fast finality mechanism on the BNB Smart Chain. + +## 2. Abstract + +BEP-126 Proposal describes a fast finality mechanism to finalize a block, once the block has been finalized, it won't be +reverted forever. + +It takes several steps to finalize a block: +1. A block is proposed by a validator and propagated to other validators. +2. Validators use their BLS private key to sign for the block as a vote message. +3. Gather the votes from validators into a pool. +4. Aggregate the BLS signature if its direct parent block has gotten enough votes when proposing a new block. +5. Set the aggregated vote attestation into the extra field of the new block's header. +6. Validators and full nodes who received the new block with the direct parent block's attestation can justify the direct parent block. +7. If there are two continuous blocks have been justified, then the previous one is finalized. + +The finality of a block can be achieved within two blocks in most cases, this is expected to reduce the chance +of chain re-organization and stabilize the block producing further. + +## 3. Motivation + +Finality is critical for blockchain security, once the block is finalized, it would not be reverted anymore. The fast +finality feature is very useful, users can make sure they get the accurate information from the latest finalized block, +then they can decide what to do next instantly. + +Currently, on BNB Smart chain, all the full nodes and validators need to wait until enough blocks have been produced +to ensure a probabilistic finality. For BSC, with 21 validators, full nodes and validators can wait 2/3*21=14 blocks +to ensure a relatively secure finality, it would be quite long time for some critical applications. + +## 4. Specification +### 4.1 Fast Finality Mechanism +We introduce a vote mechanism to reach fast finality, the whole mechanism includes several rules in vote and consensus. + +#### 4.1.1 Validator Vote Rules +Validators can vote for blocks if they think that block should be in the canonical chain, and once their votes have been +wrapped into the header, they will get rewards. At the same time, they should obey the vote rules, the vote rules can be +described as follows. + +1. A validator must not publish two distinct votes for the same height. (Rule 1) +2. A validator must not vote within the span of its other votes . (Rule 2) +3. Validators always vote for their canonical chain’s latest block. (Rule 3) + +Define the following notation: +* _s_ : the block hash of the latest justified block in the longest chain(the “source”) +* _t_ : the expected longest chain head block hash that is a descendent of s (the “target”) +* h(_s_): the height of block _s_ +* h(_t_): the height of block _t_ +* <_v_, _s_, _t_, h(_s_), h(_t_)> : validator _v_’s vote message +* _a_ -> _b_ : super majority link that ⅔*v+ validators have voted with source _a_ and target _b_ + +The Rule 1 and Rule 2 can be described as for any two votes: +1. h(*t*1) == h(*t*2) is not allowed. (Rule 1) +2. h(*s*1) < h(*s*2) < h(*t*2) < h(*t*1) is not allowed. (Rule 2) + +#### 4.1.2 Aggregate Votes Rules +The valid vote messages should be saved to the block header, before that the miner should first aggregate these votes, +the rules for aggregating votes can be described as follows: + +1. When validators mining blocks, if they see its direct parent block has gathered ⅔*v+ votes from valid validators, they +should aggregate these votes as an attestation for the parent block. We call this direct parent block as the attested +block. We assume 1 block time is totally enough for validators to receive a block, vote for the block and propagate the +vote to other validators. + +#### 4.1.3 Finality Rules +There are two steps to finalize a block, the first step we call justify, the second step we call finalize. + +1. A block is called justified if +* (1) it is the root, or +* (2) there exists attestation for this block in its direct child’s header, we call this block **justified**. +2. A block is called finalized if +* (1) it is the root, or +* (2) it is justified and its direct child is justified. + +#### 4.1.4 Longest Chain +In the Parlia and Clique consensus, the validators will rely on the sum of the “Difficulty” field to compare and confirm +which chain is the longest to pick as the ancestor. + +While introducing this finality mechanism, the chain should grow under new fork choice rule: the fork including the +highest justified block should be considered as the longest chain even though there are other chain forks with higher +difficulty sum. If there is no new block that can be justified during some time, the chain can grow with the previous +longest chain rule, which can make the chain remain original probabilistic finality. + +The new longest chain rule can be described as follows. + +1. The fork that includes the higher justified block is considered as the longest chain. +2. When the justified block is the same, fall back to compare the sum of the “Difficulty” field. + +#### 4.1.5 Validator Liveness +In the current Parlia consensus, the validator liveness is ½*v+1=11, which means when there are more than 11 validators +online, the chain can get increased continuously. + +In this design, the liveness of producing blocks and the liveness of finalizing blocks are independent. Despite of ⅔*v+ validators are needed to keep the finalized block number increasing, keeping the chain increasing only need ½*v+ validators as before. + +### 4.2 Theory Proof +Assume the malicious validators are less than ⅓*v, honest validators are more than ⅔*v, honest validators always behave +under the above rules, the vote can be propagated to all validators within one block time, then we can prove this fast +finality mechanism has accountable safety and plausible liveness. + +Accountable safety means that two blocks in different forks cannot both be finalized unless ⅓*v or more validators +violate the voting rules. + +Plausible liveness means that, regardless of any previous events, if ⅔*v+ validators follow the mechanism, then it’s +always possible to finalize a new block without any validator violating the vote rules. + +Under the assumption that less than ⅓*v validators violate the vote rules, we have the following properties: + +1. If *s*1 -> *t*1 and *s*2 -> *t*2 are distinct super majority links, then h(*t*1) != h(*t*2). +2. If *s*1 -> *t*1 and *s*2 -> *t*2 are distinct super majority links, then the inequality h(*s*1) < h(*s*2) < h(*t*2) < h(*t*1) cannot hold. + +From these two properties, we can immediately see that, for any height n: + +3. there exists at most one super majority link _s_ -> _t_ with h(_t_) == n. +4. there exists at most one justified block with height n. + +With these four properties in hand, we move to the main theorems. + +#### 4.2.1 Accountable Safety +**Theorem 1 (Accountable Safety).** Two blocks in different forks cannot both be finalized. + +Let Am (with justified Am+1, meaning h(Am) + 1 == h(Am+1)) and Bn (with justified direct child Bn+1, meaning +h(Bn) + 1 == h(Bn+1)) be distinct finalized blocks. Now suppose Am and Bn are on different forks, +and without loss of generality h(Am) < h(Bn) (If h(Am) == h(Bn) it is clear that at least one honest validator violated +Rule 1). + +Bn is finalized, so there must exist a super majority link R -> B1, …, Bi - > Bi+1, …, Bn -> Bn+1. We know no super majority +link’s target h(Bi) equals either h(Am) or h(Am+1), because that violates property 4. + +Let j be the lowest integer such that the super majority link’s target h(Bj) > h(Am+1). If the super majority link’s +source is justified , we have h(Bj-1) < h(Am+1), and h(Am) = h(Am+1)-1, so h(Bj-1) < h(Am); this implies that the +existence of a super majority link Am -> Am+1 within the span of Bj-1 -> Bj, this violates the vote Rule 2. + +#### 4.2.2 Plausible Liveness +**Theorem 2 (Plausible Liveness)**. Super majority links can always be added to produce new finalized blocks, provided there exist children extending the finalized chain. + +With the justified block growing, the +validators can always start new round voting without violating any vote rules, then we know there always will be new +justified blocks, and once one of its direct child block has been justified, this block can be finalized without +violating any vote rules. + +### 4.3 Reward +In order to make the block get finalized faster, once the validators see the votes for the block are 2/3 or more validators, +these votes will be wrapped and the reward will be distributed to these wrapped voted validators, the remained validators +who didn’t vote for the block or vote later won’t get reward. + +#### 4.3.1 Reward Rules +Rewards are distributed by weights at the end of every epoch. +* Validators whose vote is wrapped into the vote attestation can get one weight for reward +* Validators who assemble vote attestation can get additional weights. The number of weights is equal to the number of extra votes than required +* The total reward is equal to the amount our system reward contract has grown over the last epoch. If the value of the system reward contract hits the upper limit, 1 BNB will be distributed + +### 4.4 Slash +#### 4.4.1 Slash Rules +* The validator who violates the first two vote rules will be slashed +* The evidence can be submitted by anyone, whenever someone sees the malicious behavior, he can submit the evidence to a + designed system contract +* Once the evidence has been proved valid, the malicious validator will be put into jail and punished with a huge fine, like 10000 BNBs. + The submitter can get part of the rewards from our system reward contract. +* The malicious validator will only be punished once. Once the malicious validator has been put into jail, the later submitters that submit malicious evidence of the + validators won’t get any reward. + +### 4.5 Stopping Attacks +There are two well-known attacks against proof-of stake system: *long range revisions* and *catastrophic crashes*, these +attacks are also existed after implementing this BEP. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP127.md b/BEPs/BEP127.md new file mode 100644 index 000000000..a5d6abf01 --- /dev/null +++ b/BEPs/BEP127.md @@ -0,0 +1,57 @@ +# BEP-127: Temporary Maintenance Mode for Validators + +- [BEP-127: Temporary Maintenance Mode for Validators](#bep-99-temporary-maintenance-mode-for-validators) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [6. License](#6-license) + +## 1. Summary +This BEP introduces the **Temporary Maintenance** mode for validators on the BNB Smart Chain. + +## 2. Abstract +**Temporary Maintenance** is supposed to last one or a few hours. The validator seat will be temporarily dropped from the block producing rotation during the maintenance. Since long-time offline maintenance is not encouraged, the validator will still be slashed if the maintenance lasts too long. To lower the impact from poorly-operating validators who forget to claim its maintenance, they will be forced to enter **Temporary Maintenance** mode too. + +## 3. Status +This BEP is already implemented. + +## 4. Motivation +Due to the design of **Parlia** consensus, the absence of the validator, even if it is due to scheduled maintenance, will cause instability and capacity loss of BSC due to the extra waiting time and chain reorganization for other validators. Introducing **Temporary Maintenance** mode will stabilize the blocking rotation and maintain the capacity of BSC. + +## 5. Specification + +### Current Slash Mechanisms +The [slash contract](https://bscscan.com/address/0x0000000000000000000000000000000000001001) will record the missed blocking metrics of each validator. +- Once the metrics are above the predefined threshold, the blocking reward for validator will not be relayed to BC for distribution but shared with other better validators. +- If the metrics remain above another higher level of threshold, the validator will be dropped from the rotation, and put as “in jail”. This will be propagated back to BNB Beacon Chain, where a predefined amount of BNB would be slashed from the self-delegated BNB of the validator. + +### Temporary Maintenance Mode + +#### Proactive Maintenance +Validator can claim itself to enter scheduled maintenance by sending a transaction signed by the consensus key. The validator can claim itself to exit maintenance by sending another transaction. The slash cleaning work will be done within the exit transaction: + +**SlashCount = (MaintenanceEndHeight - MaintenanceStartHeight)/len(currentValidatorSet)/Scale** + +**Scale** is a governable parameter, the initial setting is 2, usually it should be larger than 1. If **SlashCount** is larger than a predefined value, the validator will still be slashed. The validator can get more time to bring the node back before being slashed if it claims itself to enter maintenance. Validator is encouraged to claim itself to exit maintenance even if it will be put in jail, since it can send the unjail transaction earlier. + +#### Passive Maintenance +Once the number of missed blocks is above a predefined threshold, the validator will enter maintenance automatically. The validator still gets a chance to catch up and claim itself online again. + +### Limit +1. The number of maintained validators has an upper limit at the same time. Once exceeded, the following proactive/passive claim request will be rejected. +2. A validator can only enter maintenance once per day. + +### ValidatorSet Change +The validators election will repeat every 24 hours, the maintenance will end immediately once election happens. + +### Impact to Validator Maintainers +Validator maintainers can claim the validator to enter maintenance mode once the node runs into unexpected issues. Validator maintainers need to send transactions to exit maintenance mode even if the validator is enforced into maintenance, otherwise, the validator may be put in jail. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + + + diff --git a/BEPs/BEP128.md b/BEPs/BEP128.md new file mode 100644 index 000000000..dcbee5612 --- /dev/null +++ b/BEPs/BEP128.md @@ -0,0 +1,48 @@ +# BEP-128: Improvement on BNB Smart Chain Staking Reward Distribution + +- [BEP-128: Improvement on BNB Smart Chain Staking Reward Distribution](#bep-128-improvement-on-bnb-smart-chain-staking-reward-distribution) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Overall Workflow](#51-overall-workflow) + - [5.2 Distribution Batch Size](#52-distribution-batch-size) + - [5.3 User Impact](#53-user-impact) + - [6. License](#6-license) + +## 1. Summary +This BEP describes a proposal to improve the BNB Smart Chain staking reward distribution mechanism on BNB Beacon Chain. + +## 2. Abstract +Instead of distributing BNB Smart Chain staking rewards in a single block for each day, this proposal suggests distributing staking rewards in many consecutive blocks, to minimize the burden on the specific block. + +## 3. Status +This BEP is already implemented. + +## 4. Motivation +Currently, the staking rewards of BNB Smart Chain are distributed in the first block of a day on BNB Beacon Chain (which is known as breath block). With the increasing number of delegators (more than 50,000 nowadays), it will lead to a heavy load to breath block, and users' transactions/requests could be affected. Meanwhile, it could also be a bottleneck for further evaluation of BNB Beacon Chain. Thus, this proposal provides a solution to fix the issue and benefit the evaluation of BNB Beacon Chain in the long term. + +## 5. Specification +### 5.1 Overall Workflow +![overall workflow](./assets/bep-128/reward-distribution.png) + +The overall distribution processes work like this: + - In breath block, validators' commission fee will be distributed, all delegators' rewards will be saved to a separate store. + - Delegators' reward will be distributed in batches in the following blocks. + +### 5.2 Distribution Batch Size + +Distribution batch size controls how many delegators will receive reward in a single block. It should be evaluated and adjusted to make sure: + - The reward distribution must finish within one day, which means the batch size should not be too small. + - It should not be too big to bring heavy load on a single block. + +At the same time, this batch size can also be governed. + +### 5.3 User Impact + +The impact to general delegators is minimal, that their rewards will be delayed a bit after applying this proposal. However, the delay is relatively small and can be ignored compared to the whole staking process. Taking the current delegation volume as an example, about 50,000 rewards are distributed, then in the worst case the delay is 3~4 minutes (500 blocks) if the batch size is 100. + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + diff --git a/BEPs/BEP130.md b/BEPs/BEP130.md new file mode 100644 index 000000000..07adaccf0 --- /dev/null +++ b/BEPs/BEP130.md @@ -0,0 +1,239 @@ +
+  BEP: 130
+  Title: Parallel Transaction Execution
+  Status: Draft
+  Type: Standards
+  Created: 2022-01-27
+
+ +# BEP-130: Parallel Transaction Execution + +- [BEP-130: Parallel Transaction Execution](#bep-130-parallel-transaction-execution) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Design Principle](#41-design-principle) + - [Compatibility](#compatibility) + - [None Intrusion \& Decoupled](#none-intrusion--decoupled) + - [Configurable](#configurable) + - [Keep It Simple And Smart](#keep-it-simple-and-smart) + - [4.2 Overview](#42-overview) + - [4.2.1 Workflow](#421-workflow) + - [4.2.2 Pipeline](#422-pipeline) + - [4.3 Initialize](#43-initialize) + - [4.4 Dispatcher](#44-dispatcher) + - [4.5 Slot Execution](#45-slot-execution) + - [4.5.1 State Of Slot](#451-state-of-slot) + - [4.5.2 Execution Stages In Slot](#452-execution-stages-in-slot) + - [4.5.3 Conflict Detection](#453-conflict-detection) + - [Conflict Detection Items](#conflict-detection-items) + - [Conflict Window](#conflict-window) + - [4.5.4 Transaction Redo](#454-transaction-redo) + - [4.5.5 Transaction Result Merge](#455-transaction-result-merge) + - [4.6 Handle System Contract](#46-handle-system-contract) + - [4.7 Block Mining and Sync](#47-block-mining-and-sync) + - [5. License](#5--license) + +## 1. Summary + +This BEP introduces a parallel transaction execution mechanism on the BNB Smart Chain. + +## 2. Abstract + +To improve the performance of block execution, this BEP introduces a mechanism to execute the transactions within one block concurrently to some extent. + +In the stage of block execution, this BEP introduces two new components: + +1. Dispatcher +2. Slot + +The slot is where the transactions are executed and the transactions in different slots can be executed concurrently. + +The dispatcher will dispatch the transactions in a block to the slots sequentially according to the dispatching strategy. + +Since the transactions can be executed in different slots concurrently, the performance of the block execution should be improved if there are not many conflicts between the different slots. + +## 3. Motivation + +BSC is facing the challenge of huge traffic and the daily transaction volume had reached an all-time high of 16 million recently. The network could get congested when there is a promotion activity happening on a popular dApp. + +Besides validators, full nodes also experienced difficulty to catch up the new blocks due to the heavy computing and storage load. + +The execution of the block transactions takes up most of the time when producing or synchronizing(in full sync mode) the blocks. For now, the transactions are executed sequentially. Introducing a parallel EVM execution mechanism can utilize the performance of multi-core processors and reduce the time of block execution which will improve the capacity of the whole network. + +## 4. Specification + + +### 4.1 Design Principle + +There are some principles that we will stick to when we design the parallel execution proposal. + +#### Compatibility + +It should not change the workflow of current BSC’s working process, e.g., consensus algorithm, storage format, contract opcode format, all of these component’s behavior should stay unchanged. + +In short, the parallel execution will produce the same result as the current sequential execution. + +#### None Intrusion & Decoupled + +The implementation should be kept within the execution layer, it should not change the data structure or interface of other modules. + +And also, it should be decoupled. There are modules such as BlockProcessor, EVM Interpreter, StateDB, StateObject, ReceiptProcessor… within the execution layer. Parallel execution could introduce new modules, such as TxDispatcher, TxResultMerger, ConflictDetector, SlotState… they should be decoupled, no circular dependency. + +#### Configurable + +The BSC node could configure its parallel execution parameters based on its hardware resources, since different hardware could have different best practice parameters. + +The parameters that can be configured could be: enable/disable, concurrent number, MaxQueueSize for each slot, dispatcher policy etc. + +These parameters can be configured on node startup or even at runtime. + +#### Keep It Simple And Smart + +The parallel execution could be very complicated, especially its execution pipeline, unorder execution & inorder commit, thread safe stateobject access, conflict detect algorithm… + +But design should keep it as simple as possible, complexity makes product unstable. + +And to achieve the best performance benefits, it should be smart on how to dispatch transactions to reduce transaction conflict and make the parallel execution slots workload balance. + +### 4.2 Overview + +The goal of this BEP is to improve the performance of block execution by executing the transactions concurrently to a certain extent. + +![overview](./assets/bep-130/1_overview.png) + +Two major components will be introduced in block execution: + +1. Dispatcher. +2. Slot. + +A configured number of slots will be created on BSC node startup, which will receive transaction requests from the dispatcher and execute transactions concurrently. Transactions that are dispatched to a same slot will be executed sequentially in this slot. + +The dispatcher will dispatch the transactions in a block to slots sequentially when there is a slot available. + +#### 4.2.1 Workflow + +Here is the general workflow of the parallel execution. When a batch of transactions are received, no matter from P2P transaction pool or downloaded blocks, there will be a state processor to handle the transactions. If parallel is not enabled, the transactions will be processed sequentially as before, otherwise they will be handled by the parallel processor, the details will be explained later. + +![workflow](./assets/bep-130/2_workflow.png) + +#### 4.2.2 Pipeline + +The parallel transaction execution would have a pipeline. The current design is for the initial phase, and it will be optimized to get the best performance. + +Let’s have an overview of the parallel pipeline first, with 8 concurrencies as an example. + +![pipeline](./assets/bep-130/3_pipeline.png) + +### 4.3 Initialize + +The parallel initialization will be done on node startup, if parallel execution is enabled. The parallel slot pool will be created, each slot will have a SlotState structure to maintain its state. Then the slot will be waiting until it receives a new transaction execution request. + +![init](./assets/bep-130/4_init.png) + +### 4.4 Dispatcher + +The dispatcher is responsible for dispatching the transactions in the block to the slots sequentially. + +![dispatcher](./assets/bep-130/5_dispatcher.png) + +The dispatcher will select a suitable target slot for each transaction and dispatch it to that slot, transactions in a block will be dispatched sequentially. The target slot for a transaction is decided at runtime, based on the state of parallel execution pipeline. + +There are many factors that will be taken into consideration to make the decision: + +1. Is the slot idle or occupied? +2. If there is a same address contract running or pending in this slot? +3. Has the slot’s pending transactions size reached the max transactions queue size limitation already? +4. If there is a very big transaction index gap between the slot’s head transactions and the transactions to be dispatched? +5. If the transaction address is a known contract with high conflict rate according to history data. +6. If the transaction address is a known contract with a huge gas cost? + +… + +The dispatcher will try to make the best decision and select an available slot for the transaction, the dispatch algorithm’s target to make a balanced workload and with less state conflict. + +### 4.5 Slot Execution + +The slot is where transactions are executed. Transactions will be dispatched to slots sequentially by the dispatcher and executed sequentially in the same slot. Transactions dispatched to different slots can be executed concurrently. + +There is a pending transaction queue in the slot. When the slot is occupied, the dispatcher can still dispatch transactions to the pending queue of the slot. + +#### 4.5.1 State Of Slot + +There are two states of a slot: + +1. Idle. The slot will be marked idle when there is no transaction executing or no pending transaction in the slot. +2. Occupied. The slot will be marked occupied if it’s executing a transaction and there may be even pending transactions. + +#### 4.5.2 Execution Stages In Slot + +Since transactions are executed concurrently in different slots, the state read by a slot could be changed by other slots, making the transaction's execution result invalid. The invalid transaction should be executed again based on the latest state. + +![dispatcher](./assets/bep-130/6_stages.png) + +For clarity, five stages will be introduced in the transaction execution: + +1. EVM execution. Execute the transaction based on a specific worldstate. +2. Wait for the finalization of the previous transactions in the block. +3. Conflict detection. Detects if there is any conflict between the storage read by this transaction and the storage changed by concurrent transactions in other slots within a conflict detect window. +4. Redo transaction. If there is any conflict detected, the current transaction should be executed again based on the latest finalized worldstate. +5. Finalize. Finalize the state changed by the current transaction to the latest world state. + +Not every transaction will go through these five stages. + +1. If the transaction is the first transaction of a block, it is the luckiest, no need to wait or do conflict detection, it can be finalized right after execution. +2. If its previous transaction was completed in the same slot, it is lucky, no need to wait too, do conflict detect and finalize. +3. For the majority of transactions, they likely need to wait for the previous transactions(TxIndex-1) to complete before it can do conflict detection. +4. And for unlucky transactions, they waited and conflict detected, they need to be redo based on the latest world state. Since redo is based on the latest world state, it won’t conflict and can skip the conflict detection stage. + +#### 4.5.3 Conflict Detection + +After a transaction is executed in a slot, it needs to make sure the previous transaction is finalized, so that it can check if there is any state conflict, otherwise its execution result can not be confirmed. + +The previous transaction can be in the same slot or different slot, each slot will provide a waiting channel for the transaction, so the previous transaction can notify it when finalized. + +The transaction execution is marked as conflict, only if the information it got was changed by other transactions since the current transaction execution was started. To make it more clear, overlapped read without write won’t be marked as conflict, hardcode write without read won’t be marked as conflict as well. + +##### Conflict Detection Items + +* StorageObject’s key/value pair +* Account Balance +* Contract Code/CodeHash/CodeSize… +* Contract State: created and suicided + +##### Conflict Window + +The transaction is executed based on a specific world state, when transaction execution is done, the world state could have been updated several times(each transaction will update world state once). + +Conflict window is an important structure to represent the transaction range that the current transaction needs to compare with. All of the world state changes within this window will be used to compare with the current transaction’s access list, to check if any read information has been updated and not valid anymore. + +![conflict window](./assets/bep-130/7_conflict_window.png) + +#### 4.5.4 Transaction Redo + +If a conflict is detected, the conflicted execution result is not reliable and will be discarded. And the transaction needs to be redo based on the latest world state. The transaction redo will not have conflicts, since all of the previous transactions have been finalized now, it can get the fresh world state and all the state objects will be valid. + +#### 4.5.5 Transaction Result Merge + +The state changes of the transaction are kept within the execution slot. They need to be merged to the main StateDB once the transaction execution is done and the result is valid. + +### 4.6 Handle System Contract + +System contracts are built in contracts to perform system level operations, such as gas fee reward, cross chain communication etc. These contracts are important components of the chain and their behavior may depend on the execution results of other transactions, so they can not be executed concurrently. Parallel transaction execution will not be applied to these system contracts, they will be executed sequentially as before. + +Since most of the transactions in a block are not system contracts, parallel execution still can work for most of the transactions. + +### 4.7 Block Mining and Sync + +There are two different phases of transaction execution: block mining and block sync. + +For the mining phase, the block is under mining and the transactions to be executed are gathered from the P2P transactions pool. There would be invalid transactions, because of bad nonce, block gas limit reached etc. These invalid transactions will not be put into the block. The concurrently executed transaction would have no idea what its transactions index in the block is or which transaction is the previous transaction until the block is mined. + +For the sync phase, the block is supposed to be confirmed, the transactions in the block are determined. + +Parallel transaction execution will support both of the two phases, but there could be some differences for implementation. + +## 5. License + +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP131.md b/BEPs/BEP131.md new file mode 100644 index 000000000..7927258e2 --- /dev/null +++ b/BEPs/BEP131.md @@ -0,0 +1,111 @@ +# BEP-131: Introduce candidate validators onto BNB Smart Chain + +- [BEP-131: Introduce candidate validators onto BNB Smart Chain](https://github.com/bnb-chain/BEPs/pull/131) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [6. License](#6-license) + +## 1. Summary + +This BEP introduces candidate validators onto BNB Smart Chain to improve the liveness and robustness of the network. + +## 2. Abstract + +BNB Smart Chain will introduce more validators, e.g. another 20 inactive validators, into the validator set as backups, which will be called "Candidates". + +Candidates will produce blocks and charge gas fees on BNB Smart Chain mainnet, but in a much less chance than the active validator set of 21 elected. A decent motivation is expected to be maintained so that the candidate validators are willing to ensure the quality and help secure BNB Smart Chain. + +## 3. Status +This BEP is already implemented. + +## 4. Motivation + +Nowadays, BNB Smart Chain has 21 active validators and many inactive validators. The inactive validators have no reward so the incentive for the runner to ensure the node quality and the delegation from the BNB holders are not enough. + +In order to decentralize the network further, more validators should be introduced. Besides increasing the anti-censorship, it always increases the robustness and availability of the network. BNB Smart Chain should survive even if more than half of the validator set were censored or taken down in an either incidental or hostile way. + +## 5. Specification + +### 5.1 Overview +![overview](./assets/bep-131/5.1_overview.png) + +In the current version, the BSC validator set is determined by its staking and delegation logic, via a staking module built on BNB Beacon Chain for BSC, and propagated every day UTC 00:00 from BNB Beacon Chain to BSC via Cross-Chain communication. + +Based on this implementation, the BNB Beacon Chain can propagate more validators to BSC, and BSC can adopt a flexible strategy to choose working validators from both the top 21 staked active validators and less staked candidates for each epoch. + +In this way, the robustness and liveness of the BNB Smart Chain can be improved, and more validator operators will be motivated to join. + +### 5.2 Workflow +Following is a simple diagram to explain the workflow of the validator setting and getting. Usually, M is smaller than N so that candidates get less chance to propose blocks. + +![workflow](./assets/bep-131/5.2_workflow.png) + +### 5.3 Roles + 1. Cabinet + + The top 21 stake validators in daily election snapshots get the most chance of producing blocks. + + 2. Candidate + + The top (21, 21+ MaxNumOfCandidates] staked validators in daily election snapshots get a small chance to produce blocks. + + 3. Inactive + + The rest validators get no chance to produce validators. + +### 5.4 Cross Chain Package +BNB Beacon Chain will send the cabinet and candidate validator set information to the validator contract on BNB Smart Chain every day through the cross-chain package. + +### 5.5 Election +![election](./assets/bep-131/5.5_election.png) + +During the consensus process, BNB Smart Chain will reacquire 21 new working validators through the interface getValidators of validator contract every epoch. On this basis, we can adopt a flexible strategy in the getValidators to achieve the goals. + +#### Election Strategy +First select N validators randomly from Cabinet, and then select M validators randomly from the unselected Cabinet validator and candidates, and finally form a group of 21 validators. + +In order to ensure that the randomness can not be manipulated, epochNumber = BlockHeight / 200 is chosen as the random source. epochNumber is a fixed value within one epoch and is incremental across the epoch. + +Following is the simplified pseudocode demonstrate how the election works: + +``` +Function Select(cabinet, candidate, M) + Shuffle(cabinet, M) + // put unselected cabinet validator into candidates + candidate = [cabinet[0:M], candidate] + Shuffle(candidate, M) + return [cabinet[M:], candidate[0:M]] + +Function Shuffle(validators, limit) + n = len(validators) + for i <- 0 to limit-1 + idx = keccak256(epochNumber, i) mod n + // Do swap + validators[i], validators[idx] = validators[idx], validators[i] +``` + +When the total number of available validators is less than 21, the random selection rule will not be applied. + +The randomness can actually be predicted. But since consensusAddr are limited to change and epochNumber is incremental across the epoch, the randomness can not be manipulated by anyone. + +### 5.5.1 Governance +The following parameters can be governed: +1. MaxNumOfCandidates: The max number of candidates can be elected each day on the BNB Chain Staking module. We can gradually increase the value of MaxNumOfCandidates when there is enough ready candidates. +2. MaxNumOfWorkingCandidates: The max number of candidates can be randomly selected to be working validators for each epoch on the BNB Smart Chain. +### 5.6 Security +A higher staked validator is more trustworthy. Based on this assumption, we let the Top 21 validators generate blocks in turn to maintain a certain degree of security, and the other validators are randomly selected to ensure that these validators will not collude and cause damage to the overall network. + +### 5.7 Liveness +In addition to Cabinet validators, Candidate validators can get the opportunity to propose blocks and get rewards accordingly. Through the reward mechanism, Candidates can be more motivated to actively maintain the nodes. On the other hand, all the slash rules also work on Candidate validators to ensure the malicious or negative behaviors from Candidates will be punished. + +Cabinet and Candidates will be randomly chosen to form the 21 working validators each epoch. The liveness of the network is usually decided by Cabinet validators who are the majority of the working validators. It means the network is still alive even if a large percentage of Candidates go offline. However, the network still suffers a liveness crisis if the majority of Cabinet go offline. + +### 5.8 Robustness +Through the new mechanism, BNB Smart Chain no longer has only 21 validators but has more candidates to choose from. When any active validators encounter instability problems, they can be replaced by candidates, thereby improving the overall robustness. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP151.md b/BEPs/BEP151.md new file mode 100644 index 000000000..3670e9cd8 --- /dev/null +++ b/BEPs/BEP151.md @@ -0,0 +1,35 @@ +# BEP-151: Decommission Decentralized Exchange on BNB Beacon Chain + +## 1. Summary +This BEP proposes to securely and smoothly decommission the build-in decentralized exchange on BNB Beacon Chain. + +## 2. Abstract +BNB Beacon Chain’s primary focus, its native decentralized application ("dApp") BNB DEX, has demonstrated its low-latency matching with large capacity headroom. With the development of BNB Smart Chain and AMM-based decentralized exchanges running well on it, BNB DEX has less usage and liquidity. After implementing this BEP, the DEX module will be disabled, which will give Beacon Chain more computing power for the future computing and governance focuses. + +## 3. Status +This BEP is already implemented. + +## 4. Motivation +BNB Beacon Chain(BC) is a blockchain developed by the BNB Chain community that implements a vision of a decentralized exchange (DEX) for digital assets. The heart of Beacon Chain is a highly performant matching engine built on distributed consensus that aims to replicate the < 1 second trading efficiency of current centralized exchanges. + +Since BNB Smart Chain's(BSC) launch to mainnet in 2020, the AMM based decentralized exchanges gain great success on BSC which even steal the thunder of order-book based DEX on BC. BC and BSC is a dual chain structure, with the evolution of this structure, BC plays more like a Beacon Chain that helps to enhance the security of BSC as a staking and governance layer. It is not suitable for a Beacon Chain to sustain a high-performance DEX any longer, especially when there is another DEX with massive adoption in the same ecosystem. + +Decommissioning the DEX module will reduce the need for system resources significantly for both validators and full nodes. The demand for liquidation can be fulfilled by BNB Smart Chain or the upcoming zkBAS. + +## 5. Specification +After the implementation of this BEP, transactions related to DEX(including `NewOrderMsg`, `ListMsg`, `ListMiniMsg`) will return an error to disable listing new trading pairs or placing any new orders. +All the existing orders will be canceled either by traders or by 3 days timeout(or 30 days for orders in the best 500 price levels, according to [BEP-67](https://github.com/bnb-chain/BEPs/blob/master/BEP67.md)). Thus there will be no more DEX transactions on Beacon Chain. + +### 5.1 Safety +After the implementation of this BEP, there will be no more new orders. +The existing orders which are not matched yet will not be matched anymore. +They can be canceled by the traders directly or by timeout automatically after a period of time, and refunded to the traders. +All the funds are SAFU. + +### 5.2 Impact +Transactions `MsgSubmitProposal` with type of `ProposalTypeListTradingPair` or `ProposalTypeDelistTradingPair` are used for submitting proposals to list new trading pairs or delist trading pairs. + +They might be not useful any longer but still valid after the BEP. It's not encouraged to send these transactions anymore. + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP153.md b/BEPs/BEP153.md new file mode 100644 index 000000000..6e2ce61f9 --- /dev/null +++ b/BEPs/BEP153.md @@ -0,0 +1,231 @@ +# BEP-153: Introduce Native Staking on BSC + +- [BEP-153: Introduce Native Staking on BSC](https://github.com/bnb-chain/BEPs/pull/153) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4motivation) + - [5. Specification](#5-specification) + - [5.1 Overview](#51-overview) + - [5.2 Staking System Contract](#52-staking-system-contract) + - [5.2.1 Cross-Chain Stake Event](#521-cross-chain-stake-event) + - [5.2.2 Data Structs](#522-data-structs) + - [5.2.3 Staking System Contract APIs](#523-staking-system-contract-apis) + - [5.3 Cross-Chain Staking APP](#53-cross-chain-staking-app) + - [5.3.1 Staking](#531-staking) + - [5.3.2 Contract Address on BC(CAoB)](#532-contract-address-on-bccaob) + - [5.3.3 Distribute Reward](#533-distribute-reward) + - [5.3.4 Distribute Undelegated](#534-distribute-undelegated) + - [5.4 Fees](#54-fees) + - [5.5 Error Handle](#55-error-handle) + - [5.5.1 Normal Error](#551-normal-error) + - [5.5.2 Crash in Application Layer](#552-crash-in-application-layer) + - [5.5.3 Error in Communication Layer](#553-error-in-communication-layer) + - [5.5.4 How Funds are Handled When Errors Occur](#554-how-funds-are-handled-when-errors-occur) + - [6. License](#6-license) + +## 1. Summary + +This BEP introduces a native staking protocol onto BNB Smart Chain. With this BEP, individual or institution delegators can stake BNB to specified validators and get staking rewards on the BSC side directly. + +## 2. Abstract + +This BEP introduces a new staking system contract on the BSC side, all staking-related operations on the BSC side should be initiated through this contract, and then applied across-chain to BNB Beacon Chain through the native cross-chain communication mechanism. The cross-chain staking APP on the BNB Beacon Chain side reuses the previous staking mechanism to handle these staking-related operations. + +The goals of this BEP is: + +- For decentralized applications (dApps), they can launch their own staking services on the BSC side base on this protocol; +- For individuals, they can either directly stake their BNB through the staking system contract , or stake through the staking services provided by dApps on the BSC side. + +## 3. Status + +This BEP is already implemented. + +## 4.Motivation + +Before this BEP, the BNB holders can only stake their assets on the BNB Beacon Chain. It means that if their assets are on the BNB Smart Chain, they have to transfer their assets across-chain to the BNB Beacon Chain first, which is not user-friendly enough. + +With this BEP, the BNB holders can stake on the BSC directly, and dApps can launch their staking service based on the protocol introduced by this BEP, which can diversify the BSC ecosystem. + +## 5. Specification + +### 5.1 Overview + +![5.1 Framework](./assets/bep-153/5.1_framework.jpg) + +There are mainly four components: + +1. Staking System Contract: A newly designed system contract in charge of handling staking requests on BSC. +2. Cross-Chain Communication: Existing cross-chain infrastructures including cross chain contract, relayer and oracle module on BC. +3. Cross-Chain Staking APP: A newly designed app on BC in charge of handling cross-chain staking requests. +4. Staking Module on BC: Existing infrastructure in charge of BC’s staking delegation. + +### 5.2 Staking System Contract + +This is a new system contract deployed on BSC. It fulfills all the basic functionalities of staking service including delegation, undelegation, claiming reward and redelegation. It receives requests, encapsulates data and sends cross-chain packages. Specifically, the cross-chain package is normalized as a Cross-Chain Stake Event as below. + +#### 5.2.1 Cross-Chain Stake Event + +The Cross-chain stake event will be emitted once a cross-chain stake transaction happens on BSC. It is mainly composed of channel ID, sequence ID and payload data. + +The payload data is a sequence of RLP encoded bytes of {eventType, params}. + +- eventType: uint8, will determine the corresponding handler that handles staking requests, and also determine how to decode the data. It includes the following types. + + Among them, `distribute reward` and `distribute undelegated` events will be emitted initially on BC. + +| Code | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | +|-------|----------|------------|------------|-------------------|------------------------| +| Event | Delegate | Undelegate | Redelegate | Distribute reward | Distribute undelegated | + +- params: different requests have different parameters including but not limited to delegator address, staking amount, validator operator address and so on. + +#### 5.2.2 Data Structs + +To keep track of delegators staking funds, we adopt multiple mappings to record data. + +```go +mapping(address => uint256) delegated +mapping(address => mapping(address => uint256)) delegatedOfValidator +mapping(address => uint256) distributedReward +mapping(address => mapping(address => uint256)) pendingUndelegateTime +mapping(address => uint256) undelegated +mapping(address => mapping(address => mapping(address => uint256))) pendingRedelegateTime +``` + +`delegated` records every delegator’s total staked amount. When a delegator submits undelegation, his/her delegated amount will decrease and after undelegation finishes, the undelegated increase the same number. + +`delegatedOfValidator` records every delegator’s staked amount to a specific validator. + +`distributedReward` records every delegator’s reward that is already distributed to BSC. + +`pendingUndelegateTime` and `pendingRedelegateTime` records the estimated finish time of undelegation/redelegation. A new operation must wait until the previous operation is closed(until the time is up or receive an ack/failack package). Please be noted that this record will not always be accurate. The previous operation may end early. + +`undelegated` records every delegator’s unlocked undelegate funds that is already distributed to BSC. + +#### 5.2.3 Staking System Contract APIs + +- `delegate(address validator, uint256 amount) payable` + + This method will handle the cross-chain delegating requests. Here, the `validator` represents the BC operator address of the validator to be delegated to. Cross-chain relayer fee should be included in the msg.value. The following graph represents the workflow of delegation on BSC: + +![5.2 Stake](./assets/bep-153/5.2_stake.jpg) + +- `undelegate(address validator, uint256 amount) payable` + + This method will handle the cross-chain undelegating requests. The staked BNBs on BC will be unlocked after 7 days and transferred to the staking contract on BSC automatically. Delegators could claim undelegated BNBs by `claimUndelegated`(see below). The `validator` represents the BC operator address of the validator delegated to. Cross-chain relayer fee should be included in the msg.value. + +- `redelegate(address validatorSrc, address validatorDst, uint256 amount) payable` + + Undelegate amount BNBs from `validatorSrc` and delegate to `validatorDst`. + +- `claimReward() returns(uint256 amount)` + + Delegators can claim their distributed reward by this method. The returned amount is the number of funds that `msg.sender` received. + +- `claimUndelegated() returns(uint256 amount)` + + Delegators can claim their undelegated funds by this method. The returned amount is the number of funds that `msg.sender` received. + +- `getDelegated(address delegator, address validator) external view returns(uint256 amount)` + + This function allows the delegator to query how much he/she has delegated to the specific validator. + +- `getTotalDelegated(address delegator) external view returns(uint256 amount)` + + This function allows the delegator to query how much he/she has delegated in all. + +- `getDistributedReward(address delegator) external view returns(uint256 amount)` + + This function allows the delegator to view the amount of the distributed rewards. + +- `getPendingRedelegateTime(address delegator, address valSrc, address valDst) external view returns(uint256 amount)` + + This function allows the delegator to view the estimated finish time of redelegation from `valSrc` to `valDst`. + +- `getPendingUndelegateTime(address delegator, address validator) external view returns(uint256 amount)` + + This function allows the delegator to view the estimated finish time of undelegation from `validator`. + +- `getUndelegated(address delegator) external view returns(uint256 amount)` + + This function allows the delegator to view the amount of the undelegated funds. + +### 5.3 Cross-Chain Staking APP + +This is a new cross-chain app on BC side. It will be called by the BC’s bridge once it receives cross-chain staking packages. The main function of this app is to parse the data and do the staking related tasks. + +#### 5.3.1 Staking + +The native staking mechanism on the BC will stay almost the same as before. The only change is that the delegation will be tagged as native or none-native(cross-chain). The Cross-Chain Staking app will decode the cross-chain package depending on the event type code and call corresponding functions. + +#### 5.3.2 Contract Address on BC(CAoB) + +The delegator’s corresponding address on the BC will be the XOR result between a map hash of a specific constant string and its BSC address. So no one could control it except for the cross-chain app. + +- The delegate CAoB is calculated by sha256("Staking Delegate Address Anchor") ^ BSC Address. This address is the counterpart of normal delegation’s delegator address. It’s used to hold the delegator’s staking funds. +- The reward CAoB is calculated by sha256("Staking Reward Address Anchor") ^ **delegate CAoB**. This address is used to hold the delegator’s reward. For convenience we add this extra address comparing to normal delegation. + +#### 5.3.3 Distribute Reward + +The delegation reward will be released at each breath block to the reward CAoB, once the balance of the reward CAoB is larger than a threshold. The reward will be cross-chain transferred to the staking system contract on the BSC side automatically. Please note that a proper cross chain relay fee will be charged so that the received reward on BSC will be slightly different. + +#### 5.3.4 Distribute Undelegated + +When undelegation finishes, the undelegated funds will be released to the stake CAoB address, and the funds of the stake CAoB will be cross-chain transferred to the staking system contract on the BSC side automatically in the next breath block. Please note that a proper cross chain relay fee will be charged so that the received undelegated BNB on BSC will be slightly different. + +### 5.4 Fees + +The fees charged for the relevant transactions are based on the following principles: + +- For normal cross-chain communication, the gas and relayer fee shall be paid by the msg sender at once; +- For the failed transactions, there may be extra gas and relayer fee as extra cross-chain communication is needed. This part will be covered by the system reward contract. +- For reward and undelegated distribution, the relayer fee will be deducted from users' funds. + +### 5.5 Error Handle + +This BEP will reuse the existing cross-chain infrastructure as much as possible. This includes and is not limited to the separation of application and communication protocol layers, uniform error handling principle and cross-chain application coding principle. As the new system contract BSC and new app on BC are all parts of the application layer, the error handling of the communication layer will remain the same as before. + +#### 5.5.1 Normal Error + +Normal errors means anticipated errors. For transactions that cross-chain communication is involved, all normal errors will be relayed back. So no errors will be missed. For this type of errors, we recommend that developers should check the returned reason for failure, modify the parameters and retry the transaction. All anticipated errors and success scenarios are listed below. + +| Function | Error | BSC result | BC result | Feedback | +|------------|------------------------------------------------------------------------------------------------------------------------|----------------------|------------|----------------------------------| +| Delegate | Any errors happened on BSC | Transaction reverted | N/A | Error message | +| Delegate | Validator jailed/not exist | Success | AckPackage | Event with error message emitted | +| Delegate | N/A (Success) | Success | N/A | N/A | +| Undelegate | Any errors happened on BSC | Transaction reverted | N/A | Error message | +| Undelegate | Amount greater than delegated shares/Validator not found/No delegation to the validator/Undelegate amount is too small | Success | AckPackage | Event with error message emitted | +| Undelegate | N/A (Success) | Success | N/A | N/A | +| Redelegate | Any errors happened on BSC | Transaction reverted | N/A | Error message | +| Redelegate | Validator jailed/not exist | Success | AckPackage | Event with error message emitted | +| Redelegate | N/A (Success) | Success | N/A | N/A | + +Therefore, if any errors happen on BSC, the transaction will be reverted and the msg sender will know it at once. But if an error happens on BC, the msg sender will not get feedback immediately. So we recommend dApp developers run some robots to monitor related events to get informed. + +#### 5.5.2 Crash in Application Layer + +The communication layer will catch the crash error of the application, record it in store or emit an event for debugging. The crash error will use the FAIL_ACK type of package if needed, and the payload of FAIL_ACK is the same as the payload of the SYNC package. + +For contracts in BSC, the crash of Application will revert state change automatically, but for Application on BC we need to build another sandbox for it, only commit store after it did not crash. + +When receiving the FAIL_ACK package, the communication layer will invoke a different method of Application, like handleFailAckPackage or ExecuteFailAckClaim. We will ensure the safety of users’ assets(see 5.5.4). + +#### 5.5.3 Error in Communication Layer + +Communication layer only plays around with these inputs: Type, Sequence, ChannelId, RelayerFee. The simplicity of these inputs helps us build a robust system. + +However, once an error happens, the communication of a channel may be blocked. We have to hard fork the chain when errors occur in the communication layer. + +#### 5.5.4 How Funds are Handled When Errors Occur During Delegation + +It is very important to protect the safety of actors’ funds. As funds need to be transferred across the chain, this BEP will reuse the cross-chain transfer design as before. The key points are that funds transferred from BSC to BC will be locked in the tokenHub system contract and funds transferred from BC to BSC will be locked in the pegAccount. Necessary mechanism is employed to ensure the cross-chain reconciliation. + +When a delegation request fails, an extra cross-chain package will be sent back to BSC. The funds will be unlocked from the tokenhub system contract, transferred to the staking system contract and be recorded as a part of the delegator’s pending undelegated. The delegator can get his/her funds back by claimUndelegated later. However, if the msg sender is a contract without a receive/fallback method, the transfer will fail and the funds may be lost forever. So **make sure your dApp implements the receive/fallback method**. + +![5.3 Error handle](./assets/bep-153/5.3_errorhandle.jpg) + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP159.md b/BEPs/BEP159.md new file mode 100644 index 000000000..a0b3b12ca --- /dev/null +++ b/BEPs/BEP159.md @@ -0,0 +1,214 @@ +# BEP-159: Introduce A New Staking Mechanism on BNB Beacon Chain + +## 1. Summary + +This BEP introduces a new staking mechanism on the BNB Beacon Chain to increase openness and provide economic security. + +## 2. Abstract + +This BEP introduces a permissionless validator election mechanism and brings the staking economy onto Beacon Chain. + +Anyone can stake their BNB to become a validator candidate or delegate their BNB to the validator candidates they trust. The validator set will be determined by the rank of the accumulated bonded tokens on validator candidates. The validators will be responsible for producing new blocks, in return, they will get block rewards, and share the rewards with delegators. + +By implementing this, the BNB holder has superpower to contribute to the security and gain reward. Staking BNB grants the right to vote on proposals and make decisions on the future of the network. + +## 3. Status + +This BEP is a draft. + +## 4. Motivation + +Currently, the BNB Beacon Chain is secured by a set of trustworthy and preapproved validators. The entrance and exit of a validator are governed by the current validator set. Although this system has high bandwidth, immutability aspects are called into question as censorship and blacklisting are easily implemented. + +On the other hand, the BNB Beacon Chain aims to enhance the security of BSC as a staking and governance layer. After the decommissioning of DEX in [BEP-151](https://github.com/bnb-chain/BEPs/blob/master/BEP151.md), Beacon Chain spares more computing power for security and governance focuses. It is good timing to introduce a [BSC-like staking mechanism](https://github.com/bnb-chain/whitepaper/blob/master/WHITEPAPER.md#staking-and-governance) on Beacon Chain. With this BEP, anyone can compete to join as a candidate to be elected as a validator. The staking status decides the top staked nodes to be the next validator set, and such an election will repeat every 24 hours. The elected validators will be responsible for producing new blocks. The community will decide the total seats of the validator set. It will bring in more decentralization and community involvement. + +## 5. Specification + +### 5.1 The Current Staking Mechanism + +[The current staking mechanism](https://github.com/bnb-chain/bnc-cosmos-sdk/blob/v0.25.0-binance.28/x/stake/handler.go#L19-L22) is conservative: + +- It needs to submit a proposal to add or remove validators. The validator set will be updated only if the proposal is approved by a majority of validators. +- The validator set update will take effect immediately. +- The staked BNB are all from validators themselves. + +### 5.2 The New Staking Mechanism + +After the implementation of this BEP: + +- The [staking mechanism](https://github.com/bnb-chain/whitepaper/blob/master/WHITEPAPER.md#staking-and-governance) used by BSC will be introduced in BC. It enables all users on BC to get involved in securing the network by applying to be a validator or delegating their BNB to the validators they trust, and earn transaction fees for this. +- The validator set update and reward distribution happen on BC around UTC 00:00 every day(in the breath block). +- Some portion of the BSC transaction fee will be distributed to BC validators, as incentives for them to secure the BSC network. + +### 5.2.1 Staking Operation + +- BNB holders, including the validators, can put their tokens "**bonded**" into the stake. Token holders can **delegate** their tokens to any validator or validator candidate, to expect it can become an actual validator, and later they can choose a different validator or candidate to **re-delegate** their tokens. +- All validator candidates will be ranked by the accumulated number of bonded tokens on them, and the top ones will become the real validators to propose blocks. +- Validators get their commission from the blocking reward to cover the cost of running high-quality nodes and share the rest reward with their delegators. +- Validators can suffer from "**Slashing**", a punishment for their bad behaviors, such as double sign and/or unavailability. +- There is an "**unbonding period**" for validators and delegators so that the system makes sure the tokens remain bonded when bad behaviors are caught. + +Data Structures for Staking Operation + +CreateValidator + +``` +// Description - description fields for a validator +type Description struct { + Moniker string `json:"moniker"` // name + Identity string `json:"identity"` // optional identity signature (ex. UPort or Keybase) + Website string `json:"website"` // optional website link + Details string `json:"details"` // optional details +} + +// CommissionMsg defines a commission message to be used for creating a +// validator. +CommissionMsg struct { + Rate sdk.Dec `json:"rate"` // the commission rate charged to delegators + MaxRate sdk.Dec `json:"max_rate"` // maximum commission rate which validator can ever charge + MaxChangeRate sdk.Dec `json:"max_change_rate"` // maximum daily increase of the validator commission +} + +// MsgCreateValidator - struct for bonding transactions +type MsgCreateValidator struct { + Description Description + Commission CommissionMsg + DelegatorAddr sdk.AccAddress `json:"delegator_address"` + ValidatorAddr sdk.ValAddress `json:"validator_address"` + PubKey crypto.PubKey `json:"pubkey"` + Delegation sdk.Coin `json:"delegation"` +} +``` + +EditValidator + +``` +// MsgEditValidator - struct for editing a validator +type MsgEditValidator struct { + Description + ValidatorAddr sdk.ValAddress `json:"address"` + CommissionRate *sdk.Dec `json:"commission_rate"` + PubKey string `json:"pubkey"` +} +``` + +Delegate + +``` +type MsgDelegate struct { + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` + Delegation sdk.Coin `json:"delegation"` +} +``` + +Redelegate + +``` +type MsgRedelegate struct { + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` + Amount sdk.Coin `json:"amount"` +} +``` + +Undelegate + +``` +type MsgUndelegate struct { + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` + Amount sdk.Coin `json:"amount"` +} +``` + +### 5.2.2 Validator Set Update + +In the current implementation, the validator set will be updated immediately after the associated proposal is approved. + +After the implementation of this BEP, staking becomes easy with low cost. So staked BNB ranking might change frequently. To reduce the instability of the network, the validator set update will happen in the first block after UTC 00:00 (which is known as the breath block). + +Since the stake volume on the BNB Beacon Chain is smaller than that on the BNB Smart Chain, it might risk that some malicious users take control of the majority of Beacon Chain validators and fake BSC validator set or cross-chain packages, thus harming the whole ecosystem. We will rank the validator candidates by accumulated staked BNB across a period(e.g. 30 days) instead of the current staked BNB. This mechanism will make the attack harder since it needs more time or more BNB to invoke. It will only affect the validator set election, not the voting power in consensus or governance. + +### 5.2.3 Reward Distribution + +Currently, the reward for BC validators is mostly from transaction fees on Beacon Chain and goes directly to the validators' wallets. + +After the implementation of [BEP-151](https://github.com/bnb-chain/BEPs/blob/master/BEP151.md), the decentralized exchange will be decommissioned from Beacon Chain. There might not be enough incentives for BC validators. + +This BEP proposes that: + +- The staked BNB of validators will not only be from themselves but also the delegators. +- A portion of fees collected on BSC will be paid to BC validators for the cost of maintaining the BC network to enhance BSC security. It will happen in the block reward distribution period. The initial ratio is 10%. +- The block proposer and its delegators receive between 1% and 5% of block fee rewards. It includes 2 parts: + - base: `fees * baseProposerReward` + - bonus: `fees * bonusProposerReward * P`, where `P = (total number of validators with included precommits / total bonded validator number)`. The more precommits the proposer includes, the larger P is. P can never be larger than 1.00 (since only bonded validators can supply valid precommits) and is always larger than 2/3. +- Any remaining fees are distributed among all validators equally, including the proposer. +- The fees will be distributed and accumulated in the system controlled addresses in every block. The `FeeForAll` part will go to a fixed address and the `FeeForProposer` part will go to a custody address which is derived from the proposer’s validator address. Nobody can spend money in the `FeeForAll` address and validators’ custody addresses. They can only be distributed to validators and delegators during the reward distribution period. +- To reduce the cost of frequent block reward distribution, the reward distribution to delegators will happen every day around UTC 00:00(in the breath block). +- A deliberate delay is introduced to make sure the distribution is fair, as [we do in BSC](https://github.com/bnb-chain/whitepaper/blob/master/WHITEPAPER.md#rewarding). +- The [BEP-128](https://github.com/bnb-chain/BEPs/blob/master/BEP128.md) introduced an optimized mechanism that distributes staking rewards in many consecutive blocks, to minimize the burden on the specific block. It's expected to use the same mechanism in BC reward distribution. The BC reward distribution will happen right after the BSC reward distribution. + +### 5.2.4 Disable Previous Transaction Types for Updating Validators + +Since a new validator set update mechanism is introduced, the previous transaction types for updating validators can be disabled. Sending transactions with message type `MsgCreateValidatorProposal` will be rejected after implementing this BEP. + +### 5.2.5 Validator Number and Block Interval Change + +There is a parameter [MaxValidators](https://github.com/bnb-chain/bnc-cosmos-sdk/blob/v0.25.0-binance.28/x/stake/types/params.go#L51) that controls the max validator number. + +It's 21 right now, which is configured in the genesis block. + +However, there are only 11 validators on Beacon Chain Mainnet currently. + +After the implementation of this BEP: + +- The validator seats will change into 11 first to avoid network instability. +- A governance mechanism on this parameter(as well as other parameters on Beacon Chain) will be added. This number can be expanded to more than 100 according to the network demands. +- Usually, the block interval is less than 1 second to fulfill the performance requirement. After implementing BEP-151, there is no more block interval requirement of DEX. The block interval can be adjusted flexibly by the validators. E.g. It can be adjusted to around 6 seconds like most other cosmos SDK chains. + +### 5.2.6 Oracle Relayers + +The oracle relayers are responsible for relaying cross-chain packages from BSC to BC. Currently they are separated services maintained by BC validators. + +After the introduction of open staking mechanism, oracle relayers might also change frequently along with validators. It might affect the stability and security of the cross-chain process. + +To ensure the security of the network, this BEP proposes to keep the current preapproved validators as a whitelist to run the oracle relayers. When the stake volume of Beacon Chain becomes stable and big enough, the whitelist can be removed, and make the validators in charge of running oracle relayers again. + +### 5.3 Change Impacts + +### 5.3.1 Impact on BSC Validators + +They will have to pay extra fees to BC validators for security. They can also stake to be BC validators themselves. + +### 5.3.2 Impact on BC Validators + +The staked BNB of BC validators will not only be from themselves but also the delegators. They might have to improve their reputation and attract more delegators to compete for becoming validators. + +### 5.3.3 Impact on BC users + +They can delegate BNB to BC validators they trust to help secure the network and earn rewards. + +### 5.4 Implementation Procedure + +Phase1: Open self delegation for validators, enable new reward distribution and new validator election mechanism. The current validator should delegate enough BNB to ensure it won't be elected out in phase2. + +Phase2: Open validator creation. Anyone can stake enough BNB to become a validator of Beacon Chain. + +Phase3: Open delegation. Anyone can delegate their BNB to a validator and get reward in return. + +### 5.5 Outlook + +This BEP proposes a new staking mechanism, which moves a big step forward in decentralization and community involvement. + +However, there are more things that can be done to enhance the network and facilitate the community. Here below are some topics to dig into: + +- Slash mechanism to penalize dishonest validators and enhance the robustness of the network. +- Slash mechanism to penalize inactive oracle relayers in Cross-Chain Transfer and Communication. + +We might create more BEPs on these in the future. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP171.md b/BEPs/BEP171.md new file mode 100644 index 000000000..1530c79c8 --- /dev/null +++ b/BEPs/BEP171.md @@ -0,0 +1,85 @@ +
+  BEP: 171
+  Title: Security Enhancement for Cross-Chain Module
+  Status: Enabled
+  Type: Standards
+  Created: 2022-10-28
+  Author: cosinlink
+
+ +# BEP-171: Security Enhancement for Cross-Chain Module + +- [BEP 171: Security Enhancement for Cross-Chain Module](#bep-171-security-enhancement-for-cross-chain-module) + - [1. Summary](#1--summary) + - [2. Motivation](#2--motivation) + - [3. Specification](#3--specification) + - [4. Reference](#4--reference) + - [5. License](#5--license) + +## 1. Summary + +This BEP introduces several security enhancements for the cross-chain bridge between BNB Beacon Chain and BNB Smart Chain. + +To further eliminate the pervasive effects of potential issues in cross chain module, it proposes the following enhancements: +* Upgrade IAVL proof verification to [ICS23 spec](https://github.com/cosmos/ibc/tree/main/spec/core/ics-023-vector-commitments). +* Apply timer lock to massive funds cross-chain transfer. +* Cross chain channels can be automatically paused by forged proof detection. +* Cross chain channels can be paused by any validator in an emergency. + +## 2. Motivation + +A full in-depth security review of BSC cross-chain bridge and Cosmos related codebase is done after the [bridge exploitation](https://www.nansen.ai/research/bnb-chains-cross-chain-bridge-exploit-explained). The community is still really concerned there could be potential security issues in the cross chain module. This BEP aims to: +* Share the same security level as CosmosHub by upgrading the old IAVL lib to the latest ICS23 implementation. The two teams(BNB-Chain and Cosmos) can consistently transmit security updates, best practices, and revised standards for secure operations. +* Exploitation automatic detection, quick action without human intervention. +* Increase the cost of the attack, like timer lock. + +## 3. Specification + +### 3.1 ICS23 Upgrade +ICS23 attempts to define a generic, cross-language, binary representation of merkle proofs, which can be generated by many underlying merkle tree storage implementations and validated by many client libraries over various languages. Currently, ICS23 provides a standard representation for proofs that accompany IBC (inter-blockchain communication) packets as defined in the cosmos specification. This BEP will abandon the stale raw IAVL merkle proof verification and upgrade to ICS23 specification. + +### 3.2 Timelock +If the value of the cross chain transfer is larger than a predefined threshold, the funds will be locked in [TokenHub](https://bscscan.com/address/0x0000000000000000000000000000000000001004) for a fixed period before they can be withdrawn to the target account. +The default threshold of BNB is 10K, and the default lock period is 12 hours, both of them are governable. However, it is hard to set a proper threshold for other BEP20 tokens. We will grant the token [owner](https://github.com/bnb-chain/BEPs/blob/master/BEP20.md#5116-getowner) permission to decide a proper threshold. The interface to set transfer threshold is as follows: + + function setLargeTransferLimit(address bep20Token, uint256 largeTransferLimit) external onlyTokenOwner(bep20Token); + +Once the funds are unlocked, anyone is able to withdraw the funds to the target account. The whitelist relayers will send the unlock withdrawal transaction by default to provide better user experience. + +### 3.3 Exploitation Automatic Detection + +The forged cross chain transaction shares the same channel and sequence with the real cross chain transaction, and both of them can be successfully verified by its merkle proof, while the payload of two transactions are different, such a trait can be used to detect forged cross chain packages. + +#### 3.3.1 Challenge + +Anyone is allowed to submit a transaction to challenge the verified cross chain package on BSC. The interface is shown as below: + + function challenge(uint64 height0, uint64 height1, uint64 packageSequence, uint8 channelId, bytes calldata payload0, bytes calldata proof0, bytes calldata payload1, bytes calldata proof1) onlyInit blockSynced(height0) blockSynced(height1) channelSupported(channelId) external; + +Once the challenge passes the merkle proof verification, the cross chain contract will compare the hash of current payload0 and payload1. If the two payloads are different, it means one of the challenge packages is invalid, the cross chain communication will be suspended automatically. + +#### 3.3.2 Suspension in case of Emergency + +The cross chain contract will be suspended if anyone succeeds in the challenge. Cabinet validators could also suspend the cross chain contract by sending a suspension transaction to the cross chain contract in case of emergency. After that, all cross chain channels will be suspended. The interface of this suspension transaction is shown as below: + + function suspend() onlyCabinet whenNotSuspended external; + +Withdrawals of large transfers will also be suspended during the suspension of cross chain. The cross chain contract could reopen through the validators by using the interface below: + + function reopen() onlyCabinet whenSuspended external; + +### 3.4 Cancel Cross Chain Transfer + +The attacker's cross-chain transfer can be canceled by cabinet validators. The interface is shown as below: + + function cancelTransfer(address tokenAddr, address attacker) onlyCabinet external; + +The funds of this account in the timer lock will be returned to [TokenHub](https://bscscan.com/address/0x0000000000000000000000000000000000001004) to prevent someone minting tokens from nothing. + +## 4. Reference + +ICS23 spec: + + +## 5. License +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP172.md b/BEPs/BEP172.md new file mode 100644 index 000000000..3a1ffb465 --- /dev/null +++ b/BEPs/BEP172.md @@ -0,0 +1,47 @@ +``` +BEP:172 +Title: Network Stability Enhancement On Slash Occur +Status: Enabled +Type: Standards +Created: 2023-01-15 +Discussions: https://forum.bnbchain.org/t/bep-172-draft-improvement-on-bsc-validator-committing-stability/637/1 +``` +# BEP-172: Network Stability Enhancement On Slash Occur + +- [BEP-172: Network Stability Enhancement On Slash Occur](#bep-172-network-stability-enhancement-on-slash-occur) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Overall workflow](#41-overall-workflow) + - [4.2 Remove recentlySigned validators from the candidate set](#42-remove-recentlysigned-validators-from-the-candidate-set) + - [4.3 Reduce minimum delay duration to be zero added to 3 seconds](#43-reduce-minimum-delay-duration-to-be-zero-added-to-3-seconds) + - [5. License](#5-license) + +## 1. Summary + + This BEP introduces an update for parlia consensus about the behavior when `slash` happened, so that the network will be more stable and efficient. + +## 2. Abstract + +This BEP introduces an update for parlia consensus, which changes the `timestamp` and `delay` setting for `offturn` validators. When the validator `inturn` missed its turn to commit block, the block mined by the `offturn` validator selected randomly would be committed as soon as possible(4 or 3 seconds). + +## 3. Motivation + +Before this BEP, a `slash` would happen when a validator missed its turn to commit a valid block. It would take some time longer than expected 3 seconds for the specific block mined with the `delay` mechanism, and even worse with the calculation algorithm deciding how long would be delayed when the block mined by `offturn` validator could be committed. And it took quit a long time (might be more than 1 minute) for the network recovering back to the expected block committing order with expected time duration(3 seconds). + +With this BEP we rewrite the calculation algorithm for the `offturn` validation `delay` time, so that it should be able to commit block in 4 seconds for the selected `offturn` validator when the `inturn` validator missed its turn. What's more, the `slash` will not have bad influence on the future blocks which means the network will recover to expected block producing duration in time. + +## 4. Specification +### 4.1 Overall workflow +![backoffTime (3)](https://user-images.githubusercontent.com/26671219/202097706-d82347f1-fed0-49cb-be08-270d81f70f8b.png) + + +### 4.2 Remove recentlySigned validators from the candidate set + - All validators would be involved to calculate the `delay` time when committing the block mined by themselves currently, and when the `inturn` validator missed its turn, the fastest-with the smallest `delay` duration equals to 4 seconds-`offturn` validator might be the one that had signed recently which led to some other `offturn` validator be the valid selected one to commit block. This is how we observed a block be committed in more than 4 seconds when the `slash` happened. In this BEP, we remove the `recently signed` validators off from the candidate set for calculating `delay` duration from 1 seconds(then the duration would be 3+1=4 seconds) up. +### 4.3 Reduce minimum delay duration to be zero added to 3 seconds + - When a `slash` happened, things would go wrong for quite a long time later on. For example, when `inturn` validator_A was `slashed` on block_100 and `offturn` validator_B took its place to commit the block of number 100. However validator_B should be `inturn` for committing block_101, then it would fail to commit block_101 since it had committed block_100 `recently`. So although there was actually no `slash` happened(all validator worked appropriately), we still need to `delay` some time (1 second or more) to wait for the `offturn` validator committing the block since the `inturn` validator had `recently` committed some block earlier.In this BEP, we reduce the shortest duration to zero second for this specific scenario which means blocks should be able to committed in expected duration (3 seconds) when all validators worked propriately. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP173.md b/BEPs/BEP173.md new file mode 100644 index 000000000..0a69738af --- /dev/null +++ b/BEPs/BEP173.md @@ -0,0 +1,104 @@ + +# BEP-173: Introduce Text Governance Proposal for BNB Smart Chain + +- [BEP-173: Introduce Text Governance Proposal for BNB Smart Chain](https://github.com/bnb-chain/BEPs/pull/173) + - [1. Summary](#1-summary) + - [2. Status](#2-status) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Introduction](#41-introduction) + - [4.2 How to draft a text proposal](#42-how-to-draft-a-text-proposal) + - [4.3 Governance stage](#43-governance-stage) + - [4.3.1 Deposit stage](#431-deposit-stage) + - [4.3.2 Voting stage](#432-voting-stage) + - [4.3.3 Tallying stage](#433-tallying-stage) + - [4.3.4 Execution stage](#434-execution-stage) + - [5. License](#5-license) + +## 1. Summary + +This BEP introduces a text governance proposal for BNB Smart Chain. + + +## 2. Status + +This BEP is already implemented. + + +## 3. Motivation + +In some scenarios, the community may need a proposal that does not directly cause any changes, like agreeing to a certain strategy, plan, commitment or other statement. + + +## 4. Specification + + +### 4.1 Introduction + +Right now, there are many system parameters that control the behavior of the BSC, e.g. slash amount, cross-chain transfer fees. All these parameters can be determined by the BSC Validator Set together through a proposal-vote process based on staking. The process executes on the BC and the new parameter values will be picked up by either the management module on the BC or corresponding system contracts via the cross-chain communication protocol. The proposals can be classified into two groups: + +1. Param Change Proposal if the parameter takes effect on the Beacon Chain; + +2. Cross Param Change Proposal if the parameter takes effect on the BNB Smart Chain. + + + + +This proposal introduces a new kind of proposal to agree on a certain strategy, plan, commitment, future upgrade, or other statements. **Text proposals** are exclusively a signaling mechanism and focal point for future coordination - they do not directly cause any changes on-chain. + + +### 4.2 How to Draft a Text Proposal + +First, the proposer needs to determine which kind of proposal should be used. Be sure to review all the details of a specific proposal type. Aside from recording the proposal outcome on the BNB Beacon Chain, a text proposal has no direct effect on the BNB Chain. + +There are two key components: + + + +1. Title - the distinguishing name of the proposal. +2. Description - the body of the proposal that further describes what is being proposed and the details surrounding the proposal. + +Here is a simple text proposal example: + + { + + "title": "Redesign the transaction ordering", + + "description": "Transactions with the same gas price are currently ordered by receive time. Since latency becomes critical after the update, nodes have less incentives to include light nodes and nodes located remotely as peers. Nodes are clustered and connected. This causes the nodes to become increasingly centralized and defeats the purpose of decentralization. Do we consider sorting with a noise value added so that order is sorted by T + N(0,sigma)?" + + } + + +### 4.3 Governance Stage + + +#### 4.3.1 Deposit Stage + +Anyone can submit a text proposal on the BNB Beacon Chain for others to view. The only cost associated with submitting a proposal is the transaction fee which costs as little as 1 BNB. However, over the course of the voting period, a proposal must have at least 2000 BNB deposited to it in order for it to proceed to the voting stage. This period lasts for at most 2 weeks but if the minimum amount of 2000 BNB is reached sooner, the proposal will proceed to the voting stage immediately. Currently, there is no penalty for delegators and validators who do not participate in governance, though there is a risk to individuals who deposit BNB to a proposal if the proposal does not pass the voting stage, in such case the deposited BNB will be distributed to the validator set. + + +#### 4.3.2 Voting Stage + +The next stage in the governance process is the voting stage which lasts a customized period. Rather than depositing BNB, validator operators in this governance stage are actually voting Yes, No, or Abstain. If a proposal reaches quorum or the minimum threshold defined by the protocol, it will proceed to the next stage for tallying. + + +#### 4.3.3 Tallying Stage + +After the voting stage, the following conditions will be taken into consideration to determine if it passes or not: + + + +* Quorum: more than 50% of the total staked tokens at the end of the voting period need to have voted +* Threshold: More than 50% or a majority of the tokens that participated in the vote, excluding "Abstain" votes must have voted "Yes" +* Veto: Less than 33.4% of the tokens that participated in the vote, not counting "Abstain" votes, have vetoed the decision "No (With Veto)". + +If any of these conditions are not met, the deposit associated with the denied proposal will not be refunded. These funds will be sent to the validator set. + + +#### 4.3.4 Execution Stage + +Once a text proposal is passed, it has no direct effect on the BNB Chain. Generic proposals such as a TextProposal must be reviewed by the BNB-Chain developers and the community for decisions on how to manually implement them. + +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP174.md b/BEPs/BEP174.md new file mode 100644 index 000000000..743baf053 --- /dev/null +++ b/BEPs/BEP174.md @@ -0,0 +1,156 @@ +
+  BEP: 174
+  Title: Cross Chain Relayer Management
+  Status: Enabled
+  Type: Standards
+  Created: 2022-11-23
+
+ +# BEP-174: Cross Chain Relayer Management +- [BEP-174: Cross Chain Relayer Management](#bep-174-cross-chain-relayer-management) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [4.1 Current Relayer Whitelist](#41-current-relayer-whitelist) + - [4.2 The New Whitelisting Mechanism](#42-the-new-whitelisting-mechanism) + - [4.3 `RelayerHub` Smart Contract Changes](#43-relayerhub-smart-contract-changes) + - [Relayer Manager functions](#relayer-manager-functions) + - [Relayer functions](#relayer-functions) + - [`updateParam` Changes](#updateparam-changes) + - [Functions to be Deprecated](#functions-to-be-deprecated) + - [4.4 Relayer Changes](#44-relayer-changes) + - [4.5 Existing relayer key migration](#45-existing-relayer-key-migration) + - [4.6 CLI commands](#46-cli-commands) + - [5. Reference Implementations](#5-reference-implementations) + - [6. License](#6-license) + +## 1. Summary + +This BEP introduces a new governance proposal type to manage the set of whitelisted Relayers. +A Relayer whitelist was introduced recently to the BSC genesis contracts ([PR-198](https://github.com/bnb-chain/bsc-genesis-contract/pull/198)). +This BEP will improve the management of the relayer whitelist by introducing Relayer Managers, where a Relayer Manager can manage the registration of a single Relayer. +Managers will be elected and ejected via governance. + +## 2. Abstract + +This BEP introduces a new governance proposal type to manage Relayer Manager public keys that will be stored in the [`RelayerHub`](https://github.com/bnb-chain/bsc-genesis-contract/blob/71dcd4c409a68a6e084645a9f1f80adecd5a4269/contracts/RelayerHub.sol) genesis contract on BSC. + +Relayer Managers will be able to manage their individual relayer public key. Only Relayer public keys registered via Managers will be able to invoke the `RelayerHub` smart contract for cross chain transfers. + +## 3. Motivation + +After the [BSC Bridge exploitation](https://github.com/verichains/public-audit-reports/discussions/17) it is important we introduce some mechanism in place that enhances the security of the system. A governance based set Manager public keys who manage a single Relayer adds an extra layer of security. + + +## 4. Specification + + +### 4.1 Current Relayer Whitelist + +Currently whitelisted relayers are [hardcoded](https://github.com/bnb-chain/bsc-genesis-contract/blob/a8476b2aefba0a66db86311ab44d43d7e2df24fe/contracts/System.sol#L88) in the `System` genesis smart contract. This list needs to be updated manually by deploying a new version of the smart contract. + +### 4.2 The New Whitelisting Mechanism +After the implementation of this BEP: + +- A Relayer Manager role will be introduced with corresponding public keys. +- The set of Managers will be updated via governance using the existing [param change proposal](https://github.com/bnb-chain/bnb-chain.github.io/blob/45f59e2/docs/learn/bsc-gov.md#submit-cross-chain-param-change-proposal) mechanism. +- Managers will NOT have to deposit any BNB (as opposed to the previous 100BNB deposit requirement). +- Once selected by governance, Managers will be able to add an associated Relayer public key. +- There will be a 1:1 relationship between Manager public key to active Relayer public key. +- Only associated Relayers can send cross chain messages. +- Managers can modify public key of their Relayer at any time. This will facilitate rotation of Relayer instances. +- The old `unregister` function will still be active to allow the existing whitelisted relayers to safely exit. + +### 4.3 `RelayerHub` Smart Contract Changes +#### Relayer Manager functions + +``` +function updateParam(string calldata key, bytes calldata value) external override onlyInit onlyGov +``` +The pre-existing function will be updated to support `addManager` and `removeManager` keys to facilitate adding and removing of managers via governance. + +``` +function removeManagerByHimself() external +``` +Allows a manager to remove himself if required. + +``` +function addManagerByGov(address) external onlyGov +``` +Adds a Manager public key to the current set of Managers. This is only called via governance. Emits an event on success. + +``` +function updateRelayer(address relayerToBeAdded) public onlyManager +``` +This can be used by the manager to add or remove its relayer. Overwrites Relayer if there is an existing Relayer already added. Emits an event on success. The `relayerToBeAdded` parameter can be set to `0` address to enable removal of a relayer (e.g. if the private key gets compromised). + +``` +function whitelistInit() external +``` +This is to ensure smooth transition so that the presently existing hardcoded whitelisted relayers continue to be relayers after the hardfork. This function needs to be **manually** called once after the hardfork. + +#### Relayer functions +``` +function isRelayer(address relayerAddress) external override view returns (bool) +``` +This will be called by the Relayer codebase, instead of registering. Relayer can stop if this returns false + + +#### `updateParam` Changes + +``` + function updateParam(string calldata key, bytes calldata value) external override onlyInit onlyGov{ + if (Memory.compareStrings(key,"addManager")) { + // TODO check and parse value + // addManagerAddress(...) + } else if (Memory.compareStrings(key,"removeManager")) { + // TODO check and parse value + // removeManagerAddress(...) + } else { + require(false, "unknown param"); + } + emit paramChange(key, value); + } +``` +The `updateParam` function will be modified accept two new keys +- `addManager` to add a Manager to the stored Manager set. +- `removeManager` to remove a Manager from the stored Manager set. + +Also `requiredDeposit` and `dues` will be removed. So no need to account for them in the keys check. + +#### Functions to be Deprecated + +These Relayer functions will be deprecated: +``` +function register() external payable ... +``` + +`unregister()` function isn't deprecated to allow existing hardcoded whitelisted relayers to have safe exit. + +### 4.4 Relayer Changes + +Update Relayer codebase to no longer register and deposit. Update abi? and run code generation to call new `verifyRelayer` method on `RelayerHub` smart contract and proceed to relay cross chain messages on success. + +### 4.5 Existing relayer key migration + +Manager keys will need to be supplied for the existing two relayers. Manager set will be seeded with these two Manager public keys. Relayer public keys will be registered to these Managers. + +Existing Relayers will need to pull down relayer code once the `RelayerHub` SC has been upgraded. + +### 4.6 CLI commands +``` +## mainet +./bnbcli params submit-cscParam-change-proposal --key "addManager" --value "ADDRESS" --target 0x0000000000000000000000000000000000001006 --deposit 200000000000:BNB --voting-period 100 --side-chain-id bsc --title "add new super trusty relayer" --from alice --trust-node --chain-id Binance-Chain-Tigris + +## testnet +./tbnbcli params submit-cscParam-change-proposal --key "addManager" --value "ADDRESS" --target 0x0000000000000000000000000000000000001006 --deposit 200000000000:BNB --voting-period 100 --side-chain-id chapel --title "add new super trusty relayer" --from alice --trust-node --chain-id Binance-Chain-Ganges +``` +The commands used to create a change proposal to governance. + +## 5. Reference Implementations +This BEP is under progress. See https://github.com/bnb-chain/bsc-genesis-contract/pull/205. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEP18.md b/BEPs/BEP18.md similarity index 95% rename from BEP18.md rename to BEPs/BEP18.md index 80a19c3cc..1f05f11c9 100644 --- a/BEP18.md +++ b/BEPs/BEP18.md @@ -13,16 +13,16 @@ - [5.4.1 App state chunk](#541-app-state-chunk) - [5.4.2 Tendermint state chunk](#542-tendermint-state-chunk) - [5.4.3 Block chunk](#543-block-chunk) - - [5.5 Operation suggestion](#55-operation-suggestion) + - [5.5 Operation Suggestion](#55-operation-suggestion) - [6. License](#6-license) ## 1. Summary -This BEP describes [state sync](https://docs.binance.org/fullnode.html#state-sync) enhancement on the Binance Chain. +This BEP describes state sync enhancement on the BNB Beacon Chain. ## 2. Abstract -[State sync](https://docs.binance.org/fullnode.html#state-sync) is a way to help newly-joined users sync the latest status of the binance chain. It syncs the latest sync-able peer's status so that fullnode user (who wants to catch up with chain as soon as possible with a cost that discards all historical blocks locally) doesn't need sync from block height 0. +State sync is a way to help newly-joined users sync the latest status of the BNB Beacon Chain. It syncs the latest sync-able peer's status so that fullnode user (who wants to catch up with chain as soon as possible with a cost that discards all historical blocks locally) doesn't need sync from block height 0. BEP-18 Proposal describes an enhancement of existing state sync implementation to improve user experience. The status of the blockchain that can be synced is represented in a **"snapshot"**, which consists of a manifest file and a bunch of snapshot chunk files. The manifest file summarizes version, height, and checksums of snapshot chunk files of this snapshot. The snapshot chunk files contain encoded essential state data to recover a full node. diff --git a/BEPs/BEP188.md b/BEPs/BEP188.md new file mode 100644 index 000000000..c38a02cca --- /dev/null +++ b/BEPs/BEP188.md @@ -0,0 +1,68 @@ +
+	BEP: 188
+	Title: Early Broadcast Mature block for in-turn validators
+	Status: Withdrawn
+	Type: Standards
+	Created: 2022-01-12
+
+ +# BEP-188: Early Broadcast Mature block for in-turn validators. + +- [BEP-188: Early Broadcast Mature block for in-turn validators.](#bep-188-early-broadcast-mature-block-for-in-turn-validators) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 Broadcast strategy](#31-broadcast-strategy) + - [3.2 consensus engine adaption](#32-consensus-engine-adaption) + - [4. Backward Compatibility](#4-backward-compatibility) + - [5. License](#5-license) + +## 1. Summary + +This BEP introduces a new block broadcast strategy for validators to improve the network capacity and stability. + +## 2. Motivation + +Currently, a mined block will not be broadcasted until the timestamp header.Time is reached, even though the mining process is finished. If an in-turn validator spends too much time in the importing phase, it may not have enough time to mine its own block. In extreme cases, it could generate an empty block or even miss its block. This could be a challenge to the stability of the blockchain.With this BEP, validators could begin to import a block earlier and have more time to mine a new block. + +## 3. Specification + +### 3.1 Broadcast strategy + +The current block production process is roughly shown in the figure below: + +![mining_process_normal](./assets/BEP-188/mining_process_normal.png) + + + +As we can see, even though a block was mined before header.Time, it will delay to be broadcasted after header.Time. Then the next in-turn validator starts importing and mining after it receives the block. Actually, a block mined by the in-turn validator can be broadcast as soon as the mining process is finished to let other validators start importing in advance. +But if we early broadcast without limit, the block production process may be like the figure below in case each validator finished mining very quickly because they ran out of gas. + +![broadcast_withoutlimit](./assets/BEP-188/broadcast_without_limit.png) + + + +In this case, more than one block was mined in one block production cycle, which will break the current rule.Let’s see how it works if we limit the block broadcast time to after its parent’s header.Time under the same condition. + +![early_broadcast_with_limit](./assets/BEP-188/early_broadcast_with_limit.png) + +Block N finished mining in advance because it ran out of gas and then broadcast without delay.Block N+1 also finished in advance and before blockN.header.Time, but it must delay broadcast to be after blockN.header.Time. In this way, the block production speed won’t be too quick to break the rule. +In summary, when a block mined by an in-turn validator, if time is after its parent block’s header.Time, broadcast it without delay.time is before its parent block’s header, broadcast it when the parent block’s head.Time is reached. + +### 3.2 consensus engine adaption + +The current consensus engine of the BNB chain does not accept future blocks, which means BSC nodes will reject the block if it is received earlier than its timestamp defined in header.Time. So we need to change the header’s verification logic in the consensus engine as well. +As the broadcast strategy changes, the logic of verifyHeader must be changed accordingly.The new logic should be like this shown in the figure below. + +![consensus_adaption](./assets/BEP-188/consensus_adaption.png) + +## 4. Backward Compatibility + +In order to ensure the compatibility of the network, we should upgrade the changes with the strategy as follows: + +* Upgrading consensus changes with a hard fork first. + +* Then upgrading the broadcast strategy after the hard fork. +## 5. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEP19.md b/BEPs/BEP19.md similarity index 98% rename from BEP19.md rename to BEPs/BEP19.md index d4f35f0e9..6d4466163 100644 --- a/BEP19.md +++ b/BEPs/BEP19.md @@ -30,7 +30,7 @@ This BEP is already implemented. ## 4. Motivation -On not-so-liquid or highly volatile markets, the classic periodic auction match methodology would result in much worse average trade price to aggressive orders (i.e. Taker orders in the continuous match context), because all the trades would be marked with one final price, instead of the average price of all the waiting orders from the market. This is not friendly to active traders and amateur clients that are more familiar with continuous match markets. This causes extra effort to split aggressive orders and much confusion as Binance DEX matches as fast as continuous matching exchange. +On not-so-liquid or highly volatile markets, the classic periodic auction match methodology would result in much worse average trade price to aggressive orders (i.e. Taker orders in the continuous match context), because all the trades would be marked with one final price, instead of the average price of all the waiting orders from the market. This is not friendly to active traders and amateur clients that are more familiar with continuous match markets. This causes extra effort to split aggressive orders and much confusion as BNB Beacon Chain DEX matches as fast as continuous matching exchange. ## 5. Specification diff --git a/BEPs/BEP194.md b/BEPs/BEP194.md new file mode 100644 index 000000000..dadd41b33 --- /dev/null +++ b/BEPs/BEP194.md @@ -0,0 +1,72 @@ +
+  BEP: 194
+  Title: Node Discovery ENR filtering
+  Status: Draft
+  Type: Standards
+  Created: 2023-02-01
+  Author: Matus Kysel
+
+ +# BEP 194: Node Discovery ENR filtering + +- [BEP 194: Node Discovery ENR filtering](#bep-194-node-discovery-enr-filtering) + - [1. Summary](#1--summary) + - [2. Motivation](#2--motivation) + - [3. Specification](#3--specification) + - [4. Reference](#4--reference) + - [5. License](#5--license) + + +## 1. Summary + +This BEP introduces node discovery filtering based on ENR records on the BNB Smart Chain. + +## 2. Motivation + +Current implementation of discovery protocol is chain agnostic and does not differentiate between different chains (ETH, BSC, ...). The discover protocol currently gossips peers from networks with different chain ids. This causes a pretty significant slowdown during peer discovery. + +![node distribution](./assets/bep-194/node_distribution.png) +*Figure 1: Current node distribution on BSC mainnet* + +From Figure 1 we can see, that new nodes have a 2x higher probability finding Ethereum nodes rather than BNB Smart Chain nodes. + +## 3. Specification + +Node discovery protocol uses distributed hash tables (DHTs) that are exchanged between nodes via p2p. We will introduce a new filtering step that will filter out nodes before insertion to the table based on their ENR records. + +``` +// Record represents a node record. The zero value is an empty record. +type Record struct { + seq uint64 // sequence number + signature []byte // the signature + raw []byte // RLP encoded record + pairs []pair // sorted list of all key/value pairs +} +``` +*Code 1: Current ENR record structure layout* + + +ENR record consists of key-value pairs. One of these key-value pairs is the `eth` key which has a genesis hash value. Based on genesis hash we can filter out nodes that are running a different chain id. + +``` +func (eth *Ethereum) currentEthEntry() *ethEntry { + return ðEntry{ForkID: forkid.NewID(eth.blockchain.Config(), eth.blockchain.Genesis().Hash(), + eth.blockchain.CurrentHeader().Number.Uint64())} +} +``` +*Code 2: eth entry generation function* + +We would introduce new flag for `boot-nodes` : + +- `-network ` filters nodes by "eth" ENR entry + + +## 4. Reference + +ENR: + +Node Discovery Protocol: + +## 5. License + +All the content are licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEP2.md b/BEPs/BEP2.md similarity index 77% rename from BEP2.md rename to BEPs/BEP2.md index 421bf8b18..221db5df9 100644 --- a/BEP2.md +++ b/BEPs/BEP2.md @@ -1,12 +1,12 @@ -# BEP-2: Tokens on Binance Chain +# BEP-2: Tokens on BNB Beacon Chain -- [BEP-2: Tokens on Binance Chain](#bep-2-tokens-on-binance-chain) +- [BEP-2: Tokens on BNB Beacon Chain](#bep-2-tokens-on-bnb-beacon-chain) - [1. Summary](#1--summary) - [2. Abstract](#2--abstract) - [3. Status](#3--status) - [4. Motivation](#4--motivation) - [5. Specification](#5--specification) - - [5.1 Native Token on Binance Chain: BNB](#51-native-token-on-binance-chain-bnb) + - [5.1 Native Token on BNB Beacon Chain: BNB](#51-native-token-on-bnb-beacon-chain-bnb) - [5.2 Token Properties](#52-token-properties) - [5.3 Token Management Operation](#53-token-management-operation) - [5.3.1 Issue token](#531-issue-token) @@ -19,28 +19,28 @@ ## 1. Summary -This BEP describes a proposal for token management on the Binance Chain. +This BEP describes a proposal for token management on the BNB Beacon Chain. ## 2. Abstract -BEP-2 Proposal describes a common set of rules for token management within the Binance Chain ecosystem. It introduces the following details of a token on Binance Chain: +BEP-2 Proposal describes a common set of rules for token management within the BNB Beacon Chain ecosystem. It introduces the following details of a token on BNB Beacon Chain: -- What information makes a token on Binance Chain -- What actions can be performed on a token on Binance Chain +- What information makes a token on BNB Beacon Chain +- What actions can be performed on a token on BNB Beacon Chain ## 3. Status -This BEP is already implemented. +This BEP is already implemented, and it has been improved via [BEP87](./BEP87.md). ## 4. Motivation -Design and issue asset on the Binance Chain, as the basic economic foundations of the blockchain. +Design and issue asset on the BNB Beacon Chain, as the basic economic foundations of the blockchain. ## 5. Specification -### 5.1 Native Token on Binance Chain: BNB +### 5.1 Native Token on BNB Beacon Chain: BNB -The Binance Token, BNB, is the native asset on Binance Chain and created within Genesis Block. As the native asset, BNB would be used for fees (gas) and staking on Binance Chain. BNB was an ERC20 token, but after Binance Chain is live, all BNB ERC20 tokens are swapped for BNB token on Binance Chain. All users who hold BNB ERC20 tokens can deposit them to Binance.com, and upon withdrawal, the new Binance Chain native tokens will be sent to their new addresses. +The BNB Beacon Token, BNB, is the native asset on BNB Beacon Chain and created within Genesis Block. As the native asset, BNB would be used for fees (gas) and staking on BNB Beacon Chain. BNB was an ERC20 token, but after BNB Beacon Chain is live, all BNB ERC20 tokens are swapped for BNB token on BNB Beacon Chain. All users who hold BNB ERC20 tokens can deposit them to Binance.com, and upon withdrawal, the new BNB Beacon Chain native tokens will be sent to their new addresses. ### 5.2 Token Properties @@ -58,7 +58,7 @@ The Binance Token, BNB, is the native asset on Binance Chain and created within #### 5.3.1 Issue token -Issuing token is to create a new token on Binance Chain. The new token represents ownership of something new, and can also peg to existing tokens from any other blockchains. +Issuing token is to create a new token on BNB Beacon Chain. The new token represents ownership of something new, and can also peg to existing tokens from any other blockchains. **Data Structure for Issue Operation**: A data structure is needed to represent the new token: @@ -80,11 +80,11 @@ Explanations: Suffix is the first 3 bytes of the issue transaction’s hash. It **Issue Process:** -- Issuer signed an issue transaction and make it broadcasted to one of Binance Chain nodes -- This Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Issuer signed an issue transaction and make it broadcasted to one of BNB Beacon Chain nodes +- This BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Issue transaction is committed on the blockchain by block proposer - Validators will verify the constraints on total supply and symbol and deduct the fee from issuer’s account -- New token’s symbol is generated based on the transaction hash. It is added to the issuer’s address and token info is saved on the Binance Chain +- New token’s symbol is generated based on the transaction hash. It is added to the issuer’s address and token info is saved on the BNB Beacon Chain #### 5.3.2 Transfer Tokens @@ -120,15 +120,15 @@ Transfer transaction is to send tokens from input addresses to output addresses. **Transfer Process:** -- Transferer initiators sign a transfer transaction and make it broadcasted to one of Binance Chain nodes -- The Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Transferer initiators sign a transfer transaction and make it broadcasted to one of BNB Beacon Chain nodes +- The BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Transfer transaction is committed on the blockchain by block proposer - Validators will verify the constraints on balance. The transfer tokens and fee will be deducted from the address of the transaction initiators. - Add the tokens to the destination addresses #### 5.3.3 Freeze Tokens -A Binance Chain user could freeze some amount of tokens in his own address. The freeze transaction will lock his fund, thus this portion of tokens could not be used for the transactions, such as: creating orders, transferring to another account, paying fees and etc. +A BNB Beacon Chain user could freeze some amount of tokens in his own address. The freeze transaction will lock his fund, thus this portion of tokens could not be used for the transactions, such as: creating orders, transferring to another account, paying fees and etc. **Data Structure** **for Freeze Operation**: A data structure is needed to represent the freeze operation @@ -139,8 +139,8 @@ A Binance Chain user could freeze some amount of tokens in his own address. The **Freeze Process:** -- Address-holder signed a freeze transaction and make it broadcasted to one of Binance Chain nodes -- The Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Address-holder signed a freeze transaction and make it broadcasted to one of BNB Beacon Chain nodes +- The BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Freeze transaction is committed on the blockchain by block proposer - Validators will verify the transaction initiator’s balance is no less than the frozen amount. The fee will be deducted from the transaction initiator’s address. - This amount of tokens in the address of the transaction initiator will be moved from balance to frozen. @@ -158,8 +158,8 @@ Unfreezing is to unlock some of the frozen tokens in the user's account and make **Unfreeze Process:** -- Address-holder signed an unfreeze transaction and make it broadcasted to one of Binance Chain nodes -- The Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Address-holder signed an unfreeze transaction and make it broadcasted to one of BNB Beacon Chain nodes +- The BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Unfreeze transaction is committed on the blockchain by block proposer - Validators will verify the transaction initiator’s frozen balance is no less than the required amount. The fee will be deducted from the address of the transaction source. - This amount of token will be moved from frozen to balance in the transaction initiator’s address. @@ -177,11 +177,11 @@ Mint transaction is to increase the total supply of a mintable token. The transa **Mint Process:** -- Token owner signs a mint transaction and makes it broadcasted to one of Binance Chain nodes -- The Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Token owner signs a mint transaction and makes it broadcasted to one of BNB Beacon Chain nodes +- The BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Mint transaction is committed on the blockchain by block proposer - Validators will verify the constraints on whether the token is mintable and whether the bumped total supply will pass the limit. Then increase its total supply and deduct the fee from the address of the token owner -- Newly minted tokens are added to the address of the token owner and token info is updated on the Binance Chain +- Newly minted tokens are added to the address of the token owner and token info is updated on the BNB Beacon Chain #### 5.3.6 Burn Tokens @@ -196,11 +196,11 @@ Burn transaction is to reduce the total supply of a token. The transaction initi **Burn Process:** -- Token owner signs a burn transaction and makes it broadcasted to one of Binance Chain nodes -- The Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Token owner signs a burn transaction and makes it broadcasted to one of BNB Beacon Chain nodes +- The BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Burn transaction is committed on the blockchain by block proposer - Validators will verify the constraints if the token’s supply is no less than the required amount, and then it decreases the total supply and deducts the fee from the address of the token owner -- Burned tokens are deducted from the address of the token owner and token info is updated on the Binance Chain +- Burned tokens are deducted from the address of the token owner and token info is updated on the BNB Beacon Chain ## 6. License diff --git a/BEPs/BEP20.md b/BEPs/BEP20.md new file mode 100644 index 000000000..4819b62aa --- /dev/null +++ b/BEPs/BEP20.md @@ -0,0 +1,135 @@ +# BEP20: Tokens on BNB Smart Chain + +- [BEP-20: Tokens on BNB Smart Chain](#bep20-tokens-on-bnb-smart-chain) + - [1. Summary](#1--summary) + - [2. Abstract](#2--abstract) + - [3. Motivation](#3--motivation) + - [4. Status](#4--status) + - [5. Specification](#5--specification) + - [5.1 Token](#51-token) + - [5.1.1 Methods](#511-methods) + - [5.1.1.1 name](#5111-name) + - [5.1.1.2 symbol](#5112-symbol) + - [5.1.1.3 decimals](#5113-decimals) + - [5.1.1.4 totalSupply](#5114-totalsupply) + - [5.1.1.5 balanceOf](#5115-balanceof) + - [5.1.1.6 transfer](#5117-transfer) + - [5.1.1.7 transferFrom](#5118-transferfrom) + - [5.1.1.8 approve](#5119-approve) + - [5.1.1.9 allowance](#51110-allowance) + - [5.1.2 Events](#512-events) + - [5.1.2.1 Transfer](#5121-transfer) + - [5.1.2.2 Approval](#5122-approval) + - [5.2 Implementation](#52-implementation) + - [6. License](#6-license) + +## 1. Summary +This BEP proposes an interface standard to create token contracts on BNB Smart Chain. + +## 2. Abstract +The following standard defines the implementation of APIs for token smart contracts. It is proposed by deriving the ERC20 protocol of Ethereum and provides the basic functionality to transfer tokens, allow tokens to be approved so they can be spent by another on-chain third party, and transfer between BNB Beacon Chain and BNB Smart Chain. + +## 3. Motivation +A standard interface allows any tokens on BNB Smart Chain to be used by other applications: from wallets to decentralized exchanges in a consistent way. Besides, this standard interface also extends [ERC20](https://eips.ethereum.org/EIPS/eip-20) to facilitate cross chain transfer. + +## 4. Status +This BEP is already implemented. + +## 5. Specification + +### 5.1 Token + +**NOTES**: +- The following specifications use syntax from Solidity **0.5.16** (or above) +- Callers MUST handle false from returns (bool success). Callers MUST NOT assume that false is never returned! + +#### 5.1.1 Methods + +##### 5.1.1.1 name +``` +function name() public view returns (string) +``` +- Returns the name of the token - e.g. "MyToken". +- **OPTIONAL** - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present. + +##### 5.1.1.2 symbol +``` +function symbol() public view returns (string) +``` +- Returns the symbol of the token. E.g. “HIX”. +- This method can be used to improve usability +- **NOTE** - This method is optional in EIP20. In BEP20, this is a required method. Tokens which don’t implement this method will never flow across the BNB Beacon Chain and BNB Smart Chain. + +##### 5.1.1.3 decimals +``` +function decimals() public view returns (uint8) +``` +- Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation. +- This method can be used to improve usability +- **NOTE** - This method is optional in EIP20. In BEP20, this is a required method. Tokens which don’t implement this method will never flow across the BNB Beacon Chain and BNB Smart Chain. + +##### 5.1.1.4 totalSupply +``` +function totalSupply() public view returns (uint256) +``` +- Returns the total token supply. If the token will flow across the BNB Beacon Chain and BNB Smart Chain, the number should be the total of circulation across 2 blockchains. + +##### 5.1.1.5 balanceOf +``` +function balanceOf(address _owner) public view returns (uint256 balance) +``` +- Returns the account balance of another account with address `_owner`. + +##### 5.1.1.6 transfer +``` +function transfer(address _to, uint256 _value) public returns (bool success) +``` +- Transfers `_value` amount of tokens to address `_to`, and MUST fire the Transfer event. The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend. +- **NOTE** - Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. + +##### 5.1.1.7 transferFrom +``` +function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) +``` +- Transfers `_value` amount of tokens from address `_from` to address `_to`, and MUST fire the Transfer event. +- The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. The function SHOULD throw unless the `_from` account has deliberately authorized the sender of the message via some mechanism. +- **NOTE** - Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. + +##### 5.1.1.8 approve +``` +function approve(address _spender, uint256 _value) public returns (bool success) +``` +- Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount. If this function is called again it overwrites the current allowance with `_value`. +- **NOTE** - To prevent attack vectors like the one described here and discussed here, clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before + +##### 5.1.1.9 allowance +``` +function allowance(address _owner, address _spender) public view returns (uint256 remaining) +``` +- Returns the amount which `_spender` is still allowed to withdraw from `_owner`. + +#### 5.1.2 Events + +##### 5.1.2.1 Transfer +``` +event Transfer(address indexed _from, address indexed _to, uint256 _value) +``` +- **MUST** trigger when tokens are transferred, including zero value transfers. +- A token contract which creates new tokens SHOULD trigger a Transfer event with the `_from` address set to 0x0 when tokens are created. + +##### 5.1.2.2 Approval +``` +event Approval(address indexed _owner, address indexed _spender, uint256 _value) +``` +**MUST** trigger on any successful call to `approve(address _spender, uint256 _value)`. + +### 5.2 Implementation + +There are already plenty of BEP20-compliant tokens deployed on the BNB Smart Chain network. Different implementations have been written by various teams that have different trade-offs: from gas saving to improved security. +Example implementations are available at [BNB Smart Chain Implementation](https://github.com/bnb-chain/bsc-genesis-contract/blob/master/contracts/bep20_template/BEP20Token.template) + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + + diff --git a/BEPs/BEP206.md b/BEPs/BEP206.md new file mode 100644 index 000000000..b3e377e56 --- /dev/null +++ b/BEPs/BEP206.md @@ -0,0 +1,446 @@ +
+  BEP: 206
+  Title: Hybrid Mode State Expiry
+  Status: Stagnant
+  Type: Standards
+  Created: 2023-02-24
+  Discussions: https://forum.bnbchain.org/t/bep-idea-state-expiry-on-bnb-chain/646/10
+
+ +# BEP: Hybrid Mode State Expiry +- [BEP: Hybrid Mode State Expiry](#bep-hybrid-mode-state-expiry) + - [1.Summary](#1summary) + - [2.Motivation](#2motivation) + - [3.Specification](#3specification) + - [3.1.Design Guide](#31design-guide) + - [a.The Two Principles](#athe-two-principles) + - [b.Better To Have](#bbetter-to-have) + - [3.2.The Components](#32the-components) + - [a.New Components](#anew-components) + - [b.Existing Components](#bexisting-components) + - [3.3.General Workflow](#33general-workflow) + - [a.From User’s Perspective](#afrom-users-perspective) + - [b.From Node’s Perspective](#bfrom-nodes-perspective) + - [In Epoch 0](#in-epoch-0) + - [In Epoch 1](#in-epoch-1) + - [In Epoch 2+](#in-epoch-2) + - [3.4.The Meta](#34the-meta) + - [a.Definition](#adefinition) + - [b.How to persistent the meta bytes](#bhow-to-persistent-the-meta-bytes) + - [c.How To Update The MetaInfo](#chow-to-update-the-metainfo) + - [d.How To Calculate The MetaHash](#dhow-to-calculate-the-metahash) + - [3.5.Epoch Information In Trie Node](#35epoch-information-in-trie-node) + - [3.6.About GetState/SetState](#36about-getstatesetstate) + - [3.7.Gas Metering](#37gas-metering) + - [3.8.Support Snapshot](#38support-snapshot) + - [a.By Off-Line Prune](#aby-off-line-prune) + - [b.Handle State Revive](#bhandle-state-revive) + - [c.Handle New Key Insert](#chandle-new-key-insert) + - [3.8.The Rent Model](#38the-rent-model) + - [a.Rent Policy](#arent-policy) + - [b.How To Fill The RentBalance](#bhow-to-fill-the-rentbalance) + - [c.How To Determine The RentPrice](#chow-to-determine-the-rentprice) + - [d.How To Charge Rent Fee](#dhow-to-charge-rent-fee) + - [3.9.Precompile Contracts: BSCStateExpiry](#39precompile-contracts-bscstateexpiry) + - [3.10.New Account Structure](#310new-account-structure) + - [3.12.New Block Structure (TBD)](#312new-block-structure-tbd) + - [3.12.State Revive](#312state-revive) + - [3.13.Prune (Important)](#313prune-important) + - [3.14.Remote DB](#314remote-db) + - [3.15.New RPC](#315new-rpc) + - [4.Rationale](#4rationale) + - [4.1.Why Keep The L1 Account Trie](#41why-keep-the-l1-account-trie) + - [4.2.Why Not Create A New L2 Storage Trie](#42why-not-create-a-new-l2-storage-trie) + - [4.3.Reasonable Epoch Period](#43reasonable-epoch-period) + - [4.4.Why Rent Model](#44why-rent-model) + - [5.Forward Compatibility](#5forward-compatibility) + - [5.1.Account Abstraction](#51account-abstraction) + - [5.2.L2 Rollup: Optimism \& ZK](#52l2-rollup-optimism--zk) + - [5.3.VerkleTree \& Stateless](#53verkletree--stateless) + - [5.4.PBSS](#54pbss) + - [6.Backward Compatibility](#6backward-compatibility) + - [6.1.Transaction Execution](#61transaction-execution) + - [6.2.User Experience](#62user-experience) + - [6.3.Web3 API](#63web3-api) + - [6.4.Snap Sync](#64snap-sync) + - [6.5.Archive Node](#65archive-node) + - [6.6.Light Client](#66light-client) + - [7. License](#7-license) + + +## 1.Summary +This BEP proposes a practical solution to address the problem of increasing world state storage on the BNB Smart Chain, by removing expired storage state. + +## 2.Motivation +Storage presents a significant challenge for many blockchains, as new blocks are continually generated, and transactions within these blocks could invoke smart contracts that also add more states to the blockchain. +A large storage size can cause several side effects on the chain, such as higher hardware requirements, increased network resources required for downloading and performing p2p sync, and performance degradation due to MPT write amplification. + +Due to the high volume of traffic, the storage size on BSC grows very rapidly. As of the end of 2022, a pruned BSC full node snapshot file is approximately 1.6TB in size, compared to approximately 1TB just one year ago. +The 1.6TB storage consists mainly of two parts: +- Block Data (~2/3), which includes the block header, block body, and receipt; +- World State (~1/3), which includes the account state and Key/Value (KV) storage state. +The Ethereum community proposed [EIP-4444](https://eips.ethereum.org/EIPS/eip-4444) to address the first part, which is to prune old block data. However, EIP-4444 does not address the second part, which is more challenging. +There have been many discussions on how to implement state expiry, with one proposed solution involving the removal of EOA accounts, extension of the address space, and the use of Verkle Trees to reduce the witness size. However, implementing such a solution would be a significant undertaking that could have a substantial impact on the ecosystem, and may not be feasible in the short term. As BSC continues to face high traffic volumes, it is essential to develop a short-term solution for state expiry that can be implemented quickly, while still retaining the ability to upgrade to a long-term solution once it becomes available. + +## 3.Specification + +|Variable|Description| +| --- | --- | +|Epoch|A time span defined by block number, if set it to ~⅔ year, if BSC validators produce block every 3 second, it would be (365\*2/3)*24\*60\*60/3 = 7,008,000| +|NumKeysLastEpoch|Number of keys that are accessed during last epoch| +|NumKeysLive|Number of keys that are not expired, i.e. accessible| +|NumKeysTotal|Total number of keys, both expired and not expired| +|HotContractThreshold|The threshold to determine if the contract is hot or not, hot means a certain percentage of live states were accessed during the last epoch. If the majority of the state were accessed recently, then the state of the contract will not expire.| +|WitnessPrice|The gas price of 1 byte witness, as witness will be part of the block and needs extra effort for validator to collect it, it could be more expensive than gas price of calldata.| + +### 3.1.Design Guide + +#### a.The Two Principles + +* Rule 1: Permanent delete is unacceptable, expired state must be able to be revived. +* Rule 2: Contract’s execution logic should stay unchanged, if it fails to get the correct state, the execution result will be discarded, i.e. transaction will be reverted. + +#### b.Better To Have + +* Simple protocol + +* Less impact to UX +* Affordable price: storage access fee, state revive fee… + +### 3.2.The Components + +There will be some new components introduced and some existing components will be updated. +![1_components.png](./assets/bep-206/1_components.png) + +#### a.New Components + +* Meta Info: it is used to record the contract’s storage status. +* Rent Model: if a user wants to keep their state from being expired, they will need to pay for the storage rent fee. The rent model will define the detailed rules of how rent fees will be charged. +* Revive & Witness: it will define the procedure for user to revive their expired state. And witness will define the format of witness to revive state, to make it more compact, witness could be merged to remove duplicated bytes. +* Account & Block: the structure of Account and Block is quite important, they will be upgraded to support state expiry. +* Big Scan: it is a special phase to collect the storage information of each contract by scanning all the contract accounts. It could take several weeks, depending on the capability of the nodes. +* Epoch: it represents a certain time span, state expiry will be Epoch based, one Epoch could be around ⅔ year. +* SystemContract(StateExpiry): a new system contract would be created to manage the state expiry policies. + +#### b.Existing Components + +* TxPool: transactions with expired state accessed need to be treated specially, tx pool module may need to be upgraded to make it more efficient. +* Sync: will be upgraded to support sync of witness and metainfo. +* Prune: it will be upgraded to support prune expire state, beside MPT trie node, it also needs to prune the storage of snapshot. +* Snapshot: snapshot will be upgraded to record the status of each KV +* Governance: some of the arguments need to be adjusted dynamically, e.g. the ScanSpeed, RentPrice, ContractLivenessThreshold… +* Gas Metering: will be upgraded to support witness charge. + +### 3.3.General Workflow + +#### a.From User’s Perspective + +Users will not need to be aware of StateExpiry, generally before users send out the transaction, they would query a RPC node about the estimated gas needed. The RPC nodes will estimate the gas needed based on execution fee and the fee to revive all the expired states. If the estimated gas needed is acceptable, the user will send out the transaction as usual. + +When the transaction is propagated to the tx pool of validator, the validator would know whether the transaction needs to access any expired state or not, if yes, the validator would be required to collect the witness and rewarded accordingly. It is ok if the validator does not get the witness, then the validator will not be allowed to include this transaction. + +![2_workflow.png](./assets/bep-206/2_workflow.png) + +#### b.From Node’s Perspective +![3_epochTree.png](./assets/bep-206/3_epochTree.png) + +##### In Epoch 0 + +Nothing will be changed, nodes just operate as usual. + +##### In Epoch 1 + +State will not expire when entering Epoch 1, so the whole state will be there in Epoch 1, no rent will be charged either. But the meta information will be updated on block finalization to record the latest status. + +##### In Epoch 2+ + +Since Epoch 2, state expiry will start to work. The state of the contract will be expired if none of the following requirements are met: + +* The state has been accessed in current or last epoch. +* It is hot, i.e. the percentage of keys accessed during the last epoch is greater than or equal to $LivenessThreshold (unable to do it without big scan, ) +* It has enough RentBalance left for KV pairs in old epochs, KV in current and previous epoch will be exempted. (not determine, if rent model will be used) + +### 3.4.The Meta + +#### a.Definition +``` +Version uint8 // in case meta definition upgrade in the future? +RLP { + EpochRecords []{epoch, numKeys} // for epoch based rent charge + NumKeysTotal uint64 // without keys in epoch0 if no big scan + RentBalance uint64 // deduct on access +} +``` +// if no rent, no meta content needed, can be empty + +![4_epochKey.png](./assets/bep-206/4_epochKey.png) + +#### b.How to persistent the meta bytes +There will be a meta hash in account structure, which will be the key to access encoded meta information. + +![5_trieMeta.png](./assets/bep-206/5_trieMeta.png) + +#### c.How To Update The MetaInfo + +It will be updated on block finalization, not by transaction level. When a block is finalized, then the access record will be determined, we will know the keys that are accessed, created or deleted. These information will be updated to the meta structure + +#### d.How To Calculate The MetaHash + +Metahash is just simply the keccak256 hash of the meta bytecode + +### 3.5.Epoch Information In Trie Node + +It would be very simple, only extend the current branch node, which will include an epoch map, which is used to mark its children’s accessed epoch value. Hash calculation will include this epoch map element, so once the epoch map is updated, the corresponding intermediate nodes will be updated as well. + +![6_extendedBranchNode.png](./assets/bep-206/6_extendedBranchNode.png) + +### 3.6.About GetState/SetState + +If GetState tries to access an expired state, then the transaction will be reverted. + +For SetState, it must do GetState first, if GetState fails due to accessing expired state, then the transaction will be reverted. + +And since delete operation can be treated the same as set, it also needs to perform GetState first. + +### 3.7.Gas Metering + +Depends on the witness size used in this contract, the cost can calculated simply by: WitnessSize * WitnessPrice + +If several transactions have overlapped KVs to revive, the first transaction would probably pay more, as when the later transaction to access these KVs, they are already revived. + +It is somehow reasonable, as the first transaction will be executed first, so it will pay slightly more. + +### 3.8.Support Snapshot + +Snapshot will still be corresponding to the MPT structure. + +Once the MPT is shrunk due to more sub-paths being expired, which will make the MPT end up with some boundary nodes. Boundary nodes are trie nodes that are either leaf nodes or intermediate nodes with at least one of its children expired. + +The snapshot shrink can be conducted by off-line prune according to the MPT. +![7_snapshot.png](./assets/bep-206/7_snapshot.png) + +#### a.By Off-Line Prune + +After off line prune of the MPT trie, the boundary will be generated. Then just go through the MPT tree, prune the snapshot according to the intermediate boundary node. +``` +// For contratc A, it has several several hashed keys with epoch marked: +0x000000000000000000000000_00000000, epoch 1 +0x000000000000000000000000_01000000, epoch 0 +0x000000000000000000000000_01010000, epoch 0 +0x000000000000000000000000_01020000, epoch 0 +0x000000000000000000000000_01030000, epoch 0 +0x000000000000000000000000_02000000, epoch 1 +0x000000000000000000000000_03000000, epoch 1 + +// Currently, it is in epoch 2, so after prune, the tree will be +0x000000000000000000000000_00000000, epoch 1 +0x000000000000000000000000_01, epochMap(0,0,0,0) // 4 children expired in epoch 0 +0x000000000000000000000000_02000000, epoch 1 +0x000000000000000000000000_03000000, epoch 1 +``` +#### b.Handle State Revive +TBD + +#### c.Handle New Key Insert +TBD + +### 3.8.The Rent Model + +#### a.Rent Policy + +* KVs accessed in current or previous epoch will not be kept, no extra fee needed +* Liveness: + +If the percentage of not expired KV accessed in the last epoch is greater than a threshold(30%? governable), then these alive KVs will not be expired. + +update: no liveness check, since no big scan + +* The Rent Balance will be used to pay for these alive KVs, pay by best + +User could save a certain range of Epoch, user may prefer to only save the KV of a few recent epochs + +#### b.How To Fill The RentBalance + +There will be a system contract to handle it, users just need to call it with the target address & balance provided, the system contract will help add the rent balance to the target address. + +The balance can not be reclaimed. + +But if the user sends the balance to an un-existed address, can it be refunded? +``` +// StateExpiryContract: 0x0000000000000000000000000000000000001008 +// or Precompile Contract? +func AddRentBlance(target Address) { + balance = GetValue() // value in transaction + metaInfo = GetMetaInfo(target) + metaInfo.rentBalance += balance +} +``` +#### c.How To Determine The RentPrice + +TBD + +#### d.How To Charge Rent Fee + +On first access of metainfo in a new Epoch, i.e. CurrentEpoch is not in EpochRecord, there will be a rent price for each epoch +``` +EpochRecords []{epoch, numKeys} // for epoch based rent charge + +if curEpoch in EpochRecords { + // rent fee already charged, once per epoch + return +} + +// first time to access +var NewEpochRecords := {curEpoch, 0} // reset +EpochRecordsSorted := sort(EpochRecords) // descending order +for epoch, numKeys := range EpochRecordsSorted { + fee := GetEpochFee(epoch, numKeys) + if RentBalance >= fee { + NewEpochRecords := append({epoch, numKeys}) + RentBalance -= fee + } +} +``` +### 3.9.Precompile Contracts: BSCStateExpiry + +This contract will has some variable to set for governance +``` +contract BSCStateExpiry { + uint256 public scanSpeed; + mapping(uint256 -> uint256) public rentPriceMap; + uint256 public livenessThreshold; + function updateParam(string key, bytes value) { + if (Memory.compareStrings(key, "ScanSpeed")) { + scanSpeed = BytesToTypes.bytesToUint256(32, value); + } else if (Memory.compareStrings(key, "RentPrice")) { + rentPrice = BytesToTypes.bytesToUint256(32, value); + rentPriceMap[curEpoch] = rentPrice + } else if (Memory.compareStrings(key, "LivenessThreshold")) { + livenessThreshold = BytesToTypes.bytesToUint256(32, value); + } + } +} +``` +### 3.10.New Account Structure +``` +type Account struct { +Nonce uint64 +Balance *big.Int +Root []byte +CodeHash []byte +MetaHash []byte // for StateExpiry +} +``` +### 3.12.New Block Structure (TBD) + +* witness can be aggregated into block +* witness can be discarded after a certain period, like blob data, since witness can be generated by re-executing the blocks. +``` +type Witness struct { +addr Hash +keys []Hash +proof []byte +} + +type Block struct { +header *Header +uncles []*Header +transactions Transactions +witness []Witness // for StateExpiry +} +``` +### 3.12.State Revive + +* transaction does not need to provide a witness, just pay the gas fee as usual, the validator will help collect the witness. +* partial revive will be supported, but need at least 1 KV +* depends on boundary nodes, as witnesses must begin from a boundary node? + +### 3.13.Prune (Important) + +off-line prune(bloom-filter) + off-line prune(epoch based, go through the tree, there is a safety check) + +And if PBSS is enabled, on second off-line is needed + +### 3.14.Remote DB + +may not need to cover in BEP + +### 3.15.New RPC + +query new account.meta, KV… + +## 4.Rationale + +* Keep L1 Account Trie Now, could introduce GC mechanism to remove “tiny account” + +* Verkle Still Can Be Used In Storage Trie? + +### 4.1.Why Keep The L1 Account Trie + +There are several reasons to keep it: + +* The size of the L1 account trie is relatively small, constituting only around 4% of the L2 storage trie on BSC as of the end of 2022. +* The L1 account trie contains crucial information about user accounts, such as their balance and nonce. If users were required to revive their accounts before accessing their assets, it would significantly impact their experience. +* By retaining the L1 account trie, the witness verification process can be much simpler. + +### 4.2.Why Not Create A New L2 Storage Trie + +In this proposal, the trie skeleton will be kept in a new epoch. There are other approaches + +which will generate a new trie tree from scratch at the start of a new epoch. Although they + +provide a comprehensive solution for state expiry, there are still two unsolved issues to address: account resurrection conflict and witness size. Additionally, they would have a significant impact on the ecosystem and rely on other infrastructure, such as address extension and Verkle Tree. + +By keeping the skeleton of the trie, it would be much easier to do witness verification and have less impact on the current ecosystem. + +### 4.3.Reasonable Epoch Period + +The state will expire if it has not been accessed for at least 1 epoch or at most 2 epochs. On average, the expiry period is 1.5 epochs. If we set the epoch period to represent 2/3 of a year, then the average state expiry period would be one year, which seems like a reasonable value. + +### 4.4.Why Rent Model + +less impact to user’s business + +## 5.Forward Compatibility + +### 5.1.Account Abstraction + +Account abstraction implementation will be impacted, as these accounts could be stored in the L2 storage trie and could be expired. + +### 5.2.L2 Rollup: Optimism & ZK + +Rollups could be impacted if the rollup transactions try to access expired storage. + +### 5.3.VerkleTree & Stateless + +### 5.4.PBSS + +## 6.Backward Compatibility + +### 6.1.Transaction Execution + +The current transaction types will be supported, but if the transaction tries to access or insert through expired nodes, then it could be reverted. + +### 6.2.User Experience + +There are several changes that could affect user experience. The behavior of many DApps may change and users will have to pay to revive their expired storage. If the revival size is very large, the cost could be expensive. + +### 6.3.Web3 API + +Some of the APIs could be impacted, such as: getProof, eth_getStorageAt... + +### 6.4.Snap Sync + +The snap sync mode will heal the world state after the initial block sync. The procedure of world state healing in snap sync mode will need to be updated. + +### 6.5.Archive Node + +More storage volume would be needed for the archive node, since more metadata will be generated in each epoch. The increased size could be remarkable, which would make the current archive node reluctant to keep the whole state of BSC mainnet. Archive service may have to be supported in other approaches. + +### 6.6.Light Client + +The implementation of the light client would be impacted, since the proof of the shadow tree would also be needed. + +## 7. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP212.md b/BEPs/BEP212.md new file mode 100644 index 000000000..55fcc2fcb --- /dev/null +++ b/BEPs/BEP212.md @@ -0,0 +1,95 @@ +# BEP-212: Reduction in Refunds + + +## Summary + +Remove gas refunds for `SELFDESTRUCT`, and reduce gas refunds for `SSTORE` to a lower level where the refunds are still substantial, but they are no longer high enough for current "exploits" of the refund mechanism to be viable. + +## Motivation + +Gas refunds for `SSTORE` and `SELFDESTRUCT` were originally introduced to motivate application developers to write applications that practice "good state hygiene", clearing storage slots and contracts that are no longer needed. However, the benefits of this technique have proven to be far lower than anticipated, and gas refunds have had multiple unexpected harmful consequences: + +* Refunds give rise to GasToken. GasToken has benefits in moving gas space from low-fee periods to high-fee periods, but it also has downsides to the network, particularly in exacerbating state size (as state slots are effectively used as a "battery" to save up gas) and inefficiently clogging blockchain gas usage +* Refunds increase block size variance. The theoretical maximum amount of actual gas consumed in a block is nearly twice the on-paper gas limit (as refunds add gas space for subsequent transactions in a block, though refunds are capped at 50% of a transaction's gas used). + +## Status + +This BEP is a draft. The code for this BEP has already been merged from upstream go-ethereum codebase into BSC node codebase. The work entails enabling EIP-3529 for BSC network configurations and perform hard fork. + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | TBD | +| `MAX_REFUND_QUOTIENT` | 5 | + +For blocks where `block.number >= FORK_BLOCK`, the following changes apply. + +1. Remove the `SELFDESTRUCT` refund. +2. Replace `SSTORE_CLEARS_SCHEDULE` (as defined in [EIP-2200](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-2200.md)) with `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` (4,800 gas as of [EIP-2929](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-2929.md) + [EIP-2930](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-2930.md)) +3. Reduce the max gas refunded after a transaction to `gas_used // MAX_REFUND_QUOTIENT` + +Remark: Previously _max gas refunded_ was defined as `gas_used // 2`. Here we +name the constant `2` as `MAX_REFUND_QUOTIENT` and change its value to `5`. + +## Rationale + +In [EIP-2200](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-2200.md#specification), three cases for refunds were introduced: + +1. If the original value is nonzero, and the new value is zero, add `SSTORE_CLEARS_SCHEDULE` (currently 15,000) gas to the refund counter +2. If the original value is zero, the current value is nonzero, and the new value is zero, add `SSTORE_SET_GAS - SLOAD_GAS` (currently 19,900) gas to the refund counter +3. If the original value is nonzero, the current value is a different nonzero value, and the new value equals the original value, add `SSTORE_RESET_GAS - SLOAD_GAS` (currently 4,900) gas to the refund counter + +Of these three, only (1) enables gastokens and allows a block to expend more gas on execution than the block gas limit. (2) does not have this property, because for the 19,900 refund to be obtained, _the same storage slot_ must have been changed from zero to nonzero previously, costing 20,000 gas. The inability to obtain gas from clearing one storage slot and use it to edit another storage slot means that it cannot be used for gas tokens. Additionally, obtaining the refund requires _reverting_ the effect of the storage write and expansion, so the refunded gas does not contribute to a client's load in processing a block. (3) behaves similarly: the 4,900 refund can only be obtained when 5,000 gas had previously been spent on the same storage slot. + +This EIP deals with case (1). We can establish under what conditions a gastoken is nonviable (ie. you cannot get more gas out of a storage slot than you put in) by using a similar "pairing" argument, mapping each refund to a previous expenditure in the same transaction on the same storage slot. lf a storage slot is changed to zero when its original value is nonzero, there are two possibilities: + +1. This could be the first time that the storage slot is set to zero. In this case, we can pair this event with the `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` minimum cost of reading and editing the storage slot for the first time. +2. This could be the second or later time that the storage slot is set to zero. In this case, we can pair this event with the most recent previous time that the value was set _away_ from zero, in which `SSTORE_CLEARS_SCHEDULE` gas is _removed_ from the refund. + +For the second and later event, it does not matter what value `SSTORE_CLEARS_SCHEDULE` has, because every refund of that size is paired with a refund _removal_ of the same size. This leaves the first event. For the total gas expended on the slot to be guaranteed to be positive, we need `SSTORE_CLEARS_SCHEDULE <= SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST`. And so this EIP simply decreases `SSTORE_CLEARS_SCHEDULE` to the sum of those two costs. + +One alternative intuition for this EIP is that there will not be a net refund for clearing data that has not yet been read (which is often "useless" data), but there will continue to be a net refund for clearing data that has been read (which is likely to be "useful" data). + +## Backwards Compatibility + +Refunds are currently only applied _after_ transaction execution, so they cannot affect how much gas is available to any particular call frame during execution. Hence, removing them will not break the ability of any code to execute, though it will render some applications economically nonviable. + +Gas tokens will become valueless. DeFi arbitrage bots, which today frequently use either established gas token schemes or a custom alternative to reduce on-chain costs, would benefit from rewriting their code to remove calls to these no-longer-functional gas storage mechanisms. + +However, fully preserving refunds in the `new = original = 0 != current` case, and keeping _some_ refund in the other `nonzero -> zero` cases, ensures that a few key use cases that receive (and deserve) favorable gas cost treatment continue to do so. For example, `zero -> nonzero -> zero` storage set patterns continue to cost only ~100 gas. Two important examples of such patterns include: + +* Anti-reentrancy locks (typically flipped from 0 to 1 right before a child call begins, and then flipped back to 0 when the child call ends) +* ERC20 approve-and-send (the "approved value" goes from zero to nonzero when the token transfer is approved, and then back to zero when the token transfer processes) + +### Effect on storage clearing incentives + +A criticism of earlier refund removal EIPs ([EIP-3298](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-3298.md) and [EIP-3403](https://github.com/ethereum/EIPs/blob/9e393a79d9937f579acbdcb234a67869259d5a96/EIPS/eip-3403.md)) is that these EIPs fully remove the incentive to set a value to zero, encouraging users to not fully clear a storage slot if they expect even the smallest probability that they will want to use that storage slot again. + +For example, if you have 1 unit of an ERC20 token and you are giving away or selling your entire balance, you could instead only give away 0.999999 units and leave the remainder behind. If you ever decide to re-acquire more of that token with the same account in the future, you would only have to pay 5000 gas (2100 for the read + 2900 for nonzero-to-nonzero set) for the `SSTORE` instead of 22100 (20000 for the zero-to-nonzero set). Today, this is counterbalanced by the 15000 refund for clearing, so you only have an incentive to do this if you are more than `15000 / 17100 = 87.7%` sure that you will use the slot again; with EIP-3298 or EIP-3403 the counterbalancing incentive would not exist, so setting to nonzero is better if your chance of using the slot again is _any_ value greater than 0%. + +A refund of 4800 gas remains, so there is only be an incentive to keep a storage slot nonzero if you expect a probability of more than `4800 / 17100 = 28.1%` that you will use that slot again. This is not perfect, but it is likely higher than the average person's expectations of later re-acquiring a token with the same address if they clear their entire balance of it. + +The capping of refunds to 1/5 of gas expended means that this refund can only be used to increase the amount of storage write operations needed to process a block by at most 25%, limiting the ability to use this mechanic for storage-write-focused denial-of-service attacks. + +## Security Considerations + +Refunds are not visible to transaction execution, so this should not have any impact on transaction execution logic. + +The maximum amount of gas that can be spent on execution in a block is limited to the gas limit, if we do not count zero-to-nonzero `SSTORE`s that were later reset back to zero. It is okay to not count those, because if such an `SSTORE` is reset, storage is not expanded and the client does not need to actually adjust the Merke tree; the gas consumption is refunded, but the effort normally required by the client to process those opcodes is also cancelled. **Clients should make sure to not do a storage write if `new_value = original_value`; this was a prudent optimization since the beginning of Ethereum but it becomes more important now.** + +## License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP216.md b/BEPs/BEP216.md new file mode 100644 index 000000000..8fa3b1c2e --- /dev/null +++ b/BEPs/BEP216.md @@ -0,0 +1,80 @@ +
+  BEP: 216
+  Title: Implement EIP-3855: PUSH0 instruction
+  Status: Enabled
+  Type: Standards
+  Created: 2023-3-30
+
+ +# BEP-216: Implement EIP 3855 PUSH0 instruction +- [BEP-216: Implement EIP 3855 PUSH0 instruction](#bep-216-implement-eip-3855-push0-instruction) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5.Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#test-cases) + - [8. License](#8-license) + - [9. Reference](#9-reference) + +## 1. Summary + +As part of the Shanghai upgrade, EIP-3855: PUSH0 Instruction is required to be implemented to BSC. + +## 2. Abstract + +Introduce the PUSH0 (0x5f) instruction, which pushes the constant value 0 onto the stack. + +## 3. Motivation + +**Original motivation from EIP-3855:** + +Many instructions expect offsets as inputs, which in a number of cases are zero. A good example is the return data parameters of CALLs, which are set to zeroes in case the contract prefers using RETURNDATA*. This is only one example, but there are many other reasons why a contract would need to push a zero value. They can achieve that today by PUSH1 0, which costs 3 gas at runtime, and is encoded as two bytes which means 2 * 200 gas deployment cost. + +Because of the overall cost many try to use various other instructions to achieve the same effect. Common examples include PC, MSIZE, CALLDATASIZE, RETURNDATASIZE, CODESIZE, CALLVALUE, and SELFBALANCE. Some of these cost only 2 gas and are a single byte long, but their value can depend on the context. + +Analysis has been conducted on ETH Mainnet (block ranges 8,567,259…8,582,058 and 12,205,970…12,817,405), and ~11.5% of all the PUSH* instructions executed push a value of zero. + +The main motivations for this change include: + +1. Reducing contract code size. +2. Reducing the risk of contracts (mis)using various instructions as an optimisation measure. Repricing/changing those instructions can be more risky. +3. Reduce the need to use DUP instructions for duplicating zeroes. + +To put the “waste” into perspective, across existing accounts 340,557,331 bytes are wasted on PUSH1 00 instructions, which means 68,111,466,200 gas was spent to deploy them. In practice a lot of these accounts share identical bytecode with others, so their total stored size in clients is lower, however the deploy time cost must have been paid nevertheless. + +An example for 2) is changing the behaviour of RETURNDATASIZE such that it may not be guaranteed to be zero at the beginning of the call frame. This was proposed as a way to chain transactions (i.e. EIP-2733). + +## 4. Specification + +The instruction PUSH0 is introduced at 0x5f. It has no immediate data, pops no items from the stack, and places a single item with the value 0 onto the stack. The cost of this instruction is 2 gas (aka base). + +## 5. Rationale + +**Gas cost** + +The base gas cost is used for instructions which place constant values onto the stack, such as ADDRESS, ORIGIN, and so forth. + +**Opcode** + +0x5f means it is in a “contiguous” space with the rest of the PUSH implementations and potentially could share the implementation. + +## 6. Backwards Compatibility + +This introduces a new opcode which did not exist previously. Already deployed contracts using this opcode could change their behaviour after this EIP. + +## 7. Test Cases + +* 5F – successful execution, stack consist of a single item, set to zero +* 5F5F..5F (1024 times) – successful execution, stack consists of 1024 items, all set to zero +* 5F5F..5F (1025 times) – execution aborts due to out of stack + +## 8 License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Most description of this BEP refer to [EIP-3855](https://eips.ethereum.org/EIPS/eip-3855): + +Alex Beregszaszi ([@axic](https://github.com/axic)), Hugo De la cruz ([@hugo-dc](https://github.com/hugo-dc)), Paweł Bylica ([@chfast](https://github.com/chfast)), "EIP-3855: PUSH0 instruction [DRAFT]," Ethereum Improvement Proposals, no. 3855, February 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3855. \ No newline at end of file diff --git a/BEPs/BEP217.md b/BEPs/BEP217.md new file mode 100644 index 000000000..3a2c96a25 --- /dev/null +++ b/BEPs/BEP217.md @@ -0,0 +1,135 @@ +
+  BEP: 217
+  Title: Implement EIP3860 Limit and meter initcode
+  Status: Enabled
+  Type: Standards
+  Created: 2023-3-30
+
+ +# BEP-217: Implement EIP3860 Limit and meter initcode +- [BEP-217: Implement EIP3860 Limit and meter initcode](#bep-217-implement-eip3860-limit-and-meter-initcode) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#test-cases) + - [8. License](#8-license) + - [9. Reference](#9-reference) + +## 1. Summary + +As part of Shanghai upgrade, EIP-3860: Limit and meter initcode is required to be implemented to BSC. + +## 2. Abstract + +The change introduces a maximum size limit for initcode (MAX_INITCODE_SIZE = 2 * MAX_CODE_SIZE = 49152). Which extended the EIP-170: Contract code size limit + +Furthermore, EIP-3860 introduced a charge of 2 gas for every 32-byte chunk of initcode to represent the cost of jumpdest-analysis. + +Lastly, the size limit results in the nice-to-have property that EVM code size, code offset (PC), and jump offset fits a 16-bit value. + +## 3. Motivation + +Refer to EIP-3860 description: + +During contract creation the client has to perform jumpdest-analysis on the initcode prior to execution. The work performed scales linearly with the size of the initcode. This work currently is not metered, nor is there a protocol enforced upper bound for the size. + +There are three costs charged today: + +1. Cost for calldata aka initcode: 4 gas for a byte with the value of zero, and 16 gas otherwise. +2. Cost for the resulting deployed code: 200 gas per byte. +3. Cost of address calculation (hashing of code) in case of CREATE2 only: 6 gas per word. + +Only the first cost applies to initcode, but only in the case of contract creation transactions. For the case of CREATE/CREATE2 there is no such cost, and it is possible to programmatically generate variations of initcode in a relatively cheap manner. In the past it was possible to craft malicious initcode due to a vulnerability fixed in 2017 by geth 1.6.5. + +Furthermore, the lack of a limit has caused lengthy discussions for some EVM proposals, influencing the design, or even causing a delay or cancellation of a feature. + +It is motivated by three reasons: + +1. Ensuring initcode is fairly charged (most importantly cost is proportional to initcode’s length) to minimize the risks for the future. +2. To have a cost system which is extendable in the future (i.e. for proposals like[ EIP-3670](https://eips.ethereum.org/EIPS/eip-3670)). +3. To simplify EVM engines by the explicit limits (code size, code offsets (PC), and jump offsets fit 16-bits). + +## 4. Specification + +### Parameters + +|Constant|Value| +| --- | --- | +|INITCODE_WORD_COST|2| +|MAX_INITCODE_SIZE|2 * MAX_CODE_SIZE| + +Where MAX_CODE_SIZE is defined by[ EIP-170](https://eips.ethereum.org/EIPS/eip-170) as 24576. + +We define initcode_cost(initcode) to equal INITCODE_WORD_COST * ceil(len(initcode) / 32). + +### Rules + +1. If length of transaction data (initcode) in a create transaction exceeds MAX_INITCODE_SIZE, transaction is invalid. (Note that this is similar to transactions considered invalid for not meeting the intrinsic gas cost requirement.) +2. For a create transaction, extend the transaction data cost formula to include initcode_cost(initcode). (Note that this is included in transaction intrinsic cost, i.e. transaction with not enough gas to cover initcode cost is invalid.) +3. If length of initcode to CREATE or CREATE2 instructions exceeds MAX_INITCODE_SIZE, instruction execution exceptionally aborts (as if it runs out of gas). +4. For the CREATE and CREATE2 instructions charge an extra gas cost equaling to initcode_cost(initcode). This cost is deducted before the calculation of the resulting contract address and the execution of initcode. (Note that this means before or at the same time as the hashing cost is applied in CREATE2.) + +## 5. Rationale + +### Gas cost constant + +The value of INITCODE_WORD_COST is selected based on performance benchmarks of differing worst-cases per implementation. The baseline for the benchmarks is the performance of KECCAK256 hashing in geth 1.10.9, which matches the 70 Mgas/s gas limit target on a 4.0 GHz x86_64 CPU. + +|EVM|version|MB/s|B/CPUcycle|CPUcycle/B|cost of 1 B|cost of 32 B| +| --- | --- | --- | --- | --- | --- | --- | +|geth/KECCAK256|1.10.9|357|1.8|0.6|0.2|6.0| +|geth|1.10.9|1091|5.5|0.2|0.1|2.0| +|evmone/Baseline|0.8.2|727|3.7|0.3|0.1|2.9| +|evmone/Advanced|0.8.2|155|0.8|1.3|0.4|13.8| + +### Gas cost per word (32-byte chunk) + +We have chosen the cost of 2 gas per word based on Geth’s implementation and comparing with KECCAK256 performance. This means the per byte cost is 0.0625. While fractional gas costs are not permitted in the EVM, we can approximate it by charging per-word. + +Moreover, calculating gas per word is compatible with the calculation of CREATE2’s hashcost of[ EIP-1014](https://eips.ethereum.org/EIPS/eip-1014). Therefore, the same implementation may be used for CREATE and CREATE2 with different cost constants: before activation 0 for CREATE and 6 for CREATE2, after activation 2 for CREATE and 6 + 2 for CREATE2. + +### Reason for size limit of initcode + +Estimating and creating worst case scenarios is easier with an upper bound in place, given one parameter for the search is greatly reduced. This allows for selecting a much more optimistic gas per byte. + +Should there be no upper bound, the cost would need to be higher accounting for unknown unknowns. Given most initcode (TODO: state maximum initcode size resulting in deployment seen on mainnet here) does not exceed the proposed limit, penalizing contracts by overly conservative costs seems unnecessary. + +### Effect of size limit of initcode + +In most, if not all cases when a new contract is being created, the resulting runtime code is copied from the initcode itself. For the basic case the 2 * MAX_CODE_SIZE limit allows MAX_CODE_SIZE for runtime code and another MAX_CODE_SIZE for contract constructor code. However, the limit may have practical implications for cases where multiple contracts are deployed in a single create transaction. + +### Initcode cost for create transaction + +The initcode cost for create transaction data (0.0625 gas per byte) is negligible compared to the transaction data cost (4 or 16 gas per byte). Despite that, we decided to include it in the specification for consistency, and more importantly for forward compatibility. + +### How to report initcode limit violation? + +We specified that initcode size limit violation for CREATE/CREATE2 results in exceptional abort of the execution. This places it in the group of early out-of-gas checks, including: stack underflow, memory expansion, static call violation, initcode hashing cost, and initcode cost introduced by this EIP. They precede the later “light” checks: call depth and balance. The choice gives consistency to the order of checks and lowers implementation complexity (out-of-gas checks can be performed in any order). + +## 6. Backwards Compatibility + +This BEP requires a “network upgrade”, since it modifies consensus rules. + +Already deployed contracts should not be affected, but certain transactions (with initcode beyond the proposed limit) would still be includable in a block, but result in an exceptional abort. + +## 7. Test Cases + +Tests should include the following cases: + +* Creation transaction with gas limit enough to cover initcode cost +* Creation transaction with gas limit enough to cover intrinsic cost except initcode cost +* CREATE/CREATE2/creation transaction with len(initcode) at MAX_INITCODE_SIZE +* CREATE/CREATE2/creation transaction with len(initcode) at MAX_INITCODE_SIZE+1 + +## 8. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 9. Reference + +Most description of this BEP refer to [EIP-3860](https://eips.ethereum.org/EIPS/eip-3860): + +Martin Holst Swende ([@holiman](https://github.com/holiman)), Paweł Bylica ([@chfast](https://github.com/chfast)), Alex Beregszaszi ([@axic](https://github.com/axic)), Andrei Maiboroda ([@gumb0](https://github.com/gumb0)), "EIP-3860: Limit and meter initcode [DRAFT]," Ethereum Improvement Proposals, no. 3860, July 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3860. \ No newline at end of file diff --git a/BEPs/BEP221.md b/BEPs/BEP221.md new file mode 100644 index 000000000..2d3a4990e --- /dev/null +++ b/BEPs/BEP221.md @@ -0,0 +1,92 @@ +
+   BEP: 221
+   Title: CometBFT Light Block Validation
+   Status: Draft
+   Type: Standards
+   Created: 2022-04-11
+
+ +# BEP-221: CometBFT Light Block Validation. + +- [BEP-221: CometBFT Light Block Validation.](#bep-221--cometbft-light-block-validation) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [4. License](#4-license) + +## 1. Summary + +This BEP introduces a new precompiled contract to validate the [CometBFT](https://docs.cometbft.com/v0.37/introduction/) light blocks. + +## 2. Motivation + +There are some cross-chain requirements between BSC and CometBFT-compatible blockchains, like the `BNB Greenfield` which +is an important part of the BNB ecosystem, thus we need a gas-friendly solution to validate the light blocks from the +CometBFT-compatible blockchains. + +## 3. Specification + +### 3.1 Consensus State + +To validate the light blocks from the CometBFT-compatible blockchains, there should be a light client of the blockchain +on the BSC side, it could be implemented as a smart contract, and this light client should record the necessary +current state which we call it **Consensus State** to validate the future light blocks. The consensus state is defined as: + +```go +type ConsensusState struct { + ChainID string + Height uint64 + NextValidatorSetHash []byte + ValidatorSet *types.ValidatorSet +} +``` + +The consensus state should be encoded as a part of the precompiled contract's input, and after applying the light block, +the updated consensus state should be encoded as a part of the precompiled contract's output. The encoding format should be: +``` +|--ChainID---|--Height---|--NextValidatorSetHash--|--[{validator pubkey, voting power, relayer address, relayer bls pubkey}]--| +|--32 bytes--|--8 bytes--|--32 bytes--------------|--[{32 bytes, 8 bytes, 20 bytes, 48 bytes}]--------------------------------| +``` + +The `validator pubkey` and `voting power` are necessary for recovering the validator in the current validator set. The +`relayer address` and `relayer bls pubkey` are extended to support some cross-chain infrastructure base on [BLS](https://en.wikipedia.org/wiki/BLS_digital_signature), +we can just pad zero bytes if we don't use `relayer address` or `relayer bls pubkey`. + +### 3.2 Light Block + +A light block of CometBFT-compatible blockchain contains a SignedHeader and a ValidatorSet, which can be imported into +the [CometBFT Light Client](https://docs.cometbft.com/v0.37/spec/light-client/) and update the light client's consensus state accordingly. The light block is defined as: + +```go +type LightBlock struct { + *SignedHeader `json:"signed_header"` + ValidatorSet *ValidatorSet `json:"validator_set"` +} +``` + +The light block itself has a **Marshal** method to convert it into a byte array, and it should be a part of the precompiled +contract's input. Within the precompiled contract, use the **Unmarshal** method to recover it. + +### 3.3 Validate Light Block + +The input of the precompiled contract should include the current consensus state and the future light block. The encoding +format should be: +``` +|--consensus state length--|--consensus state--|--light block--| +|--32 bytes----------------|-------------------|---------------| +``` + +Here are the steps to validate the light block within the precompiled contract: +1. Decode the input to get the current consensus state and the light block. +2. Apply the light block into the current consensus state according to [CometBFT Light Client Verification](https://docs.cometbft.com/v0.37/spec/light-client/verification/). +3. Encode the updated consensus state and return it to the caller. + +The output of the precompiled contract should be encoded as follows: +``` +|--validatorSetChanged--|--empty-----|--consensus state length--|--new consensus state--| +|--1 byte---------------|--23 bytes--|--8 bytes-----------------|-----------------------| +``` + +## 4. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP226.md b/BEPs/BEP226.md new file mode 100644 index 000000000..b95a5c797 --- /dev/null +++ b/BEPs/BEP226.md @@ -0,0 +1,45 @@ +
+    BEP: 226
+    Title: Enable EIP-1559 with base fee of 0
+    Status: Enabled
+    Type: Standards
+    Created: 2023-04-17
+
+ +# BEP-226: Enable EIP-1559 with base fee of 0 + +- [BEP-226: Enable EIP-1559 with base fee of 0](#bep-226-enable-eip-1559-with-base-fee-of-0) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [4. Backwards Compatibility](#4-backwards-compatibility) + - [5. License](#5-license) + + + +## 1. Summary +This BEP introduces [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md) headers and transactions to BSC but with base fee set to 0. + + +## 2. Motivation +To keep up to date with the latest developments in EVM blockchains it is important to keep the block and transaction structures up to date. New features (such as account abstraction) being introduced +to EVM chains already presuppose EIP-1559 type of block headers and transactions. Therefore, for compatibility reasons it is important that EIP-1559 constructs be enabled on BSC. + +EIP-1559 was introduced in Ethereum to improve the gas fee pricing mechanism and to make the ETH token more deflationary, as the base fee would be burnt after a transaction was completed. In BSC there is already a burning mechanism in place ([BEP-95](https://github.com/bnb-chain/BEPs/blob/master/BEP95.md)) so there is no need to burn the base fee. Therefore the base fee will be set to 0, and will +not adjust based on network congestion like in the Ethereum EIP. + + +## 3. Specification + +Essentially the same gas fee mechanism will be kept in place but the extra `BaseFee` field will be enabled in the header (which will be required to be 0). In addition, the `GasTipCap` (a.k.a. `maxPriorityFeePerGas`) and `maxFeePerGas` fields will be enabled by using a dynamic transaction type instead of the legacy transaction types. Since `baseFee` will be 0, `maxPriorityFeePerGas = maxFeePerGas` . + + +The code for EIP-1559 has already been merged from upstream go-ethereum codebase into BSC node codebase, but some custom modifications are still needed (to maintain a constant base fee of 0, and disable extra checks that keep track of the gas utilization over time ) and to ensure everything works correctly before a hard fork enabling this BEP on BSC network. + + +## 4. Backwards Compatibility +Legacy transactions will still work and be included in blocks. This is due to the fact that upgrading from legacy transactions to new transactions results in the legacy transaction's `gas_price ` entirely being consumed either by the `base_fee_per_gas` and the `priority_fee_per_gas`. + + +## 5. License +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP227.md b/BEPs/BEP227.md new file mode 100644 index 000000000..64b0d8a25 --- /dev/null +++ b/BEPs/BEP227.md @@ -0,0 +1,77 @@ +
+    BEP: 227
+    Title: Add BASEFEE opcode
+    Status: Enabled
+    Type: Standards
+    Created: 2023-04-17
+
+ + + +# BEP-227: Add BASEFEE opcode + +- [BEP-227: Add BASEFEE opcode](#bep-227-add-basefee-opcode) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Gas cost](#5-gas-cost) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Test Cases](#7-test-cases) + - [7.1 Nominal case](#71-nominal-case) + - [8. Security Considerations](#8-security-considerations) + - [9. License](#9-license) + + + +## 1. Summary +Adds an opcode that gives the EVM access to the block's base fee. This BEP is dependent on BEP-226 (EIP-1559 with base fee of 0). + +## 2. Abstract + +Add a `BASEFEE (0x48)` that returns the value of the base fee of the current block it is executing in. + +The code for this BEP has already been merged from upstream go-ethereum codebase into BSC node codebase. The work entails enabling EIP-3198 (this BEP) for BSC network configurations and performing a hard fork. + + +## 3. Motivation +The intended use case would be for contracts to get the value of the base fee (introduced by EIP-1559 (BEP-226)). + +## 4. Specification +Add a `BASEFEE` opcode at `(0x48)`, with gas cost `G_base`. + +| Op | Input | Output | Cost | +|:----: |:-----: |:------: |:----: | +| 0x48 | 0 | 1 | 2 | + + + + +### 5. Gas cost +The value of the base fee is needed to process transactions. That means it's value is already available before running the EVM code. +The opcode does not add extra complexity and additional read/write operations, hence the choice of `G_base` gas cost. + +## 6. Backwards Compatibility +There are no known backward compatibility issues with this opcode. + +## 7. Test Cases + +### 7.1 Nominal case +Assuming current block base fee is `7 wei`. +This should push the value `7` (left padded byte32) to the stack. + +Bytecode: `0x4800` (`BASEFEE, STOP`) + +| Pc | Op | Cost | Stack | RStack | +|-------|-------------|------|-----------|-----------| +| 0 | BASEFEE | 2 | [] | [] | +| 1 | STOP | 0 | [7] | [] | + +Output: 0x +Consumed gas: `2` + +## 8. Security Considerations +The value of the base fee is not sensitive and is publicly accessible in the block header. There are no known security implications with this opcode. + +## 9. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP228.md b/BEPs/BEP228.md new file mode 100644 index 000000000..f5add1b0c --- /dev/null +++ b/BEPs/BEP228.md @@ -0,0 +1,83 @@ +
+    BEP: 228
+    Title: Prevent deploying contracts starting with 0xEF
+    Status: Enabled
+    Type: Standards
+    Created: 2023-04-17
+
+ + +# BEP-228: Prevent deploying contracts starting with 0xEF. + +- [BEP-228: Prevent deploying contracts starting with 0xEF.](#bep-228-prevent-deploying-contracts-starting-with-0xef) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 Remarks](#31-remarks) + - [4. Rationale](#4-rationale) + - [5. Test Cases](#5-test-cases) + - [6. Backwards Compatibility](#6-backwards-compatibility) + - [7. Security Considerations](#7-security-considerations) + - [8. License](#8-license) + + +## 1. Summary + +Disallow new code starting with the `0xEF` byte to be deployed. Code already existing in the account trie starting with `0xEF` byte is not affected semantically by this change. + +This BEP essentially enables Ethereum's EIP-3541. The code has been already ported from go-ethereum. What remains is for this BEP to be enabled in a BSC hard fork. + +## 2. Motivation + +Contracts conforming to the EVM Object Format (EOF) are going to be validated at deploy time. In order to guarantee that every EOF-formatted contract in the state is valid, we need to prevent already deployed (and not validated) contracts from being recognized as such format. This will be achieved by choosing a byte sequence for the *magic* that doesn't exist in any of the already deployed contracts. To prevent the growth of the search space and to limit the analysis to the contracts existing before this fork, we disallow the starting byte of the format (the first byte of the magic). + +Should the EVM Object Format proposal not be deployed in the future, the *magic* can be used by other features depending on versioning. In the case versioning becomes obsolete, it is simple to roll this back by allowing contracts starting with the `0xEF` byte to be deployed again. + +## 3. Specification + +After `block.number == HF_BLOCK` new contract creation (via create transaction, `CREATE` or `CREATE2` instructions) results in an exceptional abort if the _code_'s first byte is `0xEF`. + +### 3.1 Remarks + +The *initcode* is the code executed in the context of the *create* transaction, `CREATE`, or `CREATE2` instructions. The *initcode* returns *code* (via the `RETURN` instruction), which is inserted into the account. See section 7 ("Contract Creation") in the Yellow Paper for more information. + +The opcode `0xEF` is currently an undefined instruction, therefore: *It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed.* This means *initcode* or already deployed *code* starting with this instruction will continue to abort execution. + +The exceptional abort due to *code* starting with `0xEF` behaves exactly the same as any other exceptional abort that can occur during *initcode* execution, i.e. in case of abort all gas provided to a `CREATE*` or create transaction is consumed. + +## 4. Rationale + +The `0xEF` byte was chosen because it resembles **E**xecutable **F**ormat. + +Contracts using unassigned opcodes are generally understood to be at risk of changing semantics. Hence using the unassigned `0xEF` should have lesser effects, than choosing an assigned opcode, such as `0xFD` (`REVERT`), `0xFE` (`INVALID)`, or `0xFF` (`SELFDESTRUCT`). Arguably while such contracts may not be very useful, they are still using valid opcodes. + +Analysis in May 2021, on `18084433` contracts in state, showed that there are 0 existing contracts starting with the `0xEF` byte, as opposed to 1, 4, and 12 starting with `0xFD`, `0xFE`, and `0xFF`, respectively. + +## 5. Test Cases + +Each test case below may be executed in 3 different contexts: +- create transaction (no account code) +- `CREATE`, with account code: `0x6000356000523660006000f0151560165760006000fd5b` (Yul code: `mstore(0, calldataload(0)) if iszero(create(0, 0, calldatasize())) { revert(0, 0) }`), +- `CREATE2`, with account code: `0x60003560005260003660006000f5151560185760006000fd5b` (Yul code: `mstore(0, calldataload(0)) if iszero(create2(0, 0, calldatasize(), 0)) { revert(0, 0) }`) + +| Case | Calldata | Expected result | +| -------- | -------- | -------- | +| deploy one byte `ef` | `0x60ef60005360016000f3` | new contract not deployed, transaction fails | +| deploy two bytes `ef00` | `0x60ef60005360026000f3` | new contract not deployed, transaction fails | +| deploy three bytes `ef0000` | `0x60ef60005360036000f3` | new contract not deployed, transaction fails | +| deploy 32 bytes `ef00...00` | `0x60ef60005360206000f3` | new contract not deployed, transaction fails | +| deploy one byte `fe` | `0x60fe60005360016000f3` | new contract deployed, transaction succeeds | + +## 6. Backwards Compatibility + +This is a breaking change given new code starting with the `0xEF` byte will not be deployable, and contract creation will result in a failure. However, given bytecode is executed starting at its first byte, code deployed with `0xEF` as the first byte is not executable anyway. + +While this means no currently executable contract is affected, it does rejects deployment of new data contracts starting with the `0xEF` byte. + +## 7. Security Considerations + +The authors are not aware of any security or DoS risks posed by this change. + +## 8. License + +Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP231.md b/BEPs/BEP231.md new file mode 100644 index 000000000..10b1ef87d --- /dev/null +++ b/BEPs/BEP231.md @@ -0,0 +1,153 @@ +
+  BEP: 231
+  Title: Implement EIP-2930: Optional access lists
+  Status: Enabled
+  Type: Standards
+  Created: 2023-4-19
+
+ +# BEP-231: Implement EIP-2930: Optional access lists +- [BEP-231: Implement EIP-2930: Optional access lists](#bep-231-implement-eip-2930-optional-access-lists) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Motivation](#3-motivation) + - [4. Specification](#4-specification) + - [5. Rationale](#5-rationale) + - [6. Security Considerations](#6-security-considerations) + - [7. License](#7-license) + - [8. Reference](#8-reference) + +## 1. Summary +As part of Berlin upgrade, EIP-2930: Optional access lists is required to be implemented to BSC. + +Adds a transaction type which contains an access list, a list of addresses and storage keys that the transaction plans to access. Accesses outside the list are possible, but become more expensive. + +## 2. Abstract + +We introduce a new [EIP-2718](./eip-2718.md) transaction type, with the format `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])`. + +The `accessList` specifies a list of addresses and storage keys; these addresses and storage keys are added into the `accessed_addresses` and `accessed_storage_keys` global sets (introduced in [EIP-2929](./eip-2929.md)). A gas cost is charged, though at a discount relative to the cost of accessing outside the list. + +## 3. Motivation + +This EIP serves two functions: + +1. Mitigates contract breakage risks introduced by [EIP-2929](./eip-2929.md), as transactions could pre-specify and pre-pay for the accounts and storage slots that the transaction plans to access; as a result, in the actual execution, the SLOAD and EXT* opcodes would only cost 100 gas: low enough that it would not only prevent breakage due to that EIP but also "unstuck" any contracts that became stuck due to EIP 1884. +2. Introduces the access list format and the logic for handling the format. This logic can later be repurposed for many other purposes, including block-wide witnesses, use in ReGenesis, moving toward static state access over time, and more. + +## 4. Specification + +### Definitions + +**`TransactionType`** `1`. See [EIP-2718](./eip-2718.md) + +**`ChainId`** The transaction only valid on networks with this `chainID`. + +**`YParity`** The parity (0 for even, 1 for odd) of the y-value of a secp256k1 signature. + + +### Parameters + +| Constant | Value | +| - | - | +| `FORK_BLOCK` | 12244000 | +| `ACCESS_LIST_STORAGE_KEY_COST` | 1900 | +| `ACCESS_LIST_ADDRESS_COST` | 2400 | + +As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` `1`. + +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is `rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])`. + +The `signatureYParity, signatureR, signatureS` elements of this transaction represent a secp256k1 signature over `keccak256(0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList]))`. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulativeGasUsed, logsBloom, logs])`. + +For the transaction to be valid, `accessList` must be of type `[[{20 bytes}, [{32 bytes}...]]...]`, where `...` means "zero or more of the thing to the left". For example, the following is a valid access list (all hex strings would in reality be in byte representation): + +``` +[ + [ + "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae", + [ + "0x0000000000000000000000000000000000000000000000000000000000000003", + "0x0000000000000000000000000000000000000000000000000000000000000007" + ] + ], + [ + "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", + [] + ] +] +``` + +At the beginning of execution (ie. at the same time as the `21000 + 4 * zeroes + 16 * nonzeroes` start gas is charged according to [EIP-2028](./eip-2028.md) rules), we charge additional gas for the access list: `ACCESS_LIST_ADDRESS_COST` gas per address and `ACCESS_LIST_STORAGE_KEY_COST` gas per storage key. For example, the above example would be charged `ACCESS_LIST_ADDRESS_COST * 2 + ACCESS_LIST_STORAGE_KEY_COST * 2` gas. + +Note that non-unique addresses and storage keys are not disallowed, though they will be charged for multiple times, and aside from the higher gas cost there is no other difference in execution flow or outcome from multiple-inclusion of a value as opposed to the recommended single-inclusion. + +The address and storage keys would be immediately loaded into the `accessed_addresses` and `accessed_storage_keys` global sets; this can be done using the following logic (which doubles as a specification-in-code of validation of the RLP-decoded access list) + +```python +def process_access_list(access_list) -> Tuple[List[Set[Address], Set[Pair[Address, Bytes32]]], int]: + accessed_addresses = set() + accessed_storage_keys = set() + gas_cost = 0 + assert isinstance(access_list, list) + for item in access_list: + assert isinstance(item, list) and len(item) == 2 + # Validate and add the address + address = item[0] + assert isinstance(address, bytes) and len(address) == 20 + accessed_addresses.add(address) + gas_cost += ACCESS_LIST_ADDRESS_COST + # Validate and add the storage keys + assert isinstance(item[1], list) + for key in item[1]: + assert isinstance(key, bytes) and len(key) == 32 + accessed_storage_keys.add((address, key)) + gas_cost += ACCESS_LIST_STORAGE_KEY_COST + return ( + accessed_addresses, + accessed_storage_keys, + gas_cost + ) +``` + +The access list is NOT charged per-byte fees like tx data is; the per-item costs described above are meant to cover the bandwidth costs of the access list data in addition to the costs of accessing those accounts and storage keys when evaluating the transaction. + +## 5. Rationale + +### Charging less for accesses in the access list + +This is done to encourage transactions to use the access list as much as possible, and because processing transactions is easier when their storage reads are predictable (because clients can pre-load the data from databases and/or ask for witnesses at the time the transaction is received, or at least load the data in parallel). + +### Allowing duplicates + +This is done because it maximizes simplicity, avoiding questions of what to prevent duplication against: just between two addresses/keys in the access list, between the access list and the tx sender/recipient/newly created contract, other restrictions? Because gas is charged per item, there is no gain and only cost in including a value in the access list twice, so this should not lead to extra chain bloat in practice. + +### Signature signs over the transaction type as well as the transaction data + +This is done to ensure that the transaction cannot be "re-interpreted" as a transaction of a different type. + +## Backwards Compatibility + +This EIP does make it more gas-expensive to perform "unexpected" SLOADs and account accesses. Because gas is prepaid and so does not affect fixed-gas local calls, it does not break contracts in the way that previous gas cost increases would risk. However, it does make applications that heavily rely on storage access much less economically viable. + +## 6. Security Considerations + +### Access list generation + +Access lists are difficult to construct in real-time in many situations, and this is exacerbated in environments where there is a high time lag between transaction generation and signing or simplicity of the transaction generator is highly valued (eg. either or both may apply in hardware wallets). + +However, this EIP proposes only a 10% initial discount to access lists, so there is almost no cost to not bothering with access list generation and only making a simple transaction. The cost of accessing state outside the access list is expected to be ramped up in future hard forks over time as tools are developed and access list generation becomes more mature. + +### Transaction size bloating + +Average block size will increase as a result of access lists being used. However, the per-byte cost of access lists is `1900 / 32 = 59.375` for storage keys and `2400 / 20 = 120` for addresses, making it much more expensive than calldata; hence, worst-case block size will not increase. Additionally, increases in average block size will be partially compensated for by the ability to pre-fetch storage at time of receiving a transaction and/or load storage in parallel upon receiving a block. + +## 7. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + +## 8. Reference + +Vitalik Buterin (@vbuterin), Martin Swende (@holiman), "EIP-2930: Optional access lists," Ethereum Improvement Proposals, no. 2930, August 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-2930. \ No newline at end of file diff --git a/BEPs/BEP255.md b/BEPs/BEP255.md new file mode 100644 index 000000000..86e8cc87e --- /dev/null +++ b/BEPs/BEP255.md @@ -0,0 +1,70 @@ +
+  BEP: 255
+  Title: Beacon Chain Asset Reconciliation for Security Enhancement
+  Status: Enabled
+  Type: Standards
+  Created: 2023-07-04
+
+ +# BEP-255: Beacon Chain Asset Reconciliation for Security Enhancement + +- [BEP-255: Beacon Chain Asset Reconciliation for Security Enhancement](#bep-255-beacon-chain-asset-reconciliation-for-security-enhancement) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 Asset Reconciliation](#31-asset-reconciliation) + - [3.2 Halt on Reconciliation Error](#32-halt-on-reconciliation-error) + - [4. License](#4-license) + +## 1. Summary + +This BEP proposes implementing on-chain asset reconciliation on BNB Beacon Chain to improve security. + +## 2. Motivation + +As a beacon chain, the BNB Beacon Chain plays a vital role in securing the BNB chain ecosystem. Although some +enhancements have been made to improve cross-chain security, such as BEP171, the security of assets on the BNB Beacon +Chain itself should also be guaranteed, especially after +the [bridge exploitation](https://www.nansen.ai/research/bnb-chains-cross-chain-bridge-exploit-explained). Therefore, +this BEP proposes implementing on-chain asset reconciliation. + +## Specification + +### 3.1 Asset Reconciliation + +There are many tokens issued on the BNB Beacon Chain, and they are highly valued assets to users. Therefore, +reconciliation mainly focuses on the balances of all users. However, with millions of users on the BNB Beacon Chain, it +is impossible to review all accounts and reconcile their balances. Therefore, the following approach is proposed, by +only reconciling the accounts changed in each block: + +* Firstly, the IAVL store is updated to track the storage keys that have been updated in a block. For example, if there + is a transfer transaction in a block, the related sender and receiver's storage keys will be tracked. + +* Secondly, in each EndBlocker, changes in account balances (e.g., transfers) will be calculated as balance changes for + all related accounts, and the related token supply changes (e.g., minting) will be calculated as token supply changes, + by comparing the related values in the current state and previous state with the IAVL trees, which are versioned. + +$$ \Delta_{balance} = \sum ( balance_{current\ state} - balance_{previous\ state} ) $$ + +$$ \Delta_{token\ supply} = \sum ( token\ supply_{current\ state} - token\ supply_{previous\ state} ) $$ + +* Thirdly, asset reconciliation is conducted by comparing whether the balance changes and token supply changes are + equal. If there is a reconciliation error (i.e., unbalanced asset changes), the height will be written to the chain + state, and the blockchain will panic. + +$$ reconciliation\ error\ \iff\ \Delta_{balance} \neq \Delta_{token\ supply} $$ + +### 3.2 Halt on Reconciliation Error + +If a reconciliation error occurs, the blockchain will stop producing new blocks, impacting downstream services such as +bridges, deposits, and withdrawals on exchanges. This drastic action is necessary to protect the chain and its users, so +core developers and community members should investigate the issue as soon as possible. Validators and node operators +should contact the core developers or be prepared to resume the network. + +To bring the blockchain back online, a hard fork is needed. In the fork, the reconciliation error must be addressed +correctly; for example, if exploitation exists, related accounts should be blacklisted or corrected. Once the blockchain +is resumed, downstream services can be brought back up as well. + +## License + +The content is licensed under the [CC0](https://creativecommons.org/publicdomain/zero/1.0/) license. diff --git a/BEPs/BEP294.md b/BEPs/BEP294.md new file mode 100644 index 000000000..718751be3 --- /dev/null +++ b/BEPs/BEP294.md @@ -0,0 +1,200 @@ +
+  BEP: 294
+  Title: BSC Native Staking after BC Fusion
+  Status: Enabled
+  Type: Standards
+  Created: 2023-10-13
+
+ +# BEP-294 BSC Native Staking after BC Fusion + +- [BEP-294: BSC native staking after BC Fusion](#bep-294-bsc-native-staking-after-bc-fusion) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 High Level Framework](#51-high-level-framework) + - [5.2 Staking Hub and Validator](#52-staking-hub-and-validator) + - [5.2.1 Stake Hub](#521-stake-hub) + - [5.2.1.1 Create Validator](#5211-create-validator) + - [5.2.1.2 Distribute Reward](#5212-distribute-reward) + - [5.2.1.3 Update Eligible Validators](#5213-update-eligible-validators) + - [5.2.1.4 Edit Validator](#5214-edit-validator) + - [5.2.2 Validator and Staking Credit](#522-validator-and-staking-credit) + - [5.2.2.1 Delegate](#5221-delegate) + - [5.2.2.2 Undelegate](#5222-undelegate) + - [5.2.2.3 Redelegate](#5223-redelegate) + - [5.2.2.4 Slash](#5224-slash) + - [5.3 Breath Block](#53-breath-block) + - [5.4 Other Function](#54-other-function) + - [5.4.1 Double Sign Slash](#541-double-sign-slash) + - [5.4.2 Fast Finality Vote Violation Slash](#542-fast-finality-vote-violation-slash) + - [6. License](#6-license) + +# 1. Summary + +Native Staking module is incorporating staking logic into the BNB Smart Chain(BSC) and moving this responsibility off the BNB Beacon Chain. The proposal allows BNB holders to stake BNB to the specified validators and get staking rewards on the BSC side directly. After staking, delegators will receive staking credit tokens as a tangible proof of their stake. Staking credit is a token that represents staked BNB on BSC, combining the value of initial deposit + staking rewards. Staking credit is minted upon delegation and burned when undelegated. + +# 2. Abstract + +Native Staking provides various improvements over the existing mechanism: + +- Users are able to participate in staking on the BSC without the requirement of using BNB in BEP2 format. This eliminates the need for conversion and offers users a smoother and more seamless staking experience. + +- Staking credit, as the proof of BNB staked to a specified validator, cannot be transferred. Different validators issue different staking credits. We encourage different application protocols to wrap multi kinds of staking credit into a transferable stBNB or wstBNB which can be seamlessly integrated into DeFi platforms, offering various liquidity options to enhance financial flexibility. + +- In contrast to [BEP153](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP153.md), the latest native staking mechanism brings enhanced user-friendliness and reduced transaction fees. This is accomplished by eliminating the necessity for cross-chain communication at the fundamental level. BEP153 will be disabled before the execution of this BEP. + +- Due to the transition of the underlying implementation from Cosmos to smart contracts, the rewards for staking are no longer automatically distributed to users' wallets on a periodic basis. Instead, they are distributed to the wallet when users undelegate their BNBs. + +Due to the fact that the staking module does not work independently, it often interacts with the consensus engine and the slash module, the impact on these modules is also mentioned in the proposal. + +# 3. Status + +Draft. + +# 4. Motivation + +In order to keep the Simplicity and reuse the good foundation of BNB Beacon Chain(BC), the staking logic of BSC is implemented on BC: + +1. The staking token is BNB, as it is a native token on both blockchains. +2. The staking, i.e. token bond and delegation actions happens on the Beacon Chain. +3. The BSC validator set is determined by its staking and delegation logic, via a staking module built on BC for BSC, and propagated every day UTC 00:00 from BC to BSC via Cross-Chain communication. +4. The reward distribution happens on Beacon Chain around every day UTC 00:00. + +A significant milestone in BC Fusion is transferring functionalities dependent on the Beacon Chain to BSC, thereby empowering BSC with independent running capabilities. In order to achieve a seamless transition, both BSC native staking and BC staking will coexist for a period of time. Afterwards, the cross-chain communication between BSC and BC will be stopped, only the BSC native staking module will work. + +# 5. Specification + +## 5.1 High Level Framework + +In order to achieve a seamless upgrade, both the BSC native staking and BC Cross Chain Staking mechanisms will coexist for a period of time. This will continue until a sufficient amount of voting power (¾+) is migrated to the BSC network. Once this threshold is reached, BC staking will be closed, allowing native staking to operate independently. + +The robustness of the system contracts in BSC has undergone battle testing over time.. To reduce the risks of intrusive modifications caused by native staking, we have implemented three levels of abstraction in our current solution, which enables us to easily add implementations to specific interfaces: + +![5.1 Framework](./assets/bep-294/5.1_framework.png) + +1. **Consensus Engine**. + a. The consensus engine periodically retrieves updates on the validator set from the system contract and utilizes these validator sets to validate the legitimacy of blocks and achieve fast finality. + b. After the production of a block, the consensus engine distributes block rewards to validators and the system reward contract. + c. The consensus engine will penalize the corresponding validator when they go offline. + +2. **Middle Layer Contract**. + a. **Validator Set Contract.** The contract periodically elects a validator set. This can be done by BC sending a cross-chain package to update the validator set to the contract, or by actively retrieving validator set information from the BSC native staking module. The contract also serves as a vault for temporarily storing validator rewards. Periodically, these rewards are sent back to the BC or transferred to the BSC native staking module. + b. **System Reward Contract.** This contract acts as a vault to collect part of transaction fees. The funds are used for various public purposes, like distributing fast finality rewards. + c. **Slash Contract.** This contract is used to keep track of the number of times a validator becomes unavailable and triggers penalties once a certain threshold is reached. Additionally, this contract also handles other types of slash events, such as double signing and malicious voting in fast finality. + +3. **Underlying Interface** + The current staking functionality in BSC is delegated to the Beacon Chain, which in turn affects BSC through cross chain interfaces. These interfaces can be summarized as follows: + a. **Elect Interface.** Validatorset update is propagated every day UTC 00:00 from BC to BSC via Cross-Chain communication. + b. **Reward Interface.** The Validatorset contract transfers the rewards collected on a specific day from BSC to BC through cross-chain communication. Afterwards, the rewards are distributed among delegators based on their respective shares. + c. **Slash Interface.** The Slash contract sends the slash cross-chain packet to BC, triggering the actual jail logic on BC. + +The **Consensus Engine** and **Middle Layer Contract** will remain unchanged in terms of structure and logic. However, we need to add an implementation for BSC Native Staking to the **Underlying Interface**. The specific implementation invoked will depend on the type of validator created. + +## 5.2 Staking Hub and Validator + +![5.2 StakeHub](./assets/bep-294/5.2_stakehub.png) + +The Native Staking module consists of three components: + +- **Stake Hub**: This contract serves as the entry point for managing validators and delegations, while also implementing the logic for slashing specific validators. + +- **Validator Implementation Contract:** This contract implements the logic for users to stake, unstake to a specific validator. It is also the actual implementation of the staking credit contract. + +- **Validator Proxy:** To optimize gas consumption during the creation of validators and facilitate the simultaneous upgrade of all validator contracts, a proxy-based upgradable contract approach is adopted for deploying validator contracts. This allows for efficient deployment and future upgrades of the validators. + +### 5.2.1 Stake Hub + +Stake Hub defines the structure of a Validator. A validator has following fields: + +- **operatorAddress**. The basic information of a validator can be updated by sending a transaction using this account. When a validator exits, the staked deposit can be retrieved using this account. + +- **consensusAddress**. Validator Nodes utilize this account to sign blocks, and other nodes in the network verify the signature to ensure that the block is proposed by a legitimate validator. + +- **voteAddress**. Validator Nodes use this account to participate in fast finality voting. + +- **contractAt.** Each validator has its own contract where staked BNB is temporarily held. + +- **description.** The Validator can have essential information such as a moniker and website. + +- **commission.** Validators receive a portion of the transaction fees as a commission from the block rewards. + +#### 5.2.1.1 Create Validator + +The **operatorAddress** can send a transaction to create a validator,certain conditions must be met: + +- **operatorAddress** must stake an amount equal to or greater than **minSelfDelegationBNB** on its own validator. + +- The transaction should provide proof of possession of the vote key. + +Afterward, a brand-new validator contract will be created, and the corresponding staking credit will be minted. + +#### 5.2.1.2 Distribute Reward + +Every day, a portion of the rewards collected will be directly sent to the operator account of the validator, while the remaining portion will be sent to the corresponding validator contract. + +#### 5.2.1.3 Update Eligible Validators + +The top N validators with the most staked BNB will become the active validator set. This ensures a robust and secure network by prioritizing validators who have demonstrated a significant commitment of BNB tokens. Implementing gas-efficient sorting in smart contracts presents significant challenges. + +![5.3 UpdateEligibleValidators](./assets/bep-294/5.3_update_eligible_validators.png) + +At the first block after UTC 00:00, the consensus engine query the full list of validators through the stake hub contract and retrieve the top N validators using fast sorting. This sorting process takes place within the consensus engine, ensuring high efficiency and not being restricted by the block's gas limit. Then, the consensus engine updates the validator set contract by sending a system transaction that includes the information of the top N validators. + +#### 5.2.1.4 Edit Validator + +The Operator can update a validator's information by sending transactions. The fields that can be updated include: **Consensus Address, Description, Vote Address, and Commission Rate**. Apart from the Description, all other information can only be updated once within a day. Updating the Vote Address requires providing additional proof of vote key possession. + +### 5.2.2 Validator and Staking Credit + +Each validator has its own validator contract that manages staking credit and facilitates the exchange between credit and BNB. The token name of a staking credit is "Stake{{validator moniker}}Credit", and the symbol is "st{{validator moniker}}". + +#### 5.2.2.1 Delegate + +In this contract, an important field to consider is the **totalPooledBNB**, which represents the quantity of BNB held by this contract. **totalPooledBNB** gets two sources of income: One source comes from BNB staked by users, while the other originates from rewards earned by validators for producing blocks. If users stake **bnbAmount**, the amount of credit mint to them is: **stCreditAmount = bnbAmount * totalSupply() / totalPooledBNB**. + +#### 5.2.2.2 Undelegate + +If users decide to unstake their **stCreditAmount**, they will be able to reclaim the equivalent amount of BNB, which will be exactly: **(stCreditAmount * totalPooledBNB) / totalSupply()**. + +To maintain network security and prevent potential compromises caused by incidents resulting in a large number of users unstaking, users must wait for 7 days after initiating a request before they can retrieve their BNB tokens. + +#### 5.2.2.3 Redelegate + +Unlike undelegating, redelegate enables users to unstake their BNB and stake to another validator promptly. + +To discourage potential abuse of this feature, redelegate necessitates a fee payment in BNB, proportionate to the delegated amount. This fee contributes to the rewards of the destination validator's staking pool, with no commission allocated to the validator. + +#### 5.2.2.4 Slash + +When a slash occurs, the contract will burn a specific amount of staking credit owned by the stake hub. The corresponding value of BNB will be transferred to the system reward contract. + +If there is not enough staking credit to be slashed, the validator will be frozen. It won't be elected again until the remaining fine is paid. + +## 5.3 Breath Block + +The first block after UTC 00:00 is called the Breath Block. The consensus engine activates specific logic by transmitting system transactions at breath block: + +- If a validator is in a maintenance state, it will be forcefully exited from that state. + +- The block rewards held from the previous day will be sent to the respective validator contract. + +- The validator offline counter in the Slash contract will be reset. + +- Update top N validator set. + +## 5.4 Other Function + +### 5.4.1 Double Sign Slash + +The double sign slash feature implemented on the Beacon chain needs to be migrated to the BSC contracts. In BSC, a pre-compile contract will be introduced to implement double sign detection logic, which remains consistent with the current implementation. The precompiled contract returns the height of the malicious block headers and the corresponding signer. The contract will slash the validator linked to the signer. + +### 5.4.2 Fast Finality Vote Violation Slash + +Currently, the validation of malicious voting occurs within the BSC contract. However, it does not check for the existence of the validator, but instead sends the cross-chain slash package to the Beacon Chain, which then identifies the validator and carries out the punishment. The Afterward, BSC contract carries out punitive actions using the information it has about all validators. + +# 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP297.md b/BEPs/BEP297.md new file mode 100644 index 000000000..3a4cbd9b8 --- /dev/null +++ b/BEPs/BEP297.md @@ -0,0 +1,153 @@ +
+  BEP: 297
+  Title: BSC Native Governance Module
+  Status: Enabled
+  Type: Standards
+  Created: 2023-10-16
+
+ +# BEP-297: BSC Native Governance Module +- [BEP-297: BSC Native Governance Module](#bep-297-bsc-native-governance-module) +- [1. Summary](#1-summary) +- [2. Abstract](#2-abstract) +- [3. Status](#3-status) +- [4. Motivation](#4-motivation) +- [5. Specification](#5-specification) +- [6. License](#6-license) + +# 1. Summary + +Native Governance is incorporating governance logic into the BNB Smart Chain instead of delegating this responsibility to the BNB Beacon Chain. BSC Native Governance is a primary goal for the BNB Chain Fusion. The proposal allows community members to submit proposals directly on the BSC network. Any staking credit holders are allowed to vote on these proposals, and the passed proposals will be executed automatically on the chain or manually off-chain. + +# 2. Abstract + +Native Governance has several significant differences and improvements compared to current implementations: + +- Any staking credit holders are allowed to propose and vote. +- Voters can continue to earn staking rewards during the voting period. +- Users have the option to delegate someone else to participate in governance on their behalf. +- The proposer can cancel the proposal at any time. +- A time lock period is introduced before the proposal is executed. +- If the proposal is not approved, the proposer won't suffer any financial losses anymore. + +The overall governance framework is derived from [OpenZeppelin Governor](https://docs.openzeppelin.com/contracts/4.x/governance). + +# 3. Status + +Draft. + +# 4. Motivation + +In the framework of the dual-chain structure, the Governance module from Cosmos-SDK is currently being utilized to manage proposals, votes for the BSC network. Subsequently, the tally results are transmitted to the BSC network through a cross-chain protocol, triggering automatic execution, like changing the parameter of system contract, adding whitelist relayers. + +With the progress of BNB Chain Fusion, BNB Beacon Chain no longer exists, thus the governance functionality will be migrated from Beacon Chain to Smart Chain. In addition to addressing migration requirements, this proposal also aims to enhance the existing governance mechanism and encourage more community participation. + +# 5. Specification + +## 5.1 Definitions + +- **BSCGovernor Contract**: A new system smart contract to manage the lifecycle of proposals and votes. +- **GovToken Contract**: A new system contract to manage the user's voting power, the token is not transferable. +- **Staking Credit**: Staking Credit is a cryptocurrency token that aims to represent a BNB that is "staked" to a specific validator on BSC. Different validators on the BSC issue distinct staking credit tokens. + +## 5.2 Proposal Type + +### 5.2.1 Text Proposal + +Text proposals are used to make an on-chain record of support or agreement on a certain topic or ideas. Text proposals do not contain any code. That is, they do not directly cause any direct changes to the BSC once passed. Technically, nothing happens on-chain, but we all get information from it having been considered: + +- The community engaged in a comprehensive and insightful discussion on a topic that would have otherwise been overlooked. +- A development team interested in a feature may have a clearer understanding of how the community will receive their work. +- The community can have a sense of assurance that we share a common understanding or social standard. + +### 5.2.2 Executable Proposal + +An executable proposal is used to make substantial modifications to on-chain protocols in BSC. The **Executable proposal** consists of a list of triplets in the form of **(string key, bytes value, address target)**. +**Target** is the desired target contract. The **key** and **value** represent the parameters for invoking the target contract. The target contract must implement the interface: **function govCall(string key, bytes value)**. + +We use executable proposals in the following scenarios: + +- Change the parameter of the system contract. +- Enable or disable some functionality of the system contract. +- Adding EOAs to play some key role in the system. + +## 5.3 Governance Token + +The lifecycle of staking credit and gov token are identical. +- When users stake, they mint both the staking credit and the governance token. +- Similarly, When users undelegate, both the staking credit and governance token are burned. + +Due to the non-transferability of governance tokens and staking credits, these two scenarios can cover all possible situations. + +In an ideal scenario, the balance of a user's gov token should be equal to the total BNB value of all staking credits held by the user. This condition does not hold true in the following situations: + +1. The validator receives block rewards. +2. User stakes to the validator. +3. User unstakes from the validator. +4. The validator is slashed. + +When the above situation occurs, the protocol will call the **sync** interface of the **GovToken**, either mint or burn gov token to ensure the equation holds true. Scenario #1 is an exception where the **sync** function is not automatically invoked. Users can either manually invoke the **sync** interface or wait for the next stake or unstake operation to occur. + +Token balance does not contribute to voting power directly. Voting power can be increased by directly invoking the **delegate** function or by providing a signature to be used with **delegateBySig**. The contract allows querying the voting power of any account at any height without requiring an archive node. It achieves this by keeping checkpoints of each account's voting power. These features are implemented through inheritance of [ERC20Votes](https://docs.openzeppelin.com/contracts/4.x/api/token/erc20#ERC20Votes). + +## 5.4 Governance Workflow +### 5.4.1 Community Discussion + +BSC governance is driven by the BNB Chain community. Governance discussions occur in various community-moderated platforms such as GitHub, forums, Discord, Twitter, and other channels where the BNB Chain community gathers. Once a proposal is on-chain, it cannot be modified to include feedback. Hence, it is essential to give the proposal enough time off-chain for gathering feedback, input, and edits before advancing it on-chain for voting. While this guide may not cover all possible engagement methods, it offers several suggestions: + +- Post your idea to the [Forum](https://forum.bnbchain.org/). +- Create a [BEP](https://github.com/bnb-chain/BEPs) for your idea. +- Create an issue on the [BSC repo](https://github.com/bnb-chain/bsc) directly. + +### 5.4.2 Create Proposals + +BSC proposals can be managed on UIs integrated with the onchain smart contracts, such as [Tally](https://www.tally.xyz/). Tally is a comprehensive application designed for users to engage in on-chain governance. It offers a user-friendly voting dashboard, intuitive proposal creation wizards, real-time research and analysis tools. With Tally, users can actively participate in the decision-making process and contribute to the growth of BSC. + +To submit an on-chain proposal, a user must have enough voting power to meet the **Proposal Threshold**, such as 100 BNB. Proposers should draft a **Title** and **Description** for the proposal, explain its intent, and include any relevant context for the voters. + +To create an executable proposal, we need to add actions. The call data of the action contains three parts: + +- **Target**. The target contract to call. +- **Key**. **Key** meanings vary across different target contracts, typically indicating the intended purpose. +- **Value**. The meaning of the **Value** parameter varies among different target contracts. Typically, it signifies a modified value. + +To create a text proposal, simply create a proposal without any actions. + +The proposal is delayed to become active after creation. For example, allocate a 3-day timeframe for the community to participate in detailed discussions and establish voting preferences. + +### 5.4.3 Vote on Proposal +Once a proposal is active, **delegates** can vote as only **delegates** have voting power. Staking credit holders who want to participate in governance voting must either select a trusted representative as their delegate or become a delegate themselves by self-delegating their voting power. When governance participants cast their votes, they get three options: + +1. **For** generally means that voter want the proposal to be enacted. +2. **Against** signals that voters do not want the proposal to be enacted. +3. **Abstain**. The voter wishes to contribute to the quorum without voting “for” or “against” a proposal. + +[GovernorPreventLateQuorum](https://docs.openzeppelin.com/contracts/4.x/api/governance#GovernorPreventLateQuorum) extension will be enabled to prevent a single voter from swaying the vote and triggering quorum at the last minute. It ensures that there is sufficient time for the community to react. + +### 5.4.4 Tally + +Following requirements need to be met for a proposal to be accepted by the end of voting period: + +- Quorum: A minimal of 10% of total voting power votes **For**. +- Threshold: The voting power of **For** is larger than **Against**. + +### 5.4.5 Timelock and Execution + +Once a proposal passes, it can be queued and executed. The first step to execution is queueing, this will cause the **Governor Contract** to interact with the timelock contract and queue the actions for execution. After the required delay, anyone is allowed to trigger the execution. + +The community has time to take action on proposals that have been manipulated due to vulnerabilities, fall under spam or violate rules of engagement. However, these actions are often beyond the scope of on-chain protocols, such as validators reaching a consensus to veto a passed proposal through a hard fork. Such a situation should be avoided at all costs. + +## 5.5 Proposal Status +- **Publish.** The proposal is created but not active for vote yet. +- **Active.** The proposal is active for vote. +- **Defeated.** The proposal is rejected. +- **Canceled.** The proposal is canceled. +- **Accepted.** The proposal is passed but not queued yet. +- **Queued.** The proposal is queued in the **TimeLock** contract but not ready for execution. +- **AwaitingExecution.** The proposal is ready for execution after queued. +- **Executed.** The proposal is executed. + + +# 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEP3.md b/BEPs/BEP3.md similarity index 74% rename from BEP3.md rename to BEPs/BEP3.md index 3df27356a..e227789e9 100644 --- a/BEP3.md +++ b/BEPs/BEP3.md @@ -6,46 +6,45 @@ This BEP is about introducing Hash Timer Locked Contract functions and further m # Abstract -[HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) has been used for Atomic Swap and cross payment channel for a few years on Bitcoin and its variant blockchains, and also Ethereum. This BEP defines native transactions to support HTLC on Binance Chain, and also proposes the standard infrastructure and procedure to use HTLC for inter-chain atomic swap to easily create and use pegged token, which is called `Atomic Peg`. +[HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) has been used for Atomic Swap and cross payment channel for a few years on Bitcoin and its variant blockchains, and also Ethereum. This BEP defines native transactions to support HTLC on BNB Beacon Chain, and also proposes the standard infrastructure and procedure to use HTLC for inter-chain atomic swap to easily create and use pegged token, which is called `Atomic Peg`. # Status -This BEP is under implementation. +This BEP is already implemented. # Motivation -Binance Chain serves fast transferring transactions and also high capacity asset Exchange, which have benefits a lot assets issues on it. However, there are major cases Binance Chain itself cannot satisfy: - +BNB Beacon Chain serves fast transferring transactions and high-capacity asset exchange, which greatly benefit assets issued on it. However, there are major cases in which BNB Beacon Chain itself cannot satisfy: 1. Assets have complicated token economies themselves, such as DeFi. 2. Assets serve as native tokens on other blockchain. -For these tokens, the best way to use Binance Chain is to spread the tokens on multiple chains. One can issue or peg part of total token supply on Binance Chain to enjoy the speed, fast finality and powerful exchange, meanwhile keep other benefit and necessity on other chains. Many new requirements are imposed for such model: +For these tokens, the best way to use BNB Beacon Chain is to spread the tokens on multiple chains. One can issue or peg part of total token supply on BNB Beacon Chain to enjoy the speed, fast finality and powerful exchange, meanwhile keep other benefit and necessity on other chains. Many new requirements are imposed for such model: -1. there should be an easy way for users to swap unidirectionally or bidirectionally between Binance Chain and the other chain, better in a trustless way; +1. there should be an easy way for users to swap unidirectionally or bidirectionally between BNB Beacon Chain and the other chain, better in a trustless way; 2. there should be restrictions and/or transparency to ensure the total supply of tokens remained the same, and no one, even the issuer cannot freely change the circulation at will; 3. there should be an easy way to calculate how many tokens are in circulation on each chain of both sides. -Here new transaction and logics are required on Binance Chain, as it doesn’t support Smart Contract. Also a standard infrastructure and procedure should be proposed and used as best practice for such inter-chain communications. +Here new transaction and logics are required on BNB Beacon Chain, as it doesn’t support Smart Contract. Also a standard infrastructure and procedure should be proposed and used as best practice for such inter-chain communications. -The BEP is to tackle the problem, and try to pave the broadway for a practical cross chain solution to empower the decentralized economy with Binance DEX. +The BEP is to tackle the problem, and try to pave the broadway for a practical cross chain solution to empower the decentralized economy with BNB Beacon Chain DEX. # Specification ## Atomic Peg Swap -The primary purpose of HTLC in Binance Chain is to support Atomic Peg Swap (APS). APS is proposed here as the standard way for asset/token issuers to peg or migrate part of the asset/token onto Binance Chain, so that users of the tokens can enjoy the fast transactions and pleasant trading experience. +The primary purpose of HTLC in BNB Beacon Chain is to support Atomic Peg Swap (APS). APS is proposed here as the standard way for asset/token issuers to peg or migrate part of the asset/token onto BNB Beacon Chain, so that users of the tokens can enjoy the fast transactions and pleasant trading experience. APS is designed to support peg token from any EVM based blockchain or any one with full smart contract features. Here in order to simplify the description, Ethereum is used as the most typical example. ### Roles -* **Client**: users who want to swap tokens from Ethereum to Binance Chain, or the other way round. Client address on Binance chain is called **CB** in the following sections; -* **Owner**: the issuers or anyone who want to peg the tokens from Ethereum to Binance Chain. In most cases, the Owner should be the issuer of the token. There expects one or multiple Owners to provide some service for one blockchain/project, depending on the size of the blockchain/project. Pegged Token Owner address on Binance chain is called **OB** in the following sections +* **Client**: users who want to swap tokens from Ethereum to BNB Beacon Chain, or the other way round. Client address on BNB Beacon chain is called **CB** in the following sections; +* **Owner**: the issuers or anyone who want to peg the tokens from Ethereum to BNB Beacon Chain. In most cases, the Owner should be the issuer of the token. There expects one or multiple Owners to provide some service for one blockchain/project, depending on the size of the blockchain/project. Pegged Token Owner address on BNB Beacon chain is called **OB** in the following sections ### Infrastructure Components -* **New transaction types on Binance Chain**: HTLT and CHLT transactions are used to lock and claim the asset to swap. The details are covered in the following section. -* **Swap smart contracts on Ethereum**: the APS contract are used to lock and claim the asset to swap too. The function should be similar to the new transaction types on Binance Chain. The details of interface covered in the following section. +* **New transaction types on BNB Beacon Chain**: HTLT and CHLT transactions are used to lock and claim the asset to swap. The details are covered in the following section. +* **Swap smart contracts on Ethereum**: the APS contract are used to lock and claim the asset to swap too. The function should be similar to the new transaction types on BNB Beacon Chain. The details of interface covered in the following section. * **Deputy process**: an application run and maintained by Owner to facilitate the automatic and continuous swap activity. * **Client tooling**: wallets or other tools that help Clients to monitor the blockchains to complete the claim (and maybe the lock as well). @@ -53,11 +52,11 @@ APS is designed to support peg token from any EVM based blockchain or any one wi #### Preparation Stage -1. Owner should issue proper number of tokens on Binance Chain as the Pegged -2. Owner should create one address on Binance Chain, and transfer in enough number of tokens for swap +1. Owner should issue proper number of tokens on BNB Beacon Chain as the Pegged +2. Owner should create one address on BNB Beacon Chain, and transfer in enough number of tokens for swap 3. Owner should deploy the APS Ethereum smart contract on Ethereum, and deposit enough number of tokens for swap into a dedicated address (which both should be public announced). -4. Client should have an address on both Binance Chain and Ethereum. -5. For such swap, Owner should publish all their Binance Chain and APS contract address, and also the expected minimum time span, MinLockTime. +4. Client should have an address on both BNB Beacon Chain and Ethereum. +5. For such swap, Owner should publish all their BNB Beacon Chain and APS contract address, and also the expected minimum time span, MinLockTime. #### Usage Expectation and Benefits @@ -66,16 +65,16 @@ APS is designed to support peg token from any EVM based blockchain or any one wi 3. Client gets guarantee on their fund safety. They don’t need to worry too much about the availability of the Deputy process, or any cheat from issuers or swap service providers. 4. It is possible for one set of infrastructure to handle swap for multiple tokens. -#### Client Swap Tokens from Ethereum to Binance Chain +#### Client Swap Tokens from Ethereum to BNB Beacon Chain 1. Client calls APS contract, with the hash of a secret, X tokens and a time span T parameters, to express his/her interest to swap X tokens. If the parameters are good (e.g. T>MinLockTime, enough tokens to swap), the call transaction is recorded on the blockchain. -2. Deputy process monitors the events of the APS contract on Ethereum. If it detects the client’s call and verify good, it will sign and broadcast the HTLT transaction on Binance Chain. This will lock X (or more as bonus) number of pegged tokens on Binance Chain. Please note the time span used in this HTLT transaction should be smaller enough than T in Client’s APS call. -3. Client or Client tooling monitors any transactions onto CB, if it is from OB and has the proper hash, Client or Client tooling should broadcast CHLT transaction to claim his/her requested Pegged tokens by disclosing the random number generating the hash. Binance Chain will verify the random number, if it matches the hash, it will release the locked Pegged tokens to Client address CB. +2. The Deputy process monitors the events of the APS contract on Ethereum. If it detects a Client's call and verifies it is valid, it will sign and broadcast the HTLT transaction on BNB Beacon Chain. This will lock X (or more as a bonus) number of pegged tokens on BNB Beacon Chain. Please note that the time span used in this HTLT transaction should be shorter than T in the Client's APS call. +3. Client or Client tooling monitors any transactions onto CB, if it is from OB and has the proper hash, Client or Client tooling should broadcast CHLT transaction to claim his/her requested Pegged tokens by disclosing the random number generating the hash. BNB Beacon Chain will verify the random number, if it matches the hash, it will release the locked Pegged tokens to Client address CB. 4. Deputy process monitors the transactions onto OB. If there is a success CHLT, it will read the value of the random number Client disclosed, and call APS contract to claim the locked tokens by Client. -#### Client Swap Tokens from Binance to Ethereum +#### Client Swap Tokens from BNB Beacon to Ethereum -1. Client sends HTLT transaction to Owner address OB with the hash of a secret, X tokens and a time span T parameters, to express his/her interest to swap X tokens. If the parameter is good, the transaction will be recorded on Binance Chain. +1. Client sends HTLT transaction to Owner address OB with the hash of a secret, X tokens and a time span T parameters, to express his/her interest to swap X tokens. If the parameter is good, the transaction will be recorded on BNB Beacon Chain. 2. Deputy Process monitors the transactions onto OB. If there is a success HTLT, it will double verify the transaction parameters (e.g. T>MinLockTime, enough tokens to swap). If all are good, it will call the APS contract on Ethereum to lock X number of tokens on Ethereum with the hash with shorter time span, expecting to be unlocked by Client address CE. 3. Client or Client tooling monitors events of the APS contract on Ethereum. If it detects Deputy process’s call, it will verify and call the APS contract to claim the tokens by disclosing the random number generating the hash. 4. Deputy process monitors the events from APS contract. If there is a successful claim, it will read the value of the random number Client disclosed and broadcast a CHLT transaction to claim the locked tokens by the Client via the HTLT. @@ -84,10 +83,10 @@ APS is designed to support peg token from any EVM based blockchain or any one wi In the following scenarios, client will need swap between several BEP2 tokens: -1. Users want to swap assets that are not listed on Binance DEX. +1. Users want to swap assets that are not listed on BNB Beacon Chain DEX. 2. Users want to swap several assets with several others at the same time. -For instance, suppose a client has some `BNB` token and want to swap some other BEP2 tokens which are not listed on Binance Dex, like `ABC` and `DEF`: +For instance, suppose a client has some `BNB` token and want to swap some other BEP2 tokens which are not listed on BNB Beacon Chain Dex, like `ABC` and `DEF`: 1. Client send a HTLT transaction to an deputy address who has `ABC` and `DEF`. In the HTLT transaction, the client locks some `BNB` and expresses his expected gained `ABC` and `DEF` amount, for example: `1000ABC,10000DEF`. 2. Deputy process filter out the HTLT transactions in which the `to` equal to deputy address and the swap ratio is reasonalbe. Then the deputy send `Deposit HTLT` transaction to lock some `ABC` and `DEF` under the same hash timer lock. @@ -100,15 +99,15 @@ Client Tooling is the part to help user experience. While the most commonly used 1. start the request of Atomic Peg on either chain of the two, which means sign and broadcast specific transactions, or trigger smart contract with parameters; 2. monitor the blockchain and automatically claim the swapped token (or automatically trigger the refund after the timeout on Ethereum and other blockchains). -3. if the wallet supports multiple blockchain, e.g. both Binance Chain and Ethereum, it will be super convenient for Client to complete the whole swap process within the wallet. +3. if the wallet supports multiple blockchain, e.g. both BNB Beacon Chain and Ethereum, it will be super convenient for Client to complete the whole swap process within the wallet. -## New Transaction Types on Binance Chain +## New Transaction Types on BNB Beacon Chain The below are the details for HTLT, deposit HTLT, claim HTLT and refund HTLT. ### Hash Timer Locked Transfer -Hash Timer Locked Transfer (HTLT) is a new transaction type on Binance Chain, to serve as HTLC in the first step of Atomic Swap, with parameters defined as below: +Hash Timer Locked Transfer (HTLT) is a new transaction type on BNB Beacon Chain, to serve as HTLC in the first step of Atomic Swap, with parameters defined as below: | Name | Type | Description | Optional | | -----| ---- | ----------- | -------- | @@ -167,10 +166,10 @@ Refund Hash Timer Locked Transfer is to refund the locked asset after timelock i 2. `_randomNumberHash`: `sha256(_randomNumber, _timestamp)` 3. `_heightSpan` is the number of blocks to wait before the asset can be refunded 4. `_receiverAddr` is the Ethereum address of swap counter party - 5. `_bep2Sender` the swap sender address on Binance Chain - 6. `_bep2Recipient` is the recipient address on Binance Chain. + 5. `_bep2Sender` the swap sender address on BNB Beacon Chain + 6. `_bep2Recipient` is the recipient address on BNB Beacon Chain. 7. `_outAmount` is the swapped out ERC20 token. - 8. `_bep2Amount` is the expected received BEP2 token on Binance Chain. + 8. `_bep2Amount` is the expected received BEP2 token on BNB Beacon Chain. 2. function **refund**(bytes32 _swapID) 1. `_swapID `: `sha256(swap.randomNumberHash, swap.From, swap.SenderOtherChain)` 3. function **claim**(bytes32 _swapID, bytes32 _randomNumber) diff --git a/BEPs/BEP322.md b/BEPs/BEP322.md new file mode 100644 index 000000000..49057d610 --- /dev/null +++ b/BEPs/BEP322.md @@ -0,0 +1,463 @@ +
+	BEP: 322
+	Title: Builder API Specification for BNB Smart Chain
+	Status: Enabled
+	Type: Standards
+	Created: 2023-11-15
+
+ +# BEP-322: Builder API Specification for BNB Smart Chain + + + +- [BEP-322: Builder API Specification for BNB Smart Chain](#bep-322-builder-api-specification-for-bnb-smart-chain) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Background](#3-background) + - [3.1 BSC Trust Model](#31-bsc-trust-model) + - [3.2 BSC Consensus](#32-bsc-consensus) + - [4 Workflow](#4-workflow) + - [4.1 Definition](#41-definition) + - [4.2 One-Round Interaction (default)](#42-one-round-interaction-default) + - [4.3 Two-Round Interaction (optional)](#43-two-round-interaction-optional) + - [4.4 APIs](#44-apis) + - [4.4.1 Builder APIs](#441-builder-apis) + - [4.4.1.1 Retrieve Transactions](#4411-retrieve-transactions) + - [4.4.1.2 Issues Report](#4412-issues-report) + - [4.4.2 Validator APIs](#442-validator-apis) + - [4.4.2.1 Bid Block](#4421-bid-block) + - [5. Further Discussion](#5-further-discussion) + - [5.1 Implementation Consideration](#51-implementation-consideration) + - [5.2 Payment \& Economic Considerations](#52-payment--economic-considerations) + - [5.3 Builder Registration](#53-builder-registration) + - [6. License](#6-license) + + + +## 1. Summary + +This BEP introduces a suite of interaction processes and API specifications to establish a fairer and more transparent +MEV framework on the BNB Smart Chain. Participants can follow this specification to collaborate on building and +proposing blocks. + +## 2. Motivation + +The Ethereum MEV market is thriving, with +the [Ethereum Builder API Specification](https://github.com/ethereum/builder-specs) widely supported by +mainstream consensus clients. As of October 2023, the inclusion rate of blocks from builders is +approximately [90%](https://dune.com/ChainsightAnalytics/mev-after-ethereum-merge). + +The BNB Smart Chain MEV market still remains at a Wild West stage. The absence of PBS adoption results in a chaotic +landscape with different architectures and API standards. Nowadays, it is very challenging for validators to +to integrate with multiple MEV providers. Moreover, the absence of native support from the BSC clients +further exacerbates the instability of MEV services. To tackle these issues, this BEP proposes compliant guidelines and +standards with the following aims: + +- **Improve Stability**: Unified specifications for both validators and MEV providers to enhance integration and + stabilize the market. + +- **Improve Economy**: A unified architectural specification increases speculators' costs, fostering a healthy market + competition. Validators can extract more value by integrating with multiple MEV providers, which benefits delegators + as well. + +- **Improve Transparency**: This specification aims to bring transparency to the BSC MEV market, exposing profit + distribution among stakeholders to the public. + +## 3. Background + +Before diving into the specification, let's analyze the BSC trust model and its distinctive consensus protocol. + +### 3.1 BSC Trust Model + +Validators in the BNB Smart Chain are considered more trustworthy, as it requires substantial BNB delegation and must +maintain a high reputation. This stands in contrast to Ethereum, where becoming an Ethereum validator is much easier. +As of the end of 2023, there were approximately 40 validators on BSC (with more expected to join) and a total of +20 million BNB staked. In Ethereum, the barrier to becoming a validator is very low (i.e., 32 ETH), leading to over +800,000 Ethereum validators according +to [Nasdaq](https://www.nasdaq.com/articles/the-most-pressing-issue-on-ethereum-is-validator-size-growth). + +Meanwhile, in the Ethereum PBS architecture, the 'relay' role is expected to be trusted by both builders and validators. +However, in BSC, validator misbehavior results in reputation damage and un-delegations, reducing the need for +introducing +another trusted role. In this specification, we eliminate the 'relay' role. However, this adjustment should not +compromise +the security and trust model for the MEV market between builders and validators. + +### 3.2 BSC Consensus + +In Ethereum, a block header is transferred from a builder to a validator for signing, allowing the block to be +broadcasted +to the network without disclosing the transactions to the validator. In contrast, in BSC, creating a valid block header +requires executing transactions and system contract calls (such as transferring reward and depositing to the validator +set contract), making it impossible for builders to propose the whole block. + +## 4 Workflow + +### 4.1 Definition + +- **Builder**: the party that specializes in the construction of BSC execution payloads using transactions received from + searchers and p2p network (trusted by searchers and users for fair inclusion). + +- **Proposer**: the party that signs and submits a block to the network, referred to as the validator. + +- **Mev-sentry**: the party that runs in front of a validator to proxy requests and enhance network security. + +- **Bid**: used by a builder to do competitive bidding for a block space. A bid should include the following + information: + - **block_number**. The height of the block. + - **parent_hash**. The hash of the parent block. + - **gas_fee**. The total gas fee of the bid. + - **gas_used**. The total gas used of the bid. + - **builder_fee**. The fee that the builder would like to take from the validator. + - **txs**. The transaction list in the bid(optional). + - **signature**. The signature of the bid. + +### 4.2 One-Round Interaction (default) + +Builders and validators collaborate to propose blocks during each block production interval. Two interaction options +exist +between them: one-round and two-round. With one-round, builders include transactions with their bids, allowing +validators +to immediately seal a block without additional transaction retrieves. *One-round is the default option for trusted +relationship*. + +workflow + +1) Builders submit bids with transactions to the in-turn validator. +2) The validator picks the most valuable bid from all received within a predefined time. +3) The validator executes the full transactions and verifies the bid (gas received is the same as what claimed in the + bid). +4) If the bid turns out to be invalid, the proposer will use other bid or a locally mined block and also report + detailed errors to the builder. The validator may blacklist the builder for some time or forever if the builder + offers invalid bid. +5) The validator seals the final block. + +In practical settings, opting for a **One-round with MEV-Sentry (optional)** configuration stands out as the optimal +solution +for ensuring both security and efficient payment processes. Subsequently, we will delve into the specific role that +MEV-Sentry can fulfill in the upcoming section. + +### 4.3 Two-Round Interaction (optional) + +Two-round interaction involves builders sending bids without transactions initially. If selected, validators retrieve +transactions through another RPC call before sealing the block. The two-round process is considered more time-consuming +compared to the one-round interaction. *It's suggested to adopt two-round interaction for builders who do not fully +trust validator and are not concerned about the additional latency caused by one extra round of communication.* + +workflow + +1) Builders submit bids without transactions to the in-turn validator. +2) The validator picks the most valuable bid from all received bids within a predefined time. +3) The Validator asks the builder for corresponding transactions related to the chosen bid, and also gives the builder + its signature as a receipt. The builder should return the full list of transactions. +4) The validator executes the transactions and verifies the bid (gas received is the same as what is claimed in the + bid). +5) If the bid turns to be invalid, the proposer will use other bid or a locally mined block and also report detailed + errors to the builder. The validator may blacklist the builder for some time or forever if the builder offers invalid + transactions. +6) The validator seals the final block. + +There are some **edge cases** should be elaborated: + +- If there is no profitable bid compared to local work, the validator should use locally mined block. + +- In two-round interaction, if the validator cannot receive the full list of transactions before timeout, the + validator should use the locally mined block too, and 1) notify the builder using issue report API; 2) blacklist + the builder for a while or even forever. + +- If a builder finds that its transactions are stolen by a validator, the builder should 1) refuse to send bids + to the validator, 2) disclose the steal to public channels for social influences if necessary. + +**Two-Round with MEV-Sentry(optional)** interaction: + +A MEV-Sentry can be used for validators to provide several functionalities. The sentry has its own wallet, +which should be different from the validator's consensus wallet, and append a transfer transaction to send builder fee. +It can also filter bids and only forward the more profitable ones to a validator. Meanwhile, a validator needs to +interact with many builders at the same time, sentry helps to hide the validator’s real IP +information and protect against DDoS and other threats. Therefore, it is highly suggested for validators to run such a +layer in front of itself in production. + +workflow + +After introducing the overall interactions, we would like to highlight some main differences between Ethereum +Builder Specification here for the readers who are familiar with it. + +- As mentioned in the background, the BSC trust model and consensus are different from Ethereum, it is justifiable for + builders to + send transactions to validators after receiving the receipt signature. In case a builder finds a validator stealing + transactions, it can 1) not submit bids to evil validators anymore, 2) reveal evidence to the public channels + (e.g., Discords, Github, blogs) for social influence. + +- In Ethereum, the fee settlement between builders and validators is conducted using the 'coinbase' reward (for reward + to + builders) + and token transfer (for the fee to validators). In BSC, the coinbase reward will be transferred to the system contract + for + later distribution to all delegators. A different way is proposed in this proposal, a validator can run an MEV-Sentry + to append a transfer transaction for payment. It will be further discussed in the later section. + +### 4.4 APIs + +The following APIs are introduced on Builder and BSC client sides, to implement the aforementioned workflows. + +#### 4.4.1 Builder APIs + +The following APIs should be implemented on Builder. + +##### 4.4.1.1 Retrieve Transactions + +This api is used by the validator to ask for full transactions once a builder's bid is chosen. The request body will be +treated as a receipt for payment settlement. + +Request: + +```json +{ + "jsonrpc": "2.0", + "method": "mev_retrieveTransactions", + "params": [ + { + "bid": { + "block": "the block number", + "parentHash": "the hash of the parent block", + "gasFee": "the total gas fee of the bid", + "gasUsed": "the total gas used of the bid", + "builderFee": "the fee that the builder would like to take from the validator" + }, + "signature": "the signature of the bid" + } + ], + "id": 1 +} +``` + +Response: + +```json +{ + "jsonrpc": "2.0", + "result": { + "bid": { + "block": "the block number", + "parentHash": "the hash of the parent block", + "gasFee": "the total gas fee of the bid", + "gasUsed": "the total gas used of the bid", + "builderFee": "the fee that the builder would like to take from the validator", + "txs": [ + "the transactions in the bid" + ] + }, + "signature": "the signature of the bid" + }, + "id": 1 +} +``` + +##### 4.4.1.2 Issues Report + +This API is used to report issues to a builder. For example, if a validator finds that a builder's transactions are +invalid or the transaction API is timeout-ed, a validator can notify the builder. + +Request: + +```json +{ + "jsonrpc": "2.0", + "method": "mev_reportIssue", + "params": [ + { + "validator": "validator address", + "bidHash": "hash of the bid", + "error": { + "code": -38001, + "message": "response message" + } + } + ], + "id": 1 +} +``` + +Response: + +```json +{ + "jsonrpc": "2.0", + "result": null, + "id": 1 +} +``` + +##### 4.4.1.3 Query Bundle Data + +This API enables MEV data analysts to query bundle information from builders. +It is particularly useful for MEV data providers who need to analyze market trends and create analytics dashboards. +For instance, to accurately measure MEV market activity, providers can use this API to display metrics such as +daily bundle counts and bundles per block in their analytics panels. + +Request: + +```json +{ + "jsonrpc": "2.0", + "method": "eth_bundles", + "params": [ + "0x1", + "0x3" + ], + "id": 1 +} +``` + +Params: + +1. String - `FromBlock`, It is the hex value of a block number. +2. String - `ToBlock`, It is either the hex value of a block number OR block tags: "latest", "pending". It should be +no less than `FromBlock` and less than `FromBlock+100`. + +Response: + +* Return bundles whose first-received-height(`receivedBlock`) is within the block range [`FromBlock`, `ToBlock`]. + +```json +{ + "jsonrpc": "2.0", + "result": [ + { + "receivedBlock": "0x1", + "bundles": [ + ["0x88...44b", "0x89..45b"], // tx hase list in the bundle + ["0x90...46b"] + ] + }, + { + "receivedBlock": "0x2", + "bundles": [ + ["0x23...24b", "0x39..45b"], + ["0x43...55a", "0x45..33a", "0x39..45b"] // it is possible that a same tx hash exists in different block + ] + } + ], + "id": 1 +} +``` + +#### 4.4.2 Validator APIs + +The following APIs should be implemented on the validator side or BSC clients. + +##### 4.4.2.1 Bid Block + +This API is used by the builder to submit its bid for the current block production. In general, a proposer will use the +`gas_fee` and `builder_fee_value` (`profit = gas_fee * validator_commission_rate - builder_fee_value`) to find the most +profitable bid. + +Request: + +```json +{ + "jsonrpc": "2.0", + "method": "mev_sendBid", + "params": [ + { + "bid": { + "block_number": 123456, + "parent_hash": "the hash of the parent block", + "txs": [ + "the transactions in the bid" + ], + "gasUsed": 100, + "gasFee": 100000000000, + "builderFee": 100000000000 + }, + "signature": "the signature of the bid" + } + ], + "id": 64 +} +``` + +Response: + +```json +{ + "jsonrpc": "2.0", + "id": 64, + "result": "the hash of the bid" +} +``` + +or some error: +```json +{ + "jsonrpc": "2.0", + "id": 64, + "error": { + "code": -38005, + "message": "the validator is not in-turn to propose currently, try again later" + } +} +``` + +## 5. Further Discussion + +### 5.1 Implementation Consideration + +With a shorter block time of 3 seconds in BSC compared to Ethereum's 12 seconds, designing for time efficiency becomes +crucial. Validators must set a cut-off time to stop receiving new bids, and a timeout to retrieve transactions from +the winning builder. To be more flexible, validators can choose to run a node with or without support for builders, +so a switch should be considered to turn on/off the feature based on its choice. + +block_timing + +### 5.2 Payment & Economic Considerations + +On the BNB Smart Chain, the block reward will be transferred to a system contract by consensus engine and distributed to +delegators and validators based on the staked amount every day. **This distribution mechanism is also applicable to MEV +income.** Without changing bsc consensus rule, the following approaches can be taken for payment + +or the payment from users to builders,both off-chain and on-chain solutions can be considered: + +- Users can subscribe to builders' service. For example, users can pay builder service every month based on different + levels of prices. + +- Users can insert a transfer transaction into his/her bundles to pay the builder. + +For the payment between builders and validators: + +- A validator can run a proxy and append transfer transactions to pay builders. If a validator does not append the + transfer transaction, a builder can still use the receipt (with the validator’s signature) to ask for settlement using + other approaches. + +- A validator and a builder can negotiate other off-chain and on-chain approaches that are out of the scope of the + specification. + +Furthermore, let's also discuss what will happen if a builder or a validator misbehaves. + +- If a builder wins a bid and does not return the full list of transactions to a validator, the validator can easily + detect this + and stop service for the builder. Eventually, the builder will get no income from block production and users + will also leave the builder. + +- If a validator steals transactions from a builder when there is potential value. The victim builder can detect this. + It can stop sending bids to the validator and post evidence (i.e., the signature from a validator) about the + misbehavior. The validator will lose the income from the builder and even more builders. + +### 5.3 Builder Registration + +The process for builders to register to validators is not defined in this specification. However, a promising solution +is highlighted and suggested–using a smart contract for builder registration. + +In BSC, one smart contract can be implemented to provide the following functionalities: + +- a validator can register its information (e.g., consensus address, proxy URL) for participation. +- a builder can deposit some amount of BNB for participation. +- a builder can register to validators by providing its information (e.g., builder address). + +With this kind of smart contract, builders and validators can discover each other easily. It also provides transparency +for all related stakeholders. + +## 6. License + +The content is licensed under +[CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP323.md b/BEPs/BEP323.md new file mode 100644 index 000000000..a2d919430 --- /dev/null +++ b/BEPs/BEP323.md @@ -0,0 +1,105 @@ +
+  BEP: 323
+  Title: Bundle Format for Greenfield
+  Status: Enabled
+  Type: Standards
+  Created: 2023-11-16
+
+ + +# BEP-323: Bundle Format for Greenfield + +- [BEP-323: Bundle Format for Greenfield](#bep-323-bundle-format-for-greenfield) + - [1. Summary](#1-summary) + - [2. Motivation](#2-motivation) + - [3. Specification](#3-specification) + - [3.1 Bundle Format](#31-bundle-format) + - [3.1.1 Encoding](#311-encoding) + - [4. License](#4-license) + +## 1. Summary + +This BEP proposes a solution for better on-chain storage efficiency and user experience in Greenfield by introducing +a method to bundle small files together before uploading. The new system will reduce storage space and costs caused +by small files while increasing the capacity of the entire network. + +## 2. Motivation + +Storing small files in Greenfield is inefficient. The metadata stored on the blockchain can be larger than the files, +leading to higher costs for users. Greenfield Blockchain has a capacity limit to process files simultaneously. + +To tackle this problem, we aim to design a bundle format specifically for Greenfield. This is because a specialized +format will allow developers to build something that fits exactly with what Greenfield and its users need, without +any unnecessary features. By introducing a bundle format, Greenfield can provide a better service to the users and +make sure that Greenfield stays efficient and easy to use as it grows. + +## 3. Specification + +### 3.1 Bundle Format + +The bundle format specifies the structure and organization of the bundle that users create when packing files. +This format is designed to pack flat files; hierarchical directory structures, or folders, are not supported. + +When dealing with a folder, users can simplify its structure by turning it into a series of individual files. +As part of this process, it renames each file to include the folder path. For example, a file originally named +`file.txt` inside the nested folders `dirA` and `dirB` would be renamed to `dirA/dirB/file.txt`. +This approach allows us to maintain the organization of the folder while conforming to the requirement for flat files in the bundle. + +There are still constraints for the bundle format. The file names of the files in the bundle should be unique so that +they can be indexed by the file name. + +The bundle format is structured into several key components as follows: + +* Version: This indicates the version number of the bundle protocol being used. +* Meta Size: This specifies the size of the bundle's metadata, allowing the construction of the bundle structure without the need to read the entire bundle. +* Metadata: This section contains information about the files within the bundle. It facilitates the ability to access files randomly, which means you can jump directly to any file within the bundle without going through all the files. +* Data: This portion represents the actual content and is comprised of all the files in bytes. + +![](./assets/bep-323/bundle_struct.png) + +The Meta structure is designed to include essential attributes for each file, outlined as follows: + +* Object Name: This is the name of the file within the bundle. +* Offset: This attribute marks the starting point of the file's data within the bundle. +* Size: This details the total length, in bytes, of the file. +* Hash Algo: This specifies the algorithm used for the file's hash calculation. +* Hash: This is the cryptographic hash result of the file's content. It serves as a tool for verifying the file's integrity. +* Content Type: This denotes the MIME type of the file, describing the file's nature and format. +* Tags: This is a map that holds various additional properties of the file like `owner` . + +#### 3.1.1 Encoding + +![](./assets/bep-323/bundle_encoding.png) + +The bundle's encoding format is structured as follows: + +* Version: Serialized as an unsigned 64-bit integer, occupying 8 bytes. +* Meta Size: Also an unsigned 64-bit integer, represented using 8 bytes, indicating the size of the metadata section. +* Metadata: Encoded in bytes, this section utilizes Protocol Buffers (protobuf) for serialization. +* Data: This consists of the actual file contents, represented as a sequence of bytes. + +The Meta structure will be serialized with protobuf: + +```java +enum HashAlgo { + Sha256 = 0; +} + +message Meta { + repeated FileMeta meta = 1; +} + +message FileMeta { + string object_name = 1; + uint64 offset = 2; + uint64 size = 3; + HashAlgo status = 4; + bytes hash = 5; + string content_type = 6; + map tags = 7; +} +``` + +## 4. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEPs/BEP333.md b/BEPs/BEP333.md new file mode 100644 index 000000000..c7d3be558 --- /dev/null +++ b/BEPs/BEP333.md @@ -0,0 +1,238 @@ +
+  BEP: 333
+  Title: BNB Chain Fusion
+  Status: Enabled
+  Type: Standards
+  Created: 2023-11-29
+
+ +# BEP-333: BNB Chain Fusion + +[BEP-333: BNB Chain Fusion](#bep-333-bnb-chain-fusion) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Introduction](#51-introduction) + - [5.2 Multiple Phases](#52-multiple-phases) + - [6. License](#6-license) + +## 1. Summary + +This BEP proposes to securely and smoothly transit the BNB Beacon Chain +and BNB Smart Chain (BSC) from a dual-chain structure into a single chain +structure and decommission the Beacon Chain. + +## 2. Abstract + +BNB Chain Fusion (BC Fusion) is a major achievement for BNB Chain. It +helps overcome legacy services and technical debt, enabling faster +iteration and development. BC Fusion includes three sub-BEPs: + +- [BEP-294: BSC Native Staking](https://github.com/bnb-chain/BEPs/pull/294) + +- [BEP-297: BSC Native Governance](https://github.com/bnb-chain/BEPs/pull/297) + +- [BEP-299: Token Migration after BC Fusion](https://github.com/bnb-chain/BEPs/pull/299) + +This BEP primarily proposes strategic planning and coordination for +organizing these BEPs. The goal is to facilitate the secure and seamless +implementation of BC Fusion. + +## 3. Status + +This BEP is a draft. + +## 4. Motivation + +BNB Beacon Chain is a blockchain developed by the BNB Chain community +that implements a vision of a decentralized exchange (DEX) for digital +assets. Besides this, Beacon Chain and BSC is a dual-chain structure: +Beacon Chain helps to enhance the security of BSC as a staking and +governance layer. With the rise of various other forms of Dex, +order-book based decentralized exchange was decommissioned in +[BEP151](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP151.md). +With the quick evolution of BSC, the Beacon Chain has become a burden. +The cross-chain bridge that connects the two chains slows down the +development iteration and always exposes BNB to a certain level of +security vulnerabilities. It\'s time to take a step further and migrate +the functionality of Beacon Chain to BSC, allowing Beacon Chain to +retire. + +## 5. Specification + +### 5.1 Introduction + +The Beacon Chain currently possesses several key functionalities: + +1. Cryptocurrency management platform. The Beacon Chain mainnet + currently supports a hundred kinds of [BEP2](https://explorer.bnbchain.org/assets/bep2) + and [BEP8](https://explorer.bnbchain.org/assets/bep8) + tokens. These tokens have value and can be circulated on the + Beacon Chain or transferred across different chains using + protocols such as [BEP3](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP3.md). + +2. The staking layer of BSC. The BSC utilizes the POSA consensus + algorithm. It delegates staking election and reward distribution + functions to the Beacon Chain. This design choice was based on the + fact that the Beacon Chain is built on the cosmos-sdk + architecture, which already includes a well-developed staking + module that can be reused. + +3. The governance layer of BSC. For similar reasons, the governance + functionality of BSC is delegated to the Beacon Chain as well. The + governance vote and tally happen on Beacon Chain, and the + execution plan is delivered to the BSC through cross chain + communication protocol. + +Therefore, we have three separate BEPs that discuss how to migrate these +functionalities or valuable assets to BSC. + +1. [BEP-299](https://github.com/bnb-chain/BEPs/pull/299): + This BEP presents a secure and trustless way for users to recover + their assets on the BSC once the Beacon chain stops running. + +2. [BEP-294](https://github.com/bnb-chain/BEPs/pull/294): + This BEP allows BNB holders to stake BNB to the specified + validators and get staking rewards on the BSC side directly. To + ensure network security, the migration of Staking voting power is + designed to be seamless. This means that both the Beacon Chain and + BSC\'s staking modules will coexist and function simultaneously + during the migration process. + +3. [BEP297](https://github.com/bnb-chain/BEPs/pull/297): + This BEP allows community members to submit proposals directly on + the BSC network. The governance module is fully compatible with + [Tally](https://www.tally.xyz/). + +### 5.2 Multiple Phases + +To accomplish BC Fusion, there will be several preparation and +post-action steps involved, connecting these BEPs together. Thus, BC +Fusion is divided into multiple stages: + +![multiple phases](./assets/bep-333/phases.png) + +#### 5.2.1 First Sunset Fork + +Due to the requirement of returning cryptocurrency to the user\'s wallet +in order to migrate funds to BSC through +[BEP-299](https://github.com/bnb-chain/BEPs/pull/299). The +Beacon Chain will disable specific types of transactions to encourage +users to keep their funds in their own wallets. The following types of +Beacon chain transactions will be disabled: **TimeLockMsg**, +**TimeRelockMsg**, **FreezeMsg**, **IssueMsg**, **MintMsg**, +**IssueMiniMsg**, **HTLTMsg**, **DepositHTLTMsg**. + +During the migration process, Beacon Chain prohibits the creation and +editing of validators to prevent conflicts with validators created on +BSC side. New delegations will also be prohibited. +The following types of Beacon chain transactions will be +disabled: **MsgCreateValidatorOpen**, **MsgCreateSideChainValidator**, +**MsgCreateSideChainValidatorWithVoteAddr**, +**MsgEditSideChainValidatorWithVoteAddr**, **MsgSideChainDelegate**, +**MsgSideChainReDelegate**. + +To ensure that the voting power migration process is not maliciously +manipulated, the Governance module will be automatically disabled when +the voting power is below 5M BNB. + +The above-mentioned features will be enabled in Beacon Chain +**FirstSunsetFork**. + +#### 5.2.2 BSC Feynman Hardfork + +[BEP-294](https://github.com/bnb-chain/BEPs/pull/294), +[BEP-297](https://github.com/bnb-chain/BEPs/pull/297) and +[BEP-299](https://github.com/bnb-chain/BEPs/pull/299) will +be deployed in the BSC **Feynman** hard fork. + +1. [BEP-294](https://github.com/bnb-chain/BEPs/pull/294) + will take effect immediately. Validators created on BSC will + receive triple voting power when staking an equal amount of BNB. + This encourages the transfer of voting power from the Beacon Chain + to BSC. + +2. The [BEP-297](https://github.com/bnb-chain/BEPs/pull/297) + governance functionality will not be activated immediately after + the hardfork. It will only be automatically enabled once more than + 10 million BNB are migrated to BSC. + +3. The smart contract of [BEP-299](https://github.com/bnb-chain/BEPs/pull/299) + is not available as the merkel root in the smart contract is still + empty at this time. Only after the Beacon Chain comes to a + complete halt, the Token Migration feature will be initiated by + setting the Merkle root for balance dump through governance. + +4. Cross-chain re-delegation, which allows users to un-delegate their stakes + from Beacon Chain and then delegate them on BSC in one Beacon Chain transaction, + will be enabled after governance opening the related cross-chain channel. + +An important wallet will be introduced in this hardfork: +**AssetProtector.** **AssetProtector** is a multi-signature wallet +controlled by the core dev team at the beginning. It can: + +- Pause and unpause the staking, governance and token migration + contract in emergency situations. + +- Forbidden a specific account to perform any operations in the + staking contract. + +#### 5.2.3 Second Sunset Fork + +After transferring more than two-thirds of the voting power to BSC, the +Beacon Chain must restrict additional transaction types and +automatically execute specific logic to ensure the return of funds to +users\' wallets. The following transactions will be disabled: +**MsgSideChainSubmitProposal**. + +All TimeLock and AtomicSwap will automatically be refunded to the +user\'s wallet. All the BSC delegation will be undelegated +automatically, if the delegation comes through +[BEP153](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP153.md), +the funds will be sent back to the BSC network. + +#### 5.2.4 Final Sunset Fork + +Before executing Final Sunset, users still have the opportunity to +transfer funds across chains. However, after Final Sunset, cross-chain +communication between the Beacon Chain and BSC will be completely +stopped. + +After Sunset Fork, the validators in the Beacon Chain community will +gradually shut down, and the entire chain will no longer accept new +transactions or propose new blocks. + +Some of the funds will be permanently locked: + +1. The total amount of staking funds for validators on the Beacon Chain + itself is approximately 110k BNB. + +2. On the Beacon Chain, the BEP2/BEP8 tokens that are not mirrored or + bound to BSC. + +3. The [BEP153](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP153.md) + staking reward that is less than 0.1BNB or staked value which is + less than 0.01BNB will be locked forever. + +**All these funds are not recoverable after the Final Sunset Fork.** + +#### 5.2.5 Post BC Fusion + +- The core dev team will dump the ledger of Beacon Chain and generate + a merkle tree. The data will be publicly reviewed for about 1 + month. + +- A governance proposal will be submitted to set the merkel root and + approver account of the token migration contract. + +- A dapp will be provided for token migration from Beacon Chain to + BSC. + +- All the blockchain data of Beacon Chain will be uploaded to + Greenfield, Filecoin and Arweave for archive. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEP39.md b/BEPs/BEP39.md similarity index 81% rename from BEP39.md rename to BEPs/BEP39.md index 234cbd81e..486045e31 100644 --- a/BEP39.md +++ b/BEPs/BEP39.md @@ -11,27 +11,27 @@ ## 1. Summary -This BEP describes an improvement to the [Transfer Websocket](https://docs.binance.org/api-reference/dex-api/ws-streams.html#3-transfer). +This BEP describes an improvement to the Transfer Websocket. ## 2. Abstract BEP-39 requests that `MEMO` data field be added to the `/ws/userAddress` websocket. -Currently the `MEMO` field is not being returned on the websocket, which means that services that rely on `MEMO` to set transaction specifications must then retrieve it from the [Transaction API endpoint](https://docs.binance.org/api-reference/dex-api/paths.html#transaction). +Currently the `MEMO` field is not being returned on the websocket, which means that services that rely on `MEMO` to set transaction specifications must then retrieve it from the Transaction API endpoint. -This creates unneccessary burden on the API and slows down the transaction processing. +This creates unnecessary burden on the API and slows down the transaction processing. The solution is to add it to the Transfer Websocket as a data field to stream. ## 3. Status -This BEP is under specification. +This BEP is already implemented. ## 4. Motivation Wallets, exchanges, dApps and other services will set transaction state in the `MEMO` to allow them to be stateless. -To improve the speed at which the `MEMO` field can be read and processed, it should be added to the websocket so it doesn't burden Binance Node API endpoints, which are rate-limited. +To improve the speed at which the `MEMO` field can be read and processed, it should be added to the websocket so it doesn't burden BNB Beacon Chain Node API endpoints, which are rate-limited. ## 5. Specification diff --git a/BEP6.md b/BEPs/BEP6.md similarity index 91% rename from BEP6.md rename to BEPs/BEP6.md index 549f05377..23e032155 100644 --- a/BEP6.md +++ b/BEPs/BEP6.md @@ -1,7 +1,7 @@ # BEP-6: Delist Trading Pairs ## 1. Summary -This BEP describes a proposal for delisting trading pairs from the Binance DEX. +This BEP describes a proposal for delisting trading pairs from the BNB Beacon Chain DEX. ## 2. Abstract Listing new trading pairs is done via listing proposals. Suppose a token has a crediting issue or one of its trading pairs has little trading volume for a long time, the community might consider to drop related trading pairs to save network cost. This BEP proposes a method to delist trading pairs via governance. The below picture describes the overview of how delist logic works. @@ -49,14 +49,13 @@ The DelistTradingPair proposal is similar to a governance proposal. It requires | InitialDeposit | coins | Initial deposit paid by sender. Must be strictly positive | | VotingPeriod | int | Length of the voting period| -For other document about governance proposal, please refer to this page: https://docs.binance.org/governance.html#proposal-parameters ### 5.2 Cooling-Off Period Once a `DelistTradingPair` proposal is passed, it will enter a cooling-off period. The cooling-off period lasts until the next UTC 00:00 after the 72-hour point of the proposal passing. As the name suggests, users should re-evaluate the market and take action on the proposed asset to be delisted. In this period, users can still create new orders and cancel orders on the trading pair. Once this period has ended, all outstanding orders will expire. ### 5.3 Delist Delisting happens on the next UTC 00:00 after the 72-hour point of the proposal passing. There are 2 steps to delist trading pairs as below. #### 5.3.1 Trading Pairs Constraint Check -For Binance Chain, all listed tokens requires `BNB` as an initial base pair. Suppose there are three tokens on binance chain: `A`, `B` and `BNB`, and there is only one trading pair: `A_BNB`. If someone wants to create a new `A_B` trading pair, he must create the `B_BNB` trading pair first. +For BNB Beacon Chain, all listed tokens requires `BNB` as an initial base pair. Suppose there are three tokens on BNB Beacon Chain: `A`, `B` and `BNB`, and there is only one trading pair: `A_BNB`. If someone wants to create a new `A_B` trading pair, he must create the `B_BNB` trading pair first. In conclusion, a `non-BNB` trading pair `A_B` will depend on two other trading pairs: `A_BNB` and `B_BNB`, and any `BNB` related trading pair may be the dependency of other trading pairs. diff --git a/BEP64.md b/BEPs/BEP64.md similarity index 94% rename from BEP64.md rename to BEPs/BEP64.md index dbf5f7fd9..f3590dde4 100644 --- a/BEP64.md +++ b/BEPs/BEP64.md @@ -24,7 +24,7 @@ This BEP is derived and extended from bip-0021 ## 1. Abstract -This BEP proposes a URI scheme for making Binance Chain payments. +This BEP proposes a URI scheme for making BNB Beacon Chain payments. ## 2. Motivation The purpose of this URI scheme is to enable users to easily make payments by simply clicking links on webpages or scanning QR Codes. @@ -33,7 +33,7 @@ The purpose of this URI scheme is to enable users to easily make payments by sim ### 3.1 General rules for handling -Binance Chain clients MUST NOT act on URIs without getting the user's authorization. +BNB Beacon Chain clients MUST NOT act on URIs without getting the user's authorization. They SHOULD require the user to manually approve each payment individually, though in some cases they MAY allow the user to automatically make this decision. @@ -74,7 +74,7 @@ The scheme component ("bnb:") is case-insensitive, and implementations must acce * asset: entire asset name, including the "-XXX" random suffix. For BNB, it will be just "BNB", or just don't provide this parameter to take BNB as default value. -* amount: how much of this asset will be transfered +* amount: how much of this asset will be transferred * (others): optional, for future extensions @@ -97,7 +97,7 @@ They SHOULD choose a format that is foremost least confusing, and only after tha ## 4. Rationale ### 4.1 Payment identifiers, not person identifiers -It's not feasible to have a unique address should be used for every transaction on Binance Chain. +It is not feasible to use a unique address for every transaction on BNB Beacon Chain. Therefore, the best practices are that using different memos as distinguishers. ### 4.2 Accessibility (URI scheme name) @@ -113,7 +113,7 @@ Also, very likely, what he will find are mostly technical specifications - not t Variables which are prefixed with a req- are considered required. If a client does not implement any variables which are prefixed with req-, it MUST consider the entire URI invalid. Any other variables which are not implemented, but which are not prefixed with a req-, can be safely ignored. ## 6. Backward compatibility -Currently no URI like `bnb:` is adopted by any exising wallet, all clear here. +Currently no URI like `bnb:` is adopted by any existing wallet, all clear here. ## 7. Appendix diff --git a/BEP67.md b/BEPs/BEP67.md similarity index 69% rename from BEP67.md rename to BEPs/BEP67.md index a188a0cb1..10437a657 100644 --- a/BEP67.md +++ b/BEPs/BEP67.md @@ -1,6 +1,6 @@ # BEP-67: Price-based Order Expiration -- [BEP-67: Price-based Order Expiration](#bep-67-Price-based-order-expiration) +- [BEP-67: Price-based Order Expiration](#bep-67-price-based-order-expiration) - [1. Summary](#1-summary) - [2. Abstract](#2-abstract) - [3. Status](#3-status) @@ -8,19 +8,20 @@ - [5. Specification](#5-specification) - [5.1 Order Expiration](#51-order-expiration) - [5.2 Change Impact](#52-change-impact) + - [5.2.1 Impact on Trader](#521-impact-on-trader) + - [5.2.2 Impact on BNB Beacon Chain](#522-impact-on-bnb-beacon-chain) - [6. License](#6-license) ## 1. Summary -This BEP describes an enhancement of the [Order Expiration](https://docs.binance.org/faq.html#what-is-order-expire). +This BEP describes an enhancement of the Order Expiration. ## 2. Abstract -Currently orders on Binance Chain will be expired after 3 days. Order cannot live long on the market even their price stays competitive, which is not convenient and incurs cost to traders. The solution is to keep orders in the best 500 price levels for 30 days rather than 3 days. +Currently orders on BNB Beacon Chain will be expired after 3 days. Order cannot live long on the market even their price stays competitive, which is not convenient and incurs cost to traders. The solution is to keep orders in the best 500 price levels for 30 days rather than 3 days. ## 3. Status - -This BEP is under specification. +This BEP is already implemented. ## 4. Motivation @@ -37,7 +38,7 @@ After the implementation of BEP-67, those orders in the best 500 price levels on ### 5.2 Change Impact #### 5.2.1 Impact on Trader For those traders who follow current strict 3-day expiration time, they may need change their order placement strategy. -#### 5.2.2 Impact on Binance Chain +#### 5.2.2 Impact on BNB Beacon Chain There could be more orders in node memory. So the compulsory expiration is introduced for the orders older than 30 days. ## 6. License diff --git a/BEP70.md b/BEPs/BEP70.md similarity index 72% rename from BEP70.md rename to BEPs/BEP70.md index 5aded9370..8b2f9831c 100644 --- a/BEP70.md +++ b/BEPs/BEP70.md @@ -1,6 +1,6 @@ # BEP70: List and Trade BUSD Pairs -- [BEP-70: List and Trade BUSD Pairs](#bep-70-list-and-trade-buse-pairs) +- [BEP70: List and Trade BUSD Pairs](#bep70-list-and-trade-busd-pairs) - [1. Summary](#1-summary) - [2. Abstract](#2-abstract) - [3. Status](#3-status) @@ -16,14 +16,14 @@ This BEP describes a proposal for listing and trading BUSD pairs without explicit dependency on the native token BNB. ## 2. Abstract -BUSD, as one of the most influential stable coins worldwide and the most dominant stable coin on Binance Chain, is playing an important role for trading and communicating with fiat currencies. Listing and trading BUSD pairs on Binance Chain will facilitate token owners and exchange traders, making the markets more liquid and healthier. +BUSD, as one of the most influential stable coins worldwide and the most dominant stable coin on BNB Beacon Chain, is playing an important role for trading and communicating with fiat currencies. Listing and trading BUSD pairs on BNB Beacon Chain will facilitate token owners and exchange traders, making the markets more liquid and healthier. -However, on Binance Chain now, if you want to trade between your token and BUSD , you must firstly list a trading pair between BNB and the token you have, which could be unnecessary sometimes. +However, on BNB Beacon Chain now, if you want to trade between your token and BUSD , you must firstly list a trading pair between BNB and the token you have, which could be unnecessary sometimes. This BEP proposes the solutions for listing and trading BUSD pairs without explicit dependency on BNB. ## 3. Status -Draft +This BEP is already implemented. ## 4. Motivation The purpose of this BEP are @@ -37,9 +37,6 @@ Currently, for listing a trading pair between AAA and BUSD, there are following + Existed trading pair between AAA and BNB + Existed trading pair between BUSD and BNB -For more information about governance proposal, please refer to the following page: -[https://docs.binance.org/governance.html](https://docs.binance.org/governance.html) - #### 5.1.2 Proposed Changes For proposing and listing BUSD trading pairs, BUSD must be the base asset or quote asset. It means the BaseAssetSymbol or QuoteAssetSymbol must be BUSD-BD1 on the mainnet, and QuoteAssetSymbol or BaseAssetSymbol does not have to be BNB. @@ -53,9 +50,6 @@ With the proposed changes, for listing a trading pair between AAA and BUSD, the ### 5.2 Trading Fee Calculation To calculate the trading fees, the price of BNB denominated in BUSD will be used if needed. -For more information about trading fees, please refer to the following page: -[https://docs.binance.org/trading-spec.html](https://docs.binance.org/trading-spec.html) - ## 6. License The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). \ No newline at end of file diff --git a/BEP8.md b/BEPs/BEP8.md similarity index 88% rename from BEP8.md rename to BEPs/BEP8.md index d62772b17..6ddf25efa 100644 --- a/BEP8.md +++ b/BEPs/BEP8.md @@ -6,7 +6,7 @@ - [3. Status](#3--status) - [4. Motivation](#4--motivation) - [5. Specification](#5--specification) - - [5.1 Mini-BEP2 Token on Binance Chain](#51-mini-bep2-token-on-binance-chain) + - [5.1 Mini-BEP2 Token on BNB Beacon Chain](#51-mini-bep2-token-on-bnb-beacon-chain) - [5.2 Mini-BEP2 Token Properties](#52-mini-bep2-token-properties) - [5.3 Token Management Operation](#53-token-management-operation) - [5.3.1 Issue Mini-BEP2 Tokens](#531-issue-mini-bep2-tokens) @@ -25,18 +25,18 @@ ## 1. Summary -This BEP describes a proposal for Mini-BEP2 token management on the Binance Chain. +This BEP describes a proposal for Mini-BEP2 token management on the BNB Beacon Chain. ## 2. Abstract -BEP-8 Proposal describes a common set of rules for Mini-BEP2 token management within the Binance Chain ecosystem. It introduces the following details of Mini-BEP2 token on Binance Chain: -- What information makes a Mini-BEP2 token on Binance Chain -- What actions can be performed on a Mini-BEP2 token on Binance Chain +BEP-8 Proposal describes a common set of rules for Mini-BEP2 token management within the BNB Beacon Chain ecosystem. It introduces the following details of Mini-BEP2 token on BNB Beacon Chain: +- What information makes a Mini-BEP2 token on BNB Beacon Chain +- What actions can be performed on a Mini-BEP2 token on BNB Beacon Chain - How Mini-BEP2 token trading is different from BEP2 token trading ## 3. Status -Draft +This BEP is already implemented, and it has been improved via [BEP87](./BEP87.md). ## 4. Motivation @@ -53,7 +53,7 @@ Different from the normal BEP2, using a mini-token system is good at: ## 5. Specification -### 5.1 Mini-BEP2 Token on Binance Chain +### 5.1 Mini-BEP2 Token on BNB Beacon Chain A new module “miniToken” should be created for Mini-BEP2 token. The Mini-BEP2 token should be stored in an independent blockchain storage from BEP2 token. Most BEP2 transaction types, including transfer/multisend, mint/burn and freeze/unfreeze will be reused by Mini-BEP2 token, except issue and list. The minimum amount of Mini-BEP2 Token in any of such transactions should be above a threshold in order to limit the number of Mini-BEP2 token holders and network resource consumption. Besides, the issue/listing fees are much cheaper than BEP2 token and the Mini-BEP2 token can be listed by the issuer directly without voting. ### 5.2 Mini-BEP2 Token Properties @@ -68,7 +68,7 @@ A new module “miniToken” should be created for Mini-BEP2 token. The Mini-BEP ### 5.3 Token Management Operation #### 5.3.1 Issue Mini-BEP2 Tokens -Issuing token is to create a new Mini-BEP2 token on Binance Chain. The new Mini-BEP2 token name should have a four-letter autogenerated suffix and the 4th letter should be “M”. The issue fee is different from the BEP2 token’s. +Issuing token is to create a new Mini-BEP2 token on BNB Beacon Chain. The new Mini-BEP2 token name should have a four-letter autogenerated suffix and the 4th letter should be “M”. The issue fee is different from the BEP2 token’s. User can send either issue-mini or issue-tiny transaction to issue Mini-BEP2 token with different total supply range. Please see below **TokenType** field for details. **Data Structure for Issue Operation**: A data structure is needed to represent the new Mini-BEP2 token: @@ -104,11 +104,11 @@ The data in all the above fields are not changeable after the Issue Transaction, **Issue Process:** -- Issuer signed an issue-tiny or issue-mini transaction and broadcast it to one of Binance Chain nodes -- This Binance Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other Binance Chain nodes +- Issuer signed an issue-tiny or issue-mini transaction and broadcast it to one of BNB Beacon Chain nodes +- This BNB Beacon Chain node will check this transaction. If there is no error, then this transaction will be broadcasted to other BNB Beacon Chain nodes - Issue transaction is committed on the blockchain by block proposer - Validators will verify the constraints on total supply and symbol and deduct the fee from issuer’s account -- New token’s symbol is generated based on the transaction hash. It is added to the issuer’s address and token info is saved on the Binance Chain +- New token’s symbol is generated based on the transaction hash. It is added to the issuer’s address and token info is saved on the BNB Beacon Chain #### 5.3.2 Transfer Tokens The transaction type, message structure and transaction process are the same as BEP2 5.3.2 Transfer Tokens. The difference from BEP2 transfer is that the Mini-BEP2 transfer amount should be larger than or equal to 1, unless the sender sends the total amount of the free Mini-BEP2 token in his account. @@ -153,7 +153,7 @@ The list process is different from BEP2 token list. Mini-BEP2 token issuer can l #### 5.4.2 Order placement The minimum amount of the Mini-BEP2 token should be larger than or equal to 1, which is presented as 1e8 with the 8 digit decimal rule internally. The only exceptional case is that the user sells the total amount of the free Mini-BEP2 token in his account, if it is smaller than 1, due to some partial fill during trade match. #### 5.4.3 Matching -The number of Mini-BEP2 pairs could be much bigger than BEP2 pairs due to the cheap issue/listing fee. As they are designed to use limited network resource, Binance DEX match engine will only allocate a fixed resource on matching the Mini-BEP2 pairs. Unlike BEP2 token, only limited Mini-BEP2 token pairs will be matched in each block. +The number of Mini-BEP2 pairs could be much bigger than BEP2 pairs due to the cheap issue/listing fee. As they are designed to use limited network resource, BNB Beacon Chain DEX match engine will only allocate a fixed resource on matching the Mini-BEP2 pairs. Unlike BEP2 token, only limited Mini-BEP2 token pairs will be matched in each block. #### 5.4.4 Delist Delist a trading pair of Mini-BEP2 token is the same as BEP2 delist. Please refer to BEP-6. diff --git a/BEPs/BEP82.md b/BEPs/BEP82.md new file mode 100644 index 000000000..0cff6295a --- /dev/null +++ b/BEPs/BEP82.md @@ -0,0 +1,55 @@ +# BEP-82: Token Ownership Changes + +## 1. Summary +This BEP describes the changes related to the token owner who issued a token on BNB Beacon Chain. + +## 2. Abstract +Currently, many token-related transactions, such as token listing, minting, burning, etc., can only be proposed by the token owner who can not be changed once the token is issued on BNB Beacon Chain. + +This BEP proposes the solutions to provide more convenience and flexibility for these transactions. + +## 3. Status +This BEP is already implemented + +## 4. Motivation +To reduce the transaction's dependence on the related token’s owner and make the ownership of token changeable, we introduce those solutions as following: +- Providing an entrance to transfer the ownership of a specific token. +- Removing the owner verification when handling some token related transactions. + +## 5. Specification +### 5.1 Transfer Ownership +**TransferOwnership** transaction can transfer ownership of a specific token to another address, and only the original owner has the permission to send this transaction. + +A fee (a fixed amount of BNB) will be charged on **TransferOwnership** transactions. + +Parameters for TransferOwnership Operation: + +| **Field** | **Type** | **Description** | +| ------------------- | ----------- | ------------------------ | +| From | string | the address who wants to transfer the ownership to another address | +| Symbol | string | the token symbol needs to be transferred ownership | +| NewOwner | string | the address who is assigned to be the new owner of the token | + +### 5.2 Token Owner Verification Changes +Currently, some token-related transactions are restricted to being proposed by token owners while others are not. After the implementation of this BEP, any address can burn its own tokens. Here is the comparison below: + +| **Transaction Type** | **Verify Owner(Before)** | **Verify Owner(After)** | +| ------------------------- | ------------------------- |---------------------------| +| list token | yes | yes | +| mint token | yes | yes | +| burn token | yes | no | +| freeze token | no | no | +| set URI | yes | yes | +| atomic swap related | no | no | +| time lock | no | no | +| time unlock | no | no | +| time relock | no | no | +| transfer | no | no | +| cross transfer out | no | no | +| cross bind | yes | yes | +| cross unbind | yes | yes | + + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + diff --git a/BEPs/BEP84.md b/BEPs/BEP84.md new file mode 100644 index 000000000..d13f61445 --- /dev/null +++ b/BEPs/BEP84.md @@ -0,0 +1,215 @@ +# BEP-84: Mirror BEP20 to BNB Beacon Chain + +- [BEP-84: Mirror BEP20 to BNB Beacon Chain](#bep-84-mirror-bep20-to-bnb-beacon-chain) + * [1. Summary](#1-summary) + * [2. Abstract](#2-abstract) + * [3. Motivation](#3-motivation) + * [4. Status](#4-status) + * [5. Specification](#5-specification) + + [5.1 TokenManager](#51-tokenmanager) + - [5.1.1 Mirror](#511-mirror) + - [5.1.1.1 Parameters](#5111-parameters) + - [5.1.1.2 Pre-check](#5112-pre-check) + - [5.1.1.3 Core Mechanism](#5113-core-mechanism) + - [5.1.1.4 Handle Ack Packages](#5114-handle-ack-packages) + - [5.1.2 Sync](#512-sync) + - [5.1.2.1 Parameters](#5121-parameters) + - [5.1.2.2 Pre-check](#5122-pre-check) + - [5.1.2.3 Core Mechanism](#5123-core-mechanism) + - [5.1.2.4 Handle Ack Packages](#5124-handle-ack-packages) + + [5.2 BC Bridge](#52-bc-bridge) + - [5.2.1 Mirror Channel](#521-mirror-channel) + - [5.2.2 Sync Total Supply Channel](#522-sync-total-supply-channel) + + [5.3 Proposals to Enable New Channels](#53-proposals-to-enable-new-channels) + * [6. License](#6-license) + +## 1. Summary +This BEP proposes a scheme to facilitate users to issue and bind BEP2 tokens with existing BEP20 tokens. + +## 2. Abstract +Currently, if a user wants to issue and bind a BEP2 token with an existing BEP20 token, it has to do a set of complex operations, including issue BEP2 tokens, sending a bind transaction and approving the binding request. The BEP will bring a mechanism to simplify the above process. In the new mechanism, what anyone can do this is just sending a transaction to BNB Smart Chain. + +## 3. Motivation +Current bind mechanism is based on the context that our community members are on the BNB Beacon Chain and they want to extend their tokens to the BNB Smart Chain. However, with the evolution of our community, things changed. In most cases, users issue BEP20 on the BNB Smart Chain first without considering whether they will issue BEP2 on the BNB Beacon Chain or not, so a new mechanism to conveniently extend BEP20 assets to the BNB Beacon Chain is required. In addition, the new mechanism will encourage users to extend their assets to the BNB Beacon Chain which is very helpful to flourish the BNB Chain community. +## 4. Status +This BEP is already implemented + +## 5. Specification + +Two new permissionless methods will be imported into TokenManager contract: +Mirror: If a BEP20 contract is not bound to any BEP2 token, anyone can call the mirror method to automatically issue a BEP2 token and bind them. The user is not required to have any BEP20 token and just needs to pay enough BEP2 issue fee. Besides, the BEP20 contract is even not required to implement getOwner method. After binding, all the initial circulation is on BSC. +Sync: For a BEP20 token which has been mirrored to BC, anyone can call sync method to balance the total supply on BC and BSC. For example, someone mint some BEP20 token, after calling sync method, the equivalent token will be minted on BC and transferred to the pure-code-controlled-escrow address. If someone burn some BEP20 token, after calling sync method, the equivalent token will be burned on BC from the pure-code-controlled-escrow address. + +### 5.1 TokenManager + +#### 5.1.1 Mirror + +##### 5.1.1.1 Parameters + +| **Param Name** | **Type** | **Description** | +| ------------ | -------- | ---------------------- | +| BEP20Addr | Address | BEP20 contract address | +| ExpiredTime | uint64 | The deadline to deliver this package on BC | +| msg.value | uint256 | Sum of cross chain fee and mirror fee | + +##### 5.1.1.2 Pre-check + +1. Ensure the BEP20 token hasn’t been bound before and is not in mirror pending status. +2. Ensure the BEP20 symbol follows the BEP2 symbol requirements. +3. Ensure the BEP20 name follows the BEP2 name requirements. +4. Ensure the equivalent total supply is no greater than Max BEP2 total supply. +5. Ensure msg.value >= MirrorFee + CrossChainFee and msg.value = N * 10^10 +6. Ensure expired time is earlier than one day later and no earlier than two minutes later. + +##### 5.1.1.3 Core Mechanism + +1. Transfer CrossChainFee to TokenHub +2. Mark the BEP20 token as mirror pending status +3. RLP Encode mirror package: + +| **Param Name** | **Type** | **Description** | +| ----------------- | -------- | ---------------------- | +| MirrorSender | Address | Mirror sender | +| BEP20Addr | Address | BEP20 token address | +| BEP20Name | bytes32 | BEP20 token name | +| BEP20Symbol | bytes32 | BEP20 token symbol | +| BEP20Supply | uint256 | BEP20 total supply | +| BEP20Decimals | uint8 | BEP20 decimals | +| MirrorFee | uint256 | The mirror fee from users, which will be used to cover issue BEP2 token. | +| ExpiredTime | uint64 | The package expired time, counted by second | + +4. Call CrossChain contract to send a cross chain package. +5. If a BEP20 token is in mirror pending status or already mirrored, reject approveBind on it. + +##### 5.1.1.4 Handle ack packages + +1. Fail ack package: + 1. RLP decode mirror package. + 2. Refund MirrorFee to mirror sender. + 3. Set the BEP20 pending mirror status to false + +2. Ack package + + | **Param Name** | **Type** | **Description** | + | ----------------- | -------- | ---------------------- | + | MirrorSender | Address | Mirror sender | + | BEP20Addr | Address | BEP20 token address | + | BEP20Decimals | uint8 | BEP20 decimals | + | BEP2Symbol | bytes32 | BEP2 token symbol | + | MirrorFee | uint256 | Mirror fee from sync package | + | ErrorCode | uint8 | 1. Expired time is passed
2. Duplicated BEP2 symbol
3. Already bound
4. Unknown reason | + 1. RLP decode ack package. + 2. If ErrorCode is non-zero: + 1. Refund MirrorFee to mirror sender + 2. Emit bound failure event + 3. If ErrorCode is zero: + 1. Transfer SyncFee to TokenHub + 2. Write the bound pair to TokenHub + 3. Mark the BEP20 token as bound by mirror + 4. Emit bound success event + +#### 5.1.2 Sync + +##### 5.1.2.1 Parameters + +| **Param Name** | **Type** | **Description** | +| ----------------- | -------- | ---------------------- | +| BEP20Addr | Address | BEP20 contract address | +| ExpiredTime | uint64 | The deadline to deliver this package on BC | +| msg.value | uint256 | Sum of cross chain fee and sync fee. | + +##### 5.1.2.2 Pre-check + +1. Ensure the BEP20 is bound by mirror. +2. Ensure msg.value >= SyncFee + CrossChainFee and msg.value = N * 10^10 +3. Ensure the equivalent total supply on BC doesn’t exceed the maximum limit +4. Ensure expired time is earlier than one day later and no earlier than two minutes later. + +##### 5.1.2.3 Core mechanism + +1. Transfer CrossChainFee to TokenHub +2. RLP encode sync total supply package: + + | **Param Name** | **Type** | **Description** | + | ----------------- | -------- | ---------------------- | + | SyncSender | Address | Sync sender | + | BEP20Addr | Address | BEP20 token address | + | BEP2Symbol | bytes32 | BEP2 token symbol | + | BEP20Supply | uint256 | BEP20 total supply | + | SyncFee | uint256 | Sum of cross chain fee and sync fee | + | ExpiredTime | uint64 | The package expired time, counted by second | + +3. Call CrossChain contract to send a cross chain package. + +##### 5.1.2.4 Handle ack packages + +1. Fail ack package: + 1. RLP decode sync total supply package. + 2. Refund SyncFee to users. + +2. Ack package: + + | **Param Name** | **Type** | **Description** | + | ----------------- | -------- | ---------------------- | + | SyncSender | Address | Sync sender | + | BEP20Addr | Address | BEP20 token address | + | SyncFee | uint256 | Sync fee from sync package | + | ErrorCode | uint8 | 1. Not bound by mirror
2. Expired time is passed
3. Unknown reason | + + 1. RLP decode ack package. + 2. If ErrorCode is non-zero: + 1. Refund SyncFee to sync sender + 2. Emit sync failure event + 3. If ErrorCode is zero: + 1. Transfer SyncFee to TokenHub + 2. Emit sync success event + +### 5.1.3 Implement Parameter Update Interface + +Two governance parameters will be imported into TokenManager contract: MirrorFee and SyncFee. TokenManager contract needs to implement the following method: +function updateParam(string calldata key, bytes calldata value) + +| **Key** | **Value** | **Value Type** | +| ----------------- | --------------- | ------------------ | +| "BEP2MirrorFee" | BEP2 mirror fee | uint256 | +| "BEP2SyncFee" | BEP2 sync fee | uint256 | + +## 5.2 BC Bridge + +### 5.2.1 Mirror Channel + +1. RLP decode mirror package. Generate a fail ack package if failed. +2. Ensure expiredTime is not passed. +3. Ensure the BEP20 contract is not bound. +4. Convert BEP20 total supply to the total supply on BC and Ensure the total supply doesn’t exceed the maximum limit of BEP2. +5. Issue a new BEP2 token, the suffix should be the hash of oracle payload and current channel sequence. Besides, the new BEP2 token owner will be the pure-code-controlled-escrow address. +6. Transfer all tokens to the pure-code-controlled-escrow address and write BEP20 address and decimals to the BEP2 token attribution table. +7. Unlock mirror fee from peg account to BC fee pool, so that validators can get these fees. +8. If all above steps are successful, generate a success ack package. The mirrorFee in ack package should equal to the value in sync package. Otherwise, generate an ack failure package. + +### 5.2.2 Sync Total Supply Channel + +1. RLP decode mirror package. Generate a fail ack package if failed. +2. Ensure expiredTime is not passed +3. Convert BEP20 total supply to BEP2 total supply and ensure the total supply doesn’t exceed the maximum limit of BEP2. +4. Mint/Burn + 1. BSC total supply > BC total supply, mint BEP2 and transfer all new minted tokens to the pure-code-controlled-escrow address. + 2. BSC total supply == BC total supply, nothing to do + 3. BSC total supply > BC total supply, burn BEP2 from the pure-code-controlled-escrow address. +5. Unlock sync fee from the pure-code-controlled-escrow address to BC fee pool. +6. If all above steps are successful, generate a success ack package. The mirrorFee in ack package should equal to the value in sync package. Otherwise, generate an ack failure package. + +## 5.3 Proposals to Enable New Channels +After BC and BSC are both upgraded, submit a proposal on BC to add two channels: +1. Mirror channel + 1. Channel id: 4 + 2. Handler address: 0x0000000000000000000000000000000000001008 + 3. Is reward from systemReward: false +2. Sync total supply channel: + 1. Channel id: 5 + 2. Handler address: 0x0000000000000000000000000000000000001008 + 3. Is reward from systemReward: false + + +## 6. License +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP86.md b/BEPs/BEP86.md new file mode 100644 index 000000000..d5c6bd2d5 --- /dev/null +++ b/BEPs/BEP86.md @@ -0,0 +1,43 @@ +# BEP-86: Dynamic Extra Incentive For BSC Relayers + +- [BEP-86: Dynamic Extra Incentive For BSC Relayers](#bep-86-dynamic-extra-incentive-for-bsc-relayers) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Governable Parameter](#51-governable-parameter) + - [5.2 Modify RelayerIncentivize Contract](#52-modify-relayerincentivize-contract) + - [6. License](#6-license) + +## 1. Summary + +This BEP proposes a reward mechanism to balance the gain and risk for BSC relayers, which will attract more relayers to engage in and improve the cross chain communication robustness between BC and BSC. + +## 2. Abstract + +Now all bsc-relayers are suffering from BNB loss in relaying cross chain packages from BC to BSC. Besides, it would not be helpful to community development if common users have to pay more relay fees. To compensate relayers and avoid additional burden to common users, some dynamic extra reward will be granted to bsc-relayers from the [SystemReward Contract](https://github.com/bnb-chain/bsc-genesis-contract/blob/master/contracts/SystemReward.sol). + +## 3. Status + +This BEP is already implemented. + +## 4. Motivation + +Anyone can maintain a bsc-relayer by depositing 100BNB to the RelayerHub contract. If the relay reward can cover the relay cost, then more and more people will maintain their own bsc-relayer, which will improve the robustness of the cross chain communication between BC and BSC. Otherwise, no one is willing to maintain a bsc-relayer. Thus the communication between the BC and the BSC will be blocked. + +## 5. Specification + +### 5.1 Governable Parameter +Import a governable parameter `dynamicExtraIncentiveAmount` to the [RelayerIncentivize Contract](https://github.com/bnb-chain/bsc-genesis-contract/blob/master/contracts/RelayerIncentivize.sol): +1. The `dynamicExtraIncentiveAmount` represents the amount of BNB which will be transferred from the SystemReward to the bsc relayer reward pool. +2. The `dynamicExtraIncentiveAmount` can be modified by sidechain governance on BC. + +### 5.2 Modify RelayerIncentivize Contract +Modify the `addReward` method in the RelayerIncentivize contract: +1. Try to claim `dynamicExtraIncentiveAmount` from the SystemReward contract. +2. Add the new claimed reward to the existing reward. +3. Add the total reward to the relayer reward pool. + +## 6. License +All the content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP87.md b/BEPs/BEP87.md new file mode 100644 index 000000000..299db5bef --- /dev/null +++ b/BEPs/BEP87.md @@ -0,0 +1,30 @@ +# BEP-87: Token Symbol Minimum Length Change + +## 1. Summary +This BEP proposes to reduce the minimum length limit for token symbol on BNB Beacon Chain + +## 2. Abstract +Currently, the token symbol minimum length is limited to 3. After implementing this BEP, the users are allowed to issue a token with a symbol of 2 characters. + +## 3. Status +This BEP is already implemented + +## 4. Motivation +As many users have the requirements to issue a two-character token on BNB Beacon Chain, the minimum token symbol length will be changed to 2 in this BEP. + +## 5. Specification + +### Length Changes +When the issuer sends an issue transaction for issuing BEP2/BEP8 token, the token symbol length must be between 2-8. Here is the comparison of the length check below: + +| **Token Type** | **Length Check(Before)** | **Length Check(After)** | +| :------------- | :----------------------- | :---------------------- | +| BEP2 | 3-8 | 2-8 | +| BEP8 | 3-8 | 2-8 | + +After the implementation of this BEP, the token symbol length of BNB Beacon Chain would be between 2 and 8. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). + diff --git a/BEPs/BEP89.md b/BEPs/BEP89.md new file mode 100644 index 000000000..1351928eb --- /dev/null +++ b/BEPs/BEP89.md @@ -0,0 +1,64 @@ +# BEP-89: Visual Fork of BNB Smart Chain + +- BEP-89: Visual Fork of BNB Smart Chain + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [5.1 Fork Hash](#51-fork-hash) + - [5.2 Vanity](#52-vanity) + - [5.3 Vanity](#53-clients) + - [5.4 Backwards Compatibility](#54-backwards-compatibility) + - [6. License](#6-license) + +## 1. Summary + +This BEP describes a proposal to enable the chain to display the whole view of validators that on different upcoming forks. + +## 2. Abstract + +The four bytes of `Header.Extra[28:32]` will be fulfilled with `NEXT_FORK_HASH`. The `NEXT_FORK_HASH` indicates which fork the signer of this block is going to stay on. By analysing `N` (`N` is the amount of validators) continuous block headers, we are able to know which fork is supported by the majority of validators and exact which validator has not upgraded yet. + +## 3. Status + +This BEP is already implemented + +## 4. Motivation + +BNB Smart Chain will inevitably have some hard forks in the long run. During a hard fork, BNB Smart Chain risks halting if the validators cannot reach a consensus. A validator may be slashed if it is not on the canonical fork, which could be avoided if the maintainer receives alerts in time. A new protocol should be introduced to enable the chain to display the whole view of validators on different upcoming forks, so that any nodes/validators can decide to upgrade/fork or not accordingly. +## 5. Specification + +### 5.1 Fork Hash + +Fork Hash is introduced in [EIP-2124](https://eips.ethereum.org/EIPS/eip-2124). It is a mechanism that can let ethereum nodes precisely identify whether another node will be useful. + +- `FORK_HASH`. IEEE CRC32 checksum ([4]byte) of the genesis hash and fork blocks numbers that already passed. E.g. Fork Hash for mainnet would be: `forkhash₂ = 0x91d1f948 (DAO fork) = CRC32( || uint64(1150000) || uint64(1920000))`. +- `FORK_NEXT`. Block number (uint64) of the next upcoming fork, or 0 if no next fork is known. +- `NEXT_FORK_HASH`, whose algorithm is same with `FORK_HASH`, but `FORK_NEXT` will be included as well if it is not 0. + +### 5.2 Vanity + +Format of `Header.Extra`: + +``` +| 32 bytes | 20 * N bytes | 65 bytes | +| extraVanity | validatorSetBytes | extraSeal | +``` + +`extraVanity` field is customized now, validator can use it to record `NEXT_FORK_HASH` of itself. The `NEXT_FORK_HASH` will only use the last 4 bytes of `extraVanity`. + +### 5.3 Clients + +- For validator. It will fill in `Header.Extra` with `NEXT_FORK_HASH` during preparing block header. +- For witness. It will log a warning message if the majority `NEXT_FORK_HASH` is different from local. +- For light client. No impact. + +### 5.4 Backwards Compatibility + +- This BEP itself is not a hardfork one, it breaks nothing of consensus. +- Downstream service is completely compatible with this BEP. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEP9.md b/BEPs/BEP9.md similarity index 93% rename from BEP9.md rename to BEPs/BEP9.md index 7e66a61eb..96727d6f7 100644 --- a/BEP9.md +++ b/BEPs/BEP9.md @@ -16,13 +16,13 @@ ## 1. Summary -This BEP describes a proposal for a time-locking feature of tokens on the Binance Chain. +This BEP describes a proposal for a time-locking feature of tokens on the BNB Beacon Chain. ## 2. Abstract -BEP-9 Proposal describes functionality to time-lock tokens on the Binance Chain. Such as: +BEP-9 Proposal describes functionality to time-lock tokens on the BNB Beacon Chain. Such as: -+ TimeLock: TimeLock will transfer locked tokens to a purely-code-controlled escrow account. A purely-code-controlled escrow account is a kind of account which is derived from a hard-coded string in binance chain protocol. This kind of account has no private key and it's only controled by code in protocol. Before the lock time expires, the specific user will not be able to claim them back, including restrictions where they cannot use, transfer or spend these tokens. ++ TimeLock: TimeLock will transfer locked tokens to a purely-code-controlled escrow account. A purely-code-controlled escrow account is a kind of account which is derived from a hard-coded string in BNB Beacon Chain protocol. This kind of account has no private key and it's only controlled by code in protocol. Before the lock time expires, the specific user will not be able to claim them back, including restrictions where they cannot use, transfer or spend these tokens. + TimeUnlock: TimeUnlock will claim the locked tokens back when the specified lock time has passed. + TimeRelock: TimeRelock can extend lock times, increase the amount of locked tokens or modify the description of an existing lock record. + QueryTimeLocks: QueryTimeLocks will query all lock records of a given address. diff --git a/BEPs/BEP91.md b/BEPs/BEP91.md new file mode 100644 index 000000000..531b4131b --- /dev/null +++ b/BEPs/BEP91.md @@ -0,0 +1,45 @@ +# BEP-91: Increase Block Gas Ceiling for BNB Smart Chain + +- [BEP-91: Increase Block Gas Ceiling for BNB Smart Chain](#bep-91-increase-block-gas-ceiling-for-BNB-smart-chain) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [6. License](#6-license) + +## 1. Summary + +This BEP describes a proposal for the increment of **gasceil** of BSC. + +## 2. Abstract + +BEP-91 Proposal describes a change of BSC node configuration, and suggests Validator operators should increase the value of the block `GasCeil`from `60000000` to `75000000`, and increase the value of the block `GasFloor`from `40000000` to `60000000` . + +## 3. Status + +This BEP is already implemented. + +## 4. Motivation + +The increasing adoption of BSC leads to a more active network. Blocks start hitting the gasceil daily. The increasing prevalence of blocks near the limit may lead to increased fees and delays in the processing of transactions in the future. This will undermine the core value of BSC as a fast and cheap network. + +img + +BSC network has once reached the 40M gas limit, it can handle more transactions according to the following screenshot. + +img + +Increased gasceil will lead to more transactions per block. It will be a direct solution to scale. + +## 5. Specification + +According to the past laboratory tests, BSC can process real transactions with more than 70M Gas. Considering the complex network environment in mainnet and the different hardware of validators, 60M is a relatively reasonable value. If 60M is larger than expected, the miner module of BSC will adaptively adjust it to avoid network overloading. + +It is strongly recommended to raise the gasceil parameter as well as hardware. The validator may get less reward than expected if its hardware fails to validate enough tx. + +As the transaction volume continues to increase, more changes should be made to the internal logic on transaction execution, storage and P2P communication. + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP93.md b/BEPs/BEP93.md new file mode 100644 index 000000000..8d3a8ce35 --- /dev/null +++ b/BEPs/BEP93.md @@ -0,0 +1,80 @@ +# BEP-93: Diff Sync Protocol on BSC + +## 1. Summary + +This BEP introduces a new sync mode named diff sync on the BNB Smart Chain. + +## 2. Abstract + +BEP-93 Proposal describes a fast block syncing protocol to lower the hardware requirement for running a BSC client. A BSC client can simply apply the execution result of a block securely without executing the transactions. + +Currently, BSC has three kinds of sync mode: +1. Snap sync; +2. Fast sync; +3. Full sync. + +Snap sync and fast sync are used for the initial synchronization, once the client has the entire state and all historical block data, it will switch to full sync automatically. + +It takes several steps to process a block when doing full sync: +1. Fetch/Receive blocks from other peers through p2p network. +2. Verify header and block body. +3. Execute transactions within EVM. +4. Calculate the root hash of MPT. +5. Commit MPT to memory DB, persist snapshot and MPT to disk if necessary. + +In most cases, step 3 occupied 70+% of the block processing time. + +This BEP proposes a diff sync protocol without executing transactions, in exchange, the security of a fullnode will degrade to a light client, but meanwhile the node can still keep the full state and blocks of the network. This will benefit the small node so that they can still be used as full nodes and participate in the light verification of the network. + +## 3. Status + +This BEP is already implemented. + +## 4. Motivation + +The increasing adoption of BSC leads to a more active network. Blocks on BSC start hitting the gasceil daily, and the BSC network will increase the capacity further. On the other hand, the node maintainer had a hard time keeping their node catching up with the chain. A light syncing protocol to lower the hardware requirement is an urgent need. + +## 5. Specification +### 5.1 Diff Protocol + +A new protocol named diff will run on top of the p2p network besides eth and snap. Four kinds of packages are defined under the diff protocol: + +1. **DiffCapMsg**. It is used to exchange whether the peer supports diff sync during the handshake. +2. **GetDiffLayerMsg**. It is used to request diff layers from other peers. +3. **DiffLayerMsg**. It is used to broadcast diff layers to other peers. +4. **FullDiffLayerMsg**. It is a response to GetDiffLayerMsg which contains the diff layers. + +Diff layer is the execution result of a block, it contains: +1. **BlockHash**. +2. **Number**. The height of the block. +3. **Receipts**. The receipts of the block. +4. **Codes**. The newly created smart contract code within the block. +5. **Destructs**. The destroyed accounts within the block. +6. **Accounts**. The account change within the block. +7. **Storages**. The storage change within the block. + +### 5.2 Sync Diff Layer +![Untitled Diagram drawio](https://user-images.githubusercontent.com/7310198/132794555-e071232b-9d91-461e-b6ef-9589cd37f738.png) + + +Workflow: +1. P2P nodes full sync a block and cache the generated diff layer. +2. (optional)The generated diff layer can be persisted if it is on the canonical chain. +3. P2P nodes may receive diff layers from other peers, will cache it in an untrusted diff layer set. +4. P2P node will broadcast diff layers to parts of connected peers. +5. P2P nodes will pick diff layers from the cache, disk, and untrusted set to respond to requests from other peers. +6. A full node can fetch diff layers from other peers +7. A full node can apply the diff layers to MPT and Snapshot without executing transactions, it is called light process. If the light process failed, the full node will fall back to full sync. + +### 5.3 Security +The diff sync protocol guarantees 1. Light client security; 2. State consistency. + +It sustains 1. Validator collusion 2. Short fork with an invalid state. + +For validator collusion, the full node will randomly full sync to prevent applying a false state caused by validator collusion. + +For short fork with an invalid state, it is highly recommended that at least 21 blocks are needed to reach finality for a diff sync client. + +### 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/BEP95.md b/BEPs/BEP95.md new file mode 100644 index 000000000..ebbb58515 --- /dev/null +++ b/BEPs/BEP95.md @@ -0,0 +1,63 @@ +# BEP-95: Introduce Real-Time Burning Mechanism + +- [BEP-95: Introduce Real-Time Burning Mechanism](#bep-95-introduce-real-time-burning-mechanism) + - [1. Summary](#1-summary) + - [2. Abstract](#2-abstract) + - [3. Status](#3-status) + - [4. Motivation](#4-motivation) + - [5. Specification](#5-specification) + - [6. License](#6-license) + +## 1. Summary + +This BEP introduces a real-time burning mechanism into the economic model of BSC. + +## 2. Abstract + +To speed up the burning process of BNB and make BSC more decentralized, part of the gas fee will be burned. It includes two parts: + ++ A fixed ratio of the gas fee collected by the validators will be burned in each block. ++ The burning ratio can be governed by the BSC validators. + + +## 3. Status + +This BEP is already implemented. + +## 4. Motivation + +The burning of gas fees can speed up the burning process of BNB and improve the intrinsic value of BNB. + +The BNB holders will decide how to dispatch the gas reward of BSC. + +Though the staking reward of the validators and delegators may decrease in BNB amount, the reward value in dollars may increase in the long run with the increase of BNB value and a more active ecosystem. + +## 5. Specification + +### 5.1 Gas Fee Distribution + +As BNB is not an inflationary token, there will be no mining rewards as what Bitcoin and Ethereum networks generate, and the gas fee is the major reward for validators. As BNB is also utility tokens with other use cases, delegators and validators will still enjoy other benefits of holding BNB. The gas fee is collected each block and distributed to two system smart contracts: + +1. [System Reward Contract](https://bscscan.com/address/0x0000000000000000000000000000000000001002). The contract can possess at most 100 BNB. 1/16 of the gas fee will be transferred to the system reward contract if it possesses less than 100 BNB. The funding within the reward contract is used as cross-chain package subsidies. +2. [ValidatorSet Contract](https://bscscan.com/address/0x0000000000000000000000000000000000001000). The rest of the gas fee is transferred to the ValidatorSet contract. It is the vault to keep gas fees for both validators and delegators. The funding within the contract will be transferred to BNB Beacon Chain and distributed to delegators and validators according to their shares every day. + +### 5.2 Burning Mechanism + +A governable parameters: `burnRatio` will be introduced in the [ValidatorSet Contract](https://bscscan.com/address/0x0000000000000000000000000000000000001000). At the end of each block, the Validator will sign a transaction to invoke the `deposit` function of the contract to transfer the gas fee. The burning logic is implemented within the `deposit` function that: `burnRatio` * `gasFee` will be transferred to the [burn address](https://bscscan.com/address/0x000000000000000000000000000000000000dead); + +The initial setting: + ++ burnRatio = 10% + +### 5.3 Governance + +The change of `burnRatio` will be determined by BSC Validators together through a proposal-vote process based on their staking. + +This process will be carried on BNB Beacon Chain, every community member can propose a change of the params. The proposal needs to receive a minimum deposit of BNB (2000BNB on mainnet for now, refundable after the proposal has passed) so that the validator can vote for it. The validators of BSC can vote for it or against it based on their staking amount of BNB. + +If the total voting power of bounded validators that votes for it reaches the quorum(50% on mainnet), the proposal will pass and the corresponding change of the params will be passed onto BSC via cross-chain communication and take effect immediately. The vote of unbounded validators will not be considered into the tally. + + +## 6. License + +The content is licensed under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). diff --git a/BEPs/assets/BEP-188/broadcast_without_limit.png b/BEPs/assets/BEP-188/broadcast_without_limit.png new file mode 100644 index 000000000..3a6c74fe8 Binary files /dev/null and b/BEPs/assets/BEP-188/broadcast_without_limit.png differ diff --git a/BEPs/assets/BEP-188/consensus_adaption.png b/BEPs/assets/BEP-188/consensus_adaption.png new file mode 100644 index 000000000..b05900e16 Binary files /dev/null and b/BEPs/assets/BEP-188/consensus_adaption.png differ diff --git a/BEPs/assets/BEP-188/early_broadcast_with_limit.png b/BEPs/assets/BEP-188/early_broadcast_with_limit.png new file mode 100644 index 000000000..65b883dee Binary files /dev/null and b/BEPs/assets/BEP-188/early_broadcast_with_limit.png differ diff --git a/BEPs/assets/BEP-188/mining_process_normal.png b/BEPs/assets/BEP-188/mining_process_normal.png new file mode 100644 index 000000000..254b69c0b Binary files /dev/null and b/BEPs/assets/BEP-188/mining_process_normal.png differ diff --git a/BEPs/assets/BEP-225/Complexity_Regression.png b/BEPs/assets/BEP-225/Complexity_Regression.png new file mode 100644 index 000000000..059671bbe Binary files /dev/null and b/BEPs/assets/BEP-225/Complexity_Regression.png differ diff --git a/BEPs/assets/BEP-225/GQuad_Change.png b/BEPs/assets/BEP-225/GQuad_Change.png new file mode 100644 index 000000000..53bb64112 Binary files /dev/null and b/BEPs/assets/BEP-225/GQuad_Change.png differ diff --git a/BEPs/assets/BEP-293/cross_chain.png b/BEPs/assets/BEP-293/cross_chain.png new file mode 100644 index 000000000..9ad17c00a Binary files /dev/null and b/BEPs/assets/BEP-293/cross_chain.png differ diff --git a/BEPs/assets/BEP-319/4.1-current-fee-distribution.png b/BEPs/assets/BEP-319/4.1-current-fee-distribution.png new file mode 100644 index 000000000..4adbddfac Binary files /dev/null and b/BEPs/assets/BEP-319/4.1-current-fee-distribution.png differ diff --git a/BEPs/assets/BEP-319/4.2-new-fee-distribution.png b/BEPs/assets/BEP-319/4.2-new-fee-distribution.png new file mode 100644 index 000000000..ad58fbb06 Binary files /dev/null and b/BEPs/assets/BEP-319/4.2-new-fee-distribution.png differ diff --git a/BEPs/assets/BEP-335/4-3-new-sp-graceful-exit-procedure.png b/BEPs/assets/BEP-335/4-3-new-sp-graceful-exit-procedure.png new file mode 100644 index 000000000..a71b79519 Binary files /dev/null and b/BEPs/assets/BEP-335/4-3-new-sp-graceful-exit-procedure.png differ diff --git a/BEPs/assets/BEP-335/4.1.2-VGF.png b/BEPs/assets/BEP-335/4.1.2-VGF.png new file mode 100644 index 000000000..cf085f493 Binary files /dev/null and b/BEPs/assets/BEP-335/4.1.2-VGF.png differ diff --git a/BEPs/assets/BEP-336/blob_expire.png b/BEPs/assets/BEP-336/blob_expire.png new file mode 100644 index 000000000..2eab39d23 Binary files /dev/null and b/BEPs/assets/BEP-336/blob_expire.png differ diff --git a/BEPs/assets/BEP-336/blob_gasprice.png b/BEPs/assets/BEP-336/blob_gasprice.png new file mode 100644 index 000000000..e47590125 Binary files /dev/null and b/BEPs/assets/BEP-336/blob_gasprice.png differ diff --git a/BEPs/assets/BEP-364/workflow.png b/BEPs/assets/BEP-364/workflow.png new file mode 100644 index 000000000..c7fac3509 Binary files /dev/null and b/BEPs/assets/BEP-364/workflow.png differ diff --git a/BEPs/assets/BEP-366/workflow.png b/BEPs/assets/BEP-366/workflow.png new file mode 100644 index 000000000..f0d6c1bf6 Binary files /dev/null and b/BEPs/assets/BEP-366/workflow.png differ diff --git a/BEPs/assets/BEP-381/benchstat_compare_test b/BEPs/assets/BEP-381/benchstat_compare_test new file mode 100644 index 000000000..d99bcf999 --- /dev/null +++ b/BEPs/assets/BEP-381/benchstat_compare_test @@ -0,0 +1,42 @@ +goos: darwin +goarch: arm64 +pkg: github.com/ethereum/go-ethereum/core/vm + │ compare_p256Verify │ compare_ecrecover │ + │ sec/op │ sec/op vs base │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 57.75µ ± 1% +PrecompiledEcrecover/-Gas=3000-8 50.48µ ± 1% +geomean 57.75µ 50.48µ ? ¹ ² +¹ benchmark set differs from baseline; geomeans may not be comparable +² ratios must be >0 to compute geomean + + │ compare_p256Verify │ compare_ecrecover │ + │ gas/op │ gas/op vs base │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 3.450k ± 0% +PrecompiledEcrecover/-Gas=3000-8 3.000k ± 0% +geomean 3.450k 3.000k ? ¹ ² +¹ benchmark set differs from baseline; geomeans may not be comparable +² ratios must be >0 to compute geomean + + │ compare_p256Verify │ compare_ecrecover │ + │ mgas/s │ mgas/s vs base │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 59.73 ± 1% +PrecompiledEcrecover/-Gas=3000-8 59.42 ± 1% +geomean 59.73 59.42 ? ¹ ² +¹ benchmark set differs from baseline; geomeans may not be comparable +² ratios must be >0 to compute geomean + + │ compare_p256Verify │ compare_ecrecover │ + │ B/op │ B/op vs base │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 1.523Ki ± 0% +PrecompiledEcrecover/-Gas=3000-8 800.0 ± 0% +geomean 1.523Ki 800.0 ? ¹ ² +¹ benchmark set differs from baseline; geomeans may not be comparable +² ratios must be >0 to compute geomean + + │ compare_p256Verify │ compare_ecrecover │ + │ allocs/op │ allocs/op vs base │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 33.00 ± 0% +PrecompiledEcrecover/-Gas=3000-8 7.000 ± 0% +geomean 33.00 7.000 ? ¹ ² +¹ benchmark set differs from baseline; geomeans may not be comparable +² ratios must be >0 to compute geomean diff --git a/BEPs/assets/BEP-381/ecrecover_benchmark_test b/BEPs/assets/BEP-381/ecrecover_benchmark_test new file mode 100644 index 000000000..4bf20a628 --- /dev/null +++ b/BEPs/assets/BEP-381/ecrecover_benchmark_test @@ -0,0 +1,15 @@ +goos: darwin +goarch: arm64 +pkg: github.com/ethereum/go-ethereum/core/vm +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23295 50034 ns/op 3000 gas/op 59.95 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23734 50558 ns/op 3000 gas/op 59.33 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23823 50586 ns/op 3000 gas/op 59.30 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23913 50049 ns/op 3000 gas/op 59.94 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23721 50299 ns/op 3000 gas/op 59.64 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23760 51160 ns/op 3000 gas/op 58.63 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23151 50818 ns/op 3000 gas/op 59.03 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23744 53451 ns/op 3000 gas/op 56.12 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 22837 50315 ns/op 3000 gas/op 59.62 mgas/s 800 B/op 7 allocs/op +BenchmarkPrecompiledEcrecover/-Gas=3000-8 23823 50401 ns/op 3000 gas/op 59.52 mgas/s 800 B/op 7 allocs/op +PASS +ok github.com/ethereum/go-ethereum/core/vm 17.687s diff --git a/BEPs/assets/BEP-381/p256Verify_benchmark_test b/BEPs/assets/BEP-381/p256Verify_benchmark_test new file mode 100644 index 000000000..dc908bf8e --- /dev/null +++ b/BEPs/assets/BEP-381/p256Verify_benchmark_test @@ -0,0 +1,15 @@ +goos: darwin +goarch: arm64 +pkg: github.com/ethereum/go-ethereum/core/vm +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20770 57970 ns/op 3450 gas/op 59.51 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20899 57769 ns/op 3450 gas/op 59.71 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20780 57343 ns/op 3450 gas/op 60.16 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20870 57740 ns/op 3450 gas/op 59.74 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20911 57411 ns/op 3450 gas/op 60.09 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20874 58423 ns/op 3450 gas/op 59.04 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20736 57552 ns/op 3450 gas/op 59.94 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 19700 58235 ns/op 3450 gas/op 59.24 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20814 57681 ns/op 3450 gas/op 59.80 mgas/s 1560 B/op 33 allocs/op +BenchmarkPrecompiledP256Verify/p256Verify-Gas=3450-8 20736 58806 ns/op 3450 gas/op 58.66 mgas/s 1560 B/op 33 allocs/op +PASS +ok github.com/ethereum/go-ethereum/core/vm 18.491s diff --git a/BEPs/assets/BEP-402/4-1.png b/BEPs/assets/BEP-402/4-1.png new file mode 100644 index 000000000..b28ef66e8 Binary files /dev/null and b/BEPs/assets/BEP-402/4-1.png differ diff --git a/BEPs/assets/BEP-404/4-1.png b/BEPs/assets/BEP-404/4-1.png new file mode 100644 index 000000000..1f212d9b9 Binary files /dev/null and b/BEPs/assets/BEP-404/4-1.png differ diff --git a/BEPs/assets/BEP-525/3-1-2.png b/BEPs/assets/BEP-525/3-1-2.png new file mode 100644 index 000000000..1cb1fbcba Binary files /dev/null and b/BEPs/assets/BEP-525/3-1-2.png differ diff --git a/BEPs/assets/BEP-525/3-1.png b/BEPs/assets/BEP-525/3-1.png new file mode 100644 index 000000000..569943ac6 Binary files /dev/null and b/BEPs/assets/BEP-525/3-1.png differ diff --git a/BEPs/assets/BEP-536/3-2.png b/BEPs/assets/BEP-536/3-2.png new file mode 100644 index 000000000..4e1575562 Binary files /dev/null and b/BEPs/assets/BEP-536/3-2.png differ diff --git a/BEPs/assets/BEP-564/image1.png b/BEPs/assets/BEP-564/image1.png new file mode 100644 index 000000000..3ef292c75 Binary files /dev/null and b/BEPs/assets/BEP-564/image1.png differ diff --git a/BEPs/assets/BEP-592/bal-asset-1.png b/BEPs/assets/BEP-592/bal-asset-1.png new file mode 100644 index 000000000..b49d7b199 Binary files /dev/null and b/BEPs/assets/BEP-592/bal-asset-1.png differ diff --git a/BEPs/assets/BEP-593/bep_593_arch.png b/BEPs/assets/BEP-593/bep_593_arch.png new file mode 100644 index 000000000..855fd070f Binary files /dev/null and b/BEPs/assets/BEP-593/bep_593_arch.png differ diff --git a/BEPs/assets/BEP-593/storage_compare.png b/BEPs/assets/BEP-593/storage_compare.png new file mode 100644 index 000000000..5781db788 Binary files /dev/null and b/BEPs/assets/BEP-593/storage_compare.png differ diff --git a/BEPs/assets/BEP-594/bep_594_arch.png b/BEPs/assets/BEP-594/bep_594_arch.png new file mode 100644 index 000000000..5aefbfbb7 Binary files /dev/null and b/BEPs/assets/BEP-594/bep_594_arch.png differ diff --git a/BEPs/assets/BEP-594/bep_594_workflow.png b/BEPs/assets/BEP-594/bep_594_workflow.png new file mode 100644 index 000000000..d73406950 Binary files /dev/null and b/BEPs/assets/BEP-594/bep_594_workflow.png differ diff --git a/BEPs/assets/BEP-652/analysis.md b/BEPs/assets/BEP-652/analysis.md new file mode 100644 index 000000000..fe28ea445 --- /dev/null +++ b/BEPs/assets/BEP-652/analysis.md @@ -0,0 +1,111 @@ +# BEP-652 Empirical Report + +*The following represents a summary with empirical findings from analyzing a `2**24` (16,777,216) transaction gas limit cap.* +*Date: January 28, 2026* + +## Dataset + +- **Period**: 2025-12-27 to 2026-01-28 +- **Blocks analyzed**: 4,802,727 +- **Total transactions**: 517,359,109 + +## Impact Metrics + +### Transaction Impact + +| Metric | Value | +|--------|-------| +| Affected transactions | 41,604 | +| Impact rate | 0.0080% | +| Unique affected addresses | 5,905 | +| Avg transactions per affected address | 7.0 | + +## Gas Analysis (of Affected) + +| Metric | Value | +|--------|-------| +| Average gas limit (affected txs) | 30,112,436 | +| Average gas used | 21,864,045 | +| Gas efficiency | 72.6% | +| Min gas used | 10,003,266 | +| Max gas used | 95,975,271 | +| Transactions with unnecessary high limits | 16,254 (39.07%) | + +> Note: "Unnecessary high limits" = gasLimit > gasUsed * 1.5 (50% buffer) + +## Gas Limit Distribution (gasLimit >= 16,777,216) + +| Gas Limit Range | Percentage | Transaction Count | +|-----------------|------------|-------------------| +| 16,777,216 - 30,000,000 | 58.08% | 24,154 | +| 30,000,000 - 40,000,000 | 23.62% | 9,829 | +| >40,000,000 | 18.32% | 7,620 | + + +## Gas Limit Distribution of Slow Transactions (>500ms) + +| Gas Limit Range | Percentage | Transaction Count | +|-----------------|------------|-------------------| +| <= 16,777,216 | 4.21% | 4 | +| 16,777,216 - 30,000,000 | 11.58% | 11 | +| 30,000,000 - 40,000,000 | 16.84% | 16 | +| > 40,000,000 | 67.37% | 64 | + +Total slow transactions (>500ms): 95 + +## Address Analysis + +### Top 10 From Addresses + +| Rank | Address | Transactions | Avg Gas Limit | Max Gas Limit | +|------|---------|--------------|---------------|---------------| +| 1 | 0x4688e0...ab20 | 4,749 | 24,894,947 | 24,956,279 | +| 2 | 0x5e6d93...9ac5 | 3,394 | 30,945,200 | 30,945,200 | +| 3 | 0xd81904...7220 | 2,808 | 40,945,200 | 40,945,200 | +| 4 | 0x6ad7b5...f848 | 1,634 | 25,191,664 | 61,421,290 | +| 5 | 0xeda91b...9118 | 1,158 | 17,230,949 | 17,314,203 | +| 6 | 0x8c38ce...95ea | 918 | 40,000,000 | 40,000,000 | +| 7 | 0x6205d0...f047 | 767 | 31,493,975 | 53,098,753 | +| 8 | 0x99187c...5889 | 644 | 20,000,000 | 20,000,000 | +| 9 | 0xb433b8...4ea6 | 540 | 23,572,658 | 29,066,877 | +| 10 | 0xc64bf1...7c8e | 481 | 17,351,652 | 17,351,993 | + +### Top 10 To Addresses + +| Rank | Address | Transactions | % of Total | Note | +|------|---------|--------------|------------|------| +| 1 | 0xba49fa...49dc | 4,749 | 11.4% | Airdrop Contract | +| 2 | 0xffb667...9649 | 3,394 | 8.2% | Batch Transfer Contract | +| 3 | 0xe39a5e...3d26 | 2,525 | 6.1% | Complex Transaction Contract (MEV/Arbitrage) | +| 4 | 0x7d6b49...8d95 | 2,148 | 5.2% | NFT2 Token Contract + Transfer | +| 5 | 0x4d1cdb...dbde | 1,781 | 4.3% | | +| 6 | 0x8ac784...146a | 1,717 | 4.1% | | +| 7 | 0x291c36...bd8c | 1,183 | 2.8% | | +| 8 | 0xe4f072...0e5f | 1,158 | 2.8% | | +| 9 | 0x24293c...4595 | 1,022 | 2.5% | | +| 10 | 0x07964f...0000 | 772 | 1.9% | | + +## Migration Analysis + +### Transaction Splitting Requirements + +If gasLimit capped at 16,777,216, how many splits needed per address: + +| Splits Required | Address Count | Percentage | +|-----------------|---------------|------------| +| 2 | 4,295 | 72.7% | +| 3 | 1,218 | 20.6% | +| 4+ | 392 | 6.6% | + +Total addresses needing splits: 5,905 + +## Summary + +| Metric | Value | +|--------|-------| +| Affected transactions | 41,604 (0.0080%) | +| Affected addresses | 5,905 | +| Total extra BNB | 0.0084 BNB (at 0.05 gwei) | +| Average splits required | 2.36 | + +____ diff --git a/BEPs/assets/bep-1/workflow.png b/BEPs/assets/bep-1/workflow.png new file mode 100644 index 000000000..386227d81 Binary files /dev/null and b/BEPs/assets/bep-1/workflow.png differ diff --git a/BEPs/assets/bep-128/reward-distribution.png b/BEPs/assets/bep-128/reward-distribution.png new file mode 100644 index 000000000..547819f4b Binary files /dev/null and b/BEPs/assets/bep-128/reward-distribution.png differ diff --git a/BEPs/assets/bep-130/1_overview.png b/BEPs/assets/bep-130/1_overview.png new file mode 100644 index 000000000..9078afcc9 Binary files /dev/null and b/BEPs/assets/bep-130/1_overview.png differ diff --git a/BEPs/assets/bep-130/2_workflow.png b/BEPs/assets/bep-130/2_workflow.png new file mode 100644 index 000000000..1687fb555 Binary files /dev/null and b/BEPs/assets/bep-130/2_workflow.png differ diff --git a/BEPs/assets/bep-130/3_pipeline.png b/BEPs/assets/bep-130/3_pipeline.png new file mode 100644 index 000000000..797be4439 Binary files /dev/null and b/BEPs/assets/bep-130/3_pipeline.png differ diff --git a/BEPs/assets/bep-130/4_init.png b/BEPs/assets/bep-130/4_init.png new file mode 100644 index 000000000..cf6fb4140 Binary files /dev/null and b/BEPs/assets/bep-130/4_init.png differ diff --git a/BEPs/assets/bep-130/5_dispatcher.png b/BEPs/assets/bep-130/5_dispatcher.png new file mode 100644 index 000000000..c6033fa37 Binary files /dev/null and b/BEPs/assets/bep-130/5_dispatcher.png differ diff --git a/BEPs/assets/bep-130/6_stages.png b/BEPs/assets/bep-130/6_stages.png new file mode 100644 index 000000000..49315fcf8 Binary files /dev/null and b/BEPs/assets/bep-130/6_stages.png differ diff --git a/BEPs/assets/bep-130/7_conflict_window.png b/BEPs/assets/bep-130/7_conflict_window.png new file mode 100644 index 000000000..98fe5014c Binary files /dev/null and b/BEPs/assets/bep-130/7_conflict_window.png differ diff --git a/BEPs/assets/bep-131/5.1_overview.png b/BEPs/assets/bep-131/5.1_overview.png new file mode 100644 index 000000000..d8724f6ba Binary files /dev/null and b/BEPs/assets/bep-131/5.1_overview.png differ diff --git a/BEPs/assets/bep-131/5.2_workflow.png b/BEPs/assets/bep-131/5.2_workflow.png new file mode 100644 index 000000000..7479a3108 Binary files /dev/null and b/BEPs/assets/bep-131/5.2_workflow.png differ diff --git a/BEPs/assets/bep-131/5.5_election.png b/BEPs/assets/bep-131/5.5_election.png new file mode 100644 index 000000000..6a1673f6d Binary files /dev/null and b/BEPs/assets/bep-131/5.5_election.png differ diff --git a/BEPs/assets/bep-153/5.1_framework.jpg b/BEPs/assets/bep-153/5.1_framework.jpg new file mode 100644 index 000000000..d1cd2ba40 Binary files /dev/null and b/BEPs/assets/bep-153/5.1_framework.jpg differ diff --git a/BEPs/assets/bep-153/5.2_stake.jpg b/BEPs/assets/bep-153/5.2_stake.jpg new file mode 100644 index 000000000..9cf748545 Binary files /dev/null and b/BEPs/assets/bep-153/5.2_stake.jpg differ diff --git a/BEPs/assets/bep-153/5.3_errorhandle.jpg b/BEPs/assets/bep-153/5.3_errorhandle.jpg new file mode 100644 index 000000000..15c9157ae Binary files /dev/null and b/BEPs/assets/bep-153/5.3_errorhandle.jpg differ diff --git a/BEPs/assets/bep-153/SampleStakingContract.sol b/BEPs/assets/bep-153/SampleStakingContract.sol new file mode 100644 index 000000000..a3a3fb593 --- /dev/null +++ b/BEPs/assets/bep-153/SampleStakingContract.sol @@ -0,0 +1,288 @@ +pragma solidity 0.8.16; + +interface IStaking { + + function delegate(address validator, uint256 amount) external payable; + + function undelegate(address validator, uint256 amount) external payable; + + function redelegate(address validatorSrc, address validatorDst, uint256 amount) external payable; + + function claimReward() external returns(uint256); + + function claimUndeldegated() external returns(uint256); + + function getDelegated(address delegator, address validator) external view returns(uint256); + + function getDistributedReward(address delegator) external view returns(uint256); + + function getUndelegated(address delegator) external view returns(uint256); + + function getPendingUndelegateTime(address delegator, address validator) external view returns(uint256); + + function getPendingRedelegateTime(address delegator, address valSrc, address valDst) external view returns(uint256); + + function getOracleRelayerFee() external view returns(uint256); + + function getMinDelegation() external view returns(uint256); +} + +contract StakingDappExample { + bool internal locked; + + // constants + uint256 public constant TEN_DECIMALS = 10; + address public constant STAKING_CONTRACT_ADDR = 0x0000000000000000000000000000000000002001; + + // data struct + struct PoolInfo { + uint256 rewardPerShare; + uint256 lastRewardBlock; + uint256 lastTotalReward; + } + + struct UserInfo { + uint256 amount; + uint256 rewardDebt; + uint256 pendingUndelegated; + uint256 undelegateUnlockTime; + } + + // global variables + address public owner; + uint256 public totalReceived; + uint256 public totalStaked; + uint256 public totalReward; + uint256 public reserveReward; + uint256 public reserveUndelegated; + + PoolInfo internal poolInfo; + mapping(address => UserInfo) internal userInfo; + mapping(address => bool) internal operators; + + // modifiers + modifier onlyOwner() { + require(msg.sender == owner, "only owner can call this function"); + _; + } + + modifier onlyOperator() { + require(operators[msg.sender], "only operator can call this function"); + _; + } + + modifier noReentrant() { + require(!locked, "No re-entrancy"); + locked = true; + _; + locked = false; + } + + // events + event Delegate(address indexed delegator, uint256 amount); + event DelegateSubmitted(address indexed validator, uint256 amount); + event Undelegate(address indexed delegator, uint256 amount); + event UndelegateSubmitted(address indexed validator, uint256 amount); + event RewardClaimed(address indexed delegator, uint256 amount); + event UndelegatedClaimed(address indexed delegator, uint256 amount); + event RewardReceived(uint256 amount); + event UndelegatedReceived(uint256 amount); + + receive() external payable {} + + constructor() { + owner = msg.sender; + operators[msg.sender] = true; + } + + /*********************** For user **************************/ + // This function will not always submit delegation request to the staking system contract. + // The delegation will be triggered when unstaked fund is greater than the minDelegationChange. + function delegate() external payable { + uint256 amount = msg.value; + + // update reward first + UserInfo storage user = userInfo[msg.sender]; + _updatePool(); + uint256 pendingReward; + if (user.amount > 0) { + pendingReward = user.amount*poolInfo.rewardPerShare-user.rewardDebt; + } + user.amount = user.amount+amount; + user.rewardDebt = user.amount*poolInfo.rewardPerShare-pendingReward; + + totalReceived = totalReceived+amount; + reserveUndelegated = reserveUndelegated+amount; + uint256 minDelegation = IStaking(STAKING_CONTRACT_ADDR).getMinDelegation(); + if (reserveUndelegated >= 2*minDelegation) { + uint256 realAmount = reserveUndelegated-minDelegation; + uint256 oracleRelayerFee = IStaking(STAKING_CONTRACT_ADDR).getOracleRelayerFee(); + if (address(this).balance < realAmount+oracleRelayerFee) { + return; + } + realAmount = _delegate(realAmount, oracleRelayerFee); + totalStaked = totalStaked+realAmount; + reserveUndelegated = reserveUndelegated-realAmount; + } + + emit Delegate(msg.sender, amount); + } + + // This function will not always submit delegation request to the staking system contract. + // The delegation will be triggered when reserve fund is less than the threshold. + function undelegate(uint256 amount) external { + UserInfo storage user = userInfo[msg.sender]; + require(user.amount >= amount, "insufficient balance"); + + // update reward first + _updatePool(); + uint256 pendingReward = user.amount*poolInfo.rewardPerShare-user.rewardDebt; + user.amount = user.amount-amount; + user.rewardDebt = user.amount*poolInfo.rewardPerShare-pendingReward; + + user.pendingUndelegated = user.pendingUndelegated+amount; + user.undelegateUnlockTime = block.timestamp+8*24*3600; + + uint256 minDelegation = IStaking(STAKING_CONTRACT_ADDR).getMinDelegation(); + if (reserveUndelegated < minDelegation) { + uint256 oracleRelayerFee = IStaking(STAKING_CONTRACT_ADDR).getOracleRelayerFee(); + _undelegate(minDelegation, oracleRelayerFee); + totalStaked = totalStaked-minDelegation; + reserveUndelegated = reserveUndelegated+minDelegation; + } + + totalReceived = totalReceived-amount; + emit Undelegate(msg.sender, amount); + } + + function getDelegated(address delegator) external view returns(uint256) { + return userInfo[delegator].amount; + } + + function claimReward() external noReentrant { + UserInfo storage user = userInfo[msg.sender]; + require(user.amount > 0, "no delegation"); + + _updatePool(); + uint256 pendingReward = user.amount*poolInfo.rewardPerShare-user.rewardDebt; + if (reserveReward < pendingReward) { + _claimReward(); + } + user.rewardDebt = user.amount*poolInfo.rewardPerShare; + payable(msg.sender).transfer(pendingReward); + emit RewardClaimed(msg.sender, pendingReward); + } + + function claimUndelegated() external noReentrant { + UserInfo storage user = userInfo[msg.sender]; + require((user.pendingUndelegated > 0) && (block.timestamp > user.undelegateUnlockTime), "no undelegated funds"); + + if (reserveUndelegated < user.pendingUndelegated) { + _claimUndelegated(); + } + reserveUndelegated = reserveUndelegated-user.pendingUndelegated; + totalReceived = totalReceived-user.pendingUndelegated; + user.pendingUndelegated = 0; + payable(msg.sender).transfer(user.pendingUndelegated); + emit UndelegatedClaimed(msg.sender, user.pendingUndelegated); + } + + function getPendingReward(address delegator) external view returns(uint256 pendingReward) { + UserInfo memory user = userInfo[delegator]; + pendingReward = user.amount*poolInfo.rewardPerShare-user.rewardDebt; + } + + /************************** Internal **************************/ + function _getHighestYieldingValidator() internal pure returns(uint160 highestYieldingValidator) { + // this function should return the desirable validator to delegate to + // need to be implemented by the developer + // use uint160 rather than address to prevent checksum error + highestYieldingValidator = uint160(0x001); + } + + function _getLowestYieldingValidator() internal pure returns(uint160 lowestYieldingValidator) { + // this function should return the desirable validator to undelegate from + // need to be implemented by the developer + // use uint160 rather than address to prevent checksum error + lowestYieldingValidator = uint160(0x002); + } + + function _delegate(uint256 amount, uint256 oracleRelayerFee) internal returns(uint256) { + address validator = address(_getHighestYieldingValidator()); + amount -= amount%TEN_DECIMALS; + IStaking(STAKING_CONTRACT_ADDR).delegate{value: amount+oracleRelayerFee}(validator, amount); + emit DelegateSubmitted(validator, amount); + return amount; + } + + function _undelegate(uint256 amount, uint256 oracleRelayerFee) internal returns(uint256) { + address validator = address(_getLowestYieldingValidator()); + amount -= amount%TEN_DECIMALS; + IStaking(STAKING_CONTRACT_ADDR).undelegate{value: oracleRelayerFee}(validator, amount); + emit UndelegateSubmitted(validator, amount); + return amount; + } + + function _claimReward() internal { + uint256 amount = IStaking(STAKING_CONTRACT_ADDR).claimReward(); + totalReward = totalReward+amount; + reserveReward = reserveReward+amount; + emit RewardReceived(amount); + } + + function _claimUndelegated() internal { + uint256 amount = IStaking(STAKING_CONTRACT_ADDR).claimUndeldegated(); + emit UndelegatedReceived(amount); + } + + function _updatePool() internal { + if (block.number <= poolInfo.lastRewardBlock) { + return; + } + if (totalReward == poolInfo.lastTotalReward) { + return; + } + uint256 newReward = totalReward - poolInfo.lastTotalReward; + poolInfo.lastTotalReward = totalReward; + poolInfo.rewardPerShare = poolInfo.rewardPerShare+newReward/totalStaked; + poolInfo.lastRewardBlock = block.number; + } + + /*********************** Handle faliure **************************/ + // This parts of functions should be called by the operator when failed event detected by the monitor + function handleFailedDelegate(uint256 amount) external onlyOperator { + totalStaked = totalStaked-amount; + reserveUndelegated = reserveUndelegated+amount; + + amount = IStaking(STAKING_CONTRACT_ADDR).claimUndeldegated(); + uint256 oracleRelayerFee = IStaking(STAKING_CONTRACT_ADDR).getOracleRelayerFee(); + require(address(this).balance > amount+oracleRelayerFee, "insufficient balance"); + amount = _delegate(amount, oracleRelayerFee); + totalStaked = totalStaked+amount; + reserveUndelegated = reserveUndelegated-amount; + } + + function handleFailedUndelegate(uint256 amount) external onlyOperator { + totalStaked = totalStaked+amount; + reserveUndelegated = reserveUndelegated-amount; + + uint256 oracleRelayerFee = IStaking(STAKING_CONTRACT_ADDR).getOracleRelayerFee(); + require(address(this).balance > oracleRelayerFee, "insufficient balance"); + amount = _undelegate(amount, oracleRelayerFee); + totalStaked = totalStaked-amount; + reserveUndelegated = reserveUndelegated+amount; + } + + /*********************** Params update **************************/ + function transferOwnership(address newOwner) external onlyOwner { + owner = newOwner; + } + + function addOperator(address opt) external onlyOwner { + operators[opt] = true; + } + + function delOperator(address opt) external onlyOwner { + operators[opt] = false; + } +} diff --git a/BEPs/assets/bep-194/node_distribution.png b/BEPs/assets/bep-194/node_distribution.png new file mode 100644 index 000000000..250a658fa Binary files /dev/null and b/BEPs/assets/bep-194/node_distribution.png differ diff --git a/BEPs/assets/bep-206/1_components.png b/BEPs/assets/bep-206/1_components.png new file mode 100644 index 000000000..c7e60091c Binary files /dev/null and b/BEPs/assets/bep-206/1_components.png differ diff --git a/BEPs/assets/bep-206/2_workflow.png b/BEPs/assets/bep-206/2_workflow.png new file mode 100644 index 000000000..af6f3d994 Binary files /dev/null and b/BEPs/assets/bep-206/2_workflow.png differ diff --git a/BEPs/assets/bep-206/3_epochTree.png b/BEPs/assets/bep-206/3_epochTree.png new file mode 100644 index 000000000..00c30efd9 Binary files /dev/null and b/BEPs/assets/bep-206/3_epochTree.png differ diff --git a/BEPs/assets/bep-206/4_epochKey.png b/BEPs/assets/bep-206/4_epochKey.png new file mode 100644 index 000000000..cf6fc9de6 Binary files /dev/null and b/BEPs/assets/bep-206/4_epochKey.png differ diff --git a/BEPs/assets/bep-206/5_trieMeta.png b/BEPs/assets/bep-206/5_trieMeta.png new file mode 100644 index 000000000..03b1ab7d1 Binary files /dev/null and b/BEPs/assets/bep-206/5_trieMeta.png differ diff --git a/BEPs/assets/bep-206/6_extendedBranchNode.png b/BEPs/assets/bep-206/6_extendedBranchNode.png new file mode 100644 index 000000000..5e171d743 Binary files /dev/null and b/BEPs/assets/bep-206/6_extendedBranchNode.png differ diff --git a/BEPs/assets/bep-206/7_snapshot.png b/BEPs/assets/bep-206/7_snapshot.png new file mode 100644 index 000000000..b9c343a9a Binary files /dev/null and b/BEPs/assets/bep-206/7_snapshot.png differ diff --git a/BEPs/assets/bep-294/5.1_framework.png b/BEPs/assets/bep-294/5.1_framework.png new file mode 100644 index 000000000..2eb081c71 Binary files /dev/null and b/BEPs/assets/bep-294/5.1_framework.png differ diff --git a/BEPs/assets/bep-294/5.2_stakehub.png b/BEPs/assets/bep-294/5.2_stakehub.png new file mode 100644 index 000000000..2f26ff92b Binary files /dev/null and b/BEPs/assets/bep-294/5.2_stakehub.png differ diff --git a/BEPs/assets/bep-294/5.3_update_eligible_validators.png b/BEPs/assets/bep-294/5.3_update_eligible_validators.png new file mode 100644 index 000000000..c97fc0749 Binary files /dev/null and b/BEPs/assets/bep-294/5.3_update_eligible_validators.png differ diff --git a/BEPs/assets/bep-299/asset_recovery_app.png b/BEPs/assets/bep-299/asset_recovery_app.png new file mode 100644 index 000000000..14b1755a9 Binary files /dev/null and b/BEPs/assets/bep-299/asset_recovery_app.png differ diff --git a/BEPs/assets/bep-299/asset_tree.png b/BEPs/assets/bep-299/asset_tree.png new file mode 100644 index 000000000..1bf98c1bc Binary files /dev/null and b/BEPs/assets/bep-299/asset_tree.png differ diff --git a/BEPs/assets/bep-322/block_timing.png b/BEPs/assets/bep-322/block_timing.png new file mode 100644 index 000000000..40f197bf5 Binary files /dev/null and b/BEPs/assets/bep-322/block_timing.png differ diff --git a/BEPs/assets/bep-322/workflow_1round.png b/BEPs/assets/bep-322/workflow_1round.png new file mode 100644 index 000000000..7d0fc6e03 Binary files /dev/null and b/BEPs/assets/bep-322/workflow_1round.png differ diff --git a/BEPs/assets/bep-322/workflow_2round.png b/BEPs/assets/bep-322/workflow_2round.png new file mode 100644 index 000000000..c04ac890c Binary files /dev/null and b/BEPs/assets/bep-322/workflow_2round.png differ diff --git a/BEPs/assets/bep-322/workflow_2round_proxy.png b/BEPs/assets/bep-322/workflow_2round_proxy.png new file mode 100644 index 000000000..9ffce46a5 Binary files /dev/null and b/BEPs/assets/bep-322/workflow_2round_proxy.png differ diff --git a/BEPs/assets/bep-322/workflow_topology.png b/BEPs/assets/bep-322/workflow_topology.png new file mode 100644 index 000000000..4fcce7530 Binary files /dev/null and b/BEPs/assets/bep-322/workflow_topology.png differ diff --git a/BEPs/assets/bep-323/bundle_encoding.png b/BEPs/assets/bep-323/bundle_encoding.png new file mode 100644 index 000000000..2edae5eb5 Binary files /dev/null and b/BEPs/assets/bep-323/bundle_encoding.png differ diff --git a/BEPs/assets/bep-323/bundle_struct.png b/BEPs/assets/bep-323/bundle_struct.png new file mode 100644 index 000000000..0b751f898 Binary files /dev/null and b/BEPs/assets/bep-323/bundle_struct.png differ diff --git a/BEPs/assets/bep-333/phases.png b/BEPs/assets/bep-333/phases.png new file mode 100644 index 000000000..6522dff99 Binary files /dev/null and b/BEPs/assets/bep-333/phases.png differ diff --git a/BEPs/assets/bep-341/4.1-1.png b/BEPs/assets/bep-341/4.1-1.png new file mode 100644 index 000000000..adce49369 Binary files /dev/null and b/BEPs/assets/bep-341/4.1-1.png differ diff --git a/BEPs/assets/bep-341/4.1-2.png b/BEPs/assets/bep-341/4.1-2.png new file mode 100644 index 000000000..e07c985d4 Binary files /dev/null and b/BEPs/assets/bep-341/4.1-2.png differ diff --git a/BEPs/assets/bep-341/4.1-3.png b/BEPs/assets/bep-341/4.1-3.png new file mode 100644 index 000000000..4114d5367 Binary files /dev/null and b/BEPs/assets/bep-341/4.1-3.png differ diff --git a/BEPs/assets/bep-341/4.1-4.png b/BEPs/assets/bep-341/4.1-4.png new file mode 100644 index 000000000..70d3e76d8 Binary files /dev/null and b/BEPs/assets/bep-341/4.1-4.png differ diff --git a/BEPs/assets/bep-341/4.1-5.png b/BEPs/assets/bep-341/4.1-5.png new file mode 100644 index 000000000..b2441215d Binary files /dev/null and b/BEPs/assets/bep-341/4.1-5.png differ diff --git a/BEPs/assets/bep-341/4.1-6.png b/BEPs/assets/bep-341/4.1-6.png new file mode 100644 index 000000000..02c2b4122 Binary files /dev/null and b/BEPs/assets/bep-341/4.1-6.png differ diff --git a/BEPs/assets/bep-341/4.2.1.png b/BEPs/assets/bep-341/4.2.1.png new file mode 100644 index 000000000..8a8fdd25c Binary files /dev/null and b/BEPs/assets/bep-341/4.2.1.png differ diff --git a/BEPs/assets/bep-341/4.2.2.png b/BEPs/assets/bep-341/4.2.2.png new file mode 100644 index 000000000..4e2bc8309 Binary files /dev/null and b/BEPs/assets/bep-341/4.2.2.png differ diff --git a/BEPs/assets/bep-341/4.2.3.png b/BEPs/assets/bep-341/4.2.3.png new file mode 100644 index 000000000..4fa124913 Binary files /dev/null and b/BEPs/assets/bep-341/4.2.3.png differ diff --git a/BEPs/assets/bep-341/4.2.5-1.png b/BEPs/assets/bep-341/4.2.5-1.png new file mode 100644 index 000000000..1de9bf86d Binary files /dev/null and b/BEPs/assets/bep-341/4.2.5-1.png differ diff --git a/BEPs/assets/bep-341/4.2.5-2.png b/BEPs/assets/bep-341/4.2.5-2.png new file mode 100644 index 000000000..cbb7d0854 Binary files /dev/null and b/BEPs/assets/bep-341/4.2.5-2.png differ diff --git a/BEPs/assets/bep-363/4.1.1_framework.png b/BEPs/assets/bep-363/4.1.1_framework.png new file mode 100644 index 000000000..a7af51efe Binary files /dev/null and b/BEPs/assets/bep-363/4.1.1_framework.png differ diff --git a/BEPs/assets/bep-414/wallet-interact.png b/BEPs/assets/bep-414/wallet-interact.png new file mode 100644 index 000000000..2e565ecd0 Binary files /dev/null and b/BEPs/assets/bep-414/wallet-interact.png differ diff --git a/BEPs/assets/bep-414/workflow.png b/BEPs/assets/bep-414/workflow.png new file mode 100644 index 000000000..db6ebb229 Binary files /dev/null and b/BEPs/assets/bep-414/workflow.png differ diff --git a/BEPs/assets/bep-439/add_G1_bls.json b/BEPs/assets/bep-439/add_G1_bls.json new file mode 100644 index 000000000..a7f44dda8 --- /dev/null +++ b/BEPs/assets/bep-439/add_G1_bls.json @@ -0,0 +1,65 @@ +[ + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "Name": "bls_g1add_g1+p1", + "Expected": "000000000000000000000000000000000a40300ce2dec9888b60690e9a41d3004fda4886854573974fab73b046d3147ba5b7a5bde85279ffede1b45b3918d82d0000000000000000000000000000000006d3d887e9f53b9ec4eb6cedf5607226754b07c01ace7834f57f3e7315faefb739e59018e22c492006190fba4a870025", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Name": "bls_g1add_p1+g1", + "Expected": "000000000000000000000000000000000a40300ce2dec9888b60690e9a41d3004fda4886854573974fab73b046d3147ba5b7a5bde85279ffede1b45b3918d82d0000000000000000000000000000000006d3d887e9f53b9ec4eb6cedf5607226754b07c01ace7834f57f3e7315faefb739e59018e22c492006190fba4a870025", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00000000000000000000000000000000193fb7cedb32b2c3adc06ec11a96bc0d661869316f5e4a577a9f7c179593987beb4fb2ee424dbb2f5dd891e228b46c4a0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Name": "bls_g1add_g1_wrong_order+g1", + "Expected": "000000000000000000000000000000000abe7ae4ae2b092a5cc1779b1f5605d904fa6ec59b0f084907d1f5e4d2663e117a3810e027210a72186159a21271df3e0000000000000000000000000000000001e1669f00e10205f2e2f1195d65c21022f6a9a6de21f329756309815281a4434b2864d34ebcbc1d7e7cfaaee3feeea2", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1add_(g1+0=g1)", + "Expected": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1add_(p1+0=p1)", + "Expected": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000114d1d6855d545a8aa7d76c8cf2e21f267816aef1db507c96655b9d5caac42364e6f38ba0ecb751bad54dcd6b939c2ca", + "Name": "bls_g1add_(g1-g1=0)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca9426000000000000000000000000000000000195e911162921ba5ed055b496420f197693d36569ec34c63d7c0529a097d49e543070afba4b707e878e53c2b779208a", + "Name": "bls_g1add_(p1-p1=0)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Name": "bls_g1add_(g1+g1=2*g1)", + "Expected": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d28", + "Gas": 500, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "Name": "bls_g1add_(p1+p1=2*p1)", + "Expected": "0000000000000000000000000000000015222cddbabdd764c4bee0b3720322a65ff4712c86fc4b1588d0c209210a0884fa9468e855d261c483091b2bf7de6a630000000000000000000000000000000009f9edb99bc3b75d7489735c98b16ab78b9386c5f7a1f76c7e96ac6eb5bbde30dbca31a74ec6e0f0b12229eecea33c39", + "Gas": 500, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/add_G2_bls.json b/BEPs/assets/bep-439/add_G2_bls.json new file mode 100644 index 000000000..36a7614d3 --- /dev/null +++ b/BEPs/assets/bep-439/add_G2_bls.json @@ -0,0 +1,65 @@ +[ + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "Name": "bls_g2add_g2+p2", + "Expected": "000000000000000000000000000000000b54a8a7b08bd6827ed9a797de216b8c9057b3a9ca93e2f88e7f04f19accc42da90d883632b9ca4dc38d013f71ede4db00000000000000000000000000000000077eba4eecf0bd764dce8ed5f45040dd8f3b3427cb35230509482c14651713282946306247866dfe39a8e33016fcbe520000000000000000000000000000000014e60a76a29ef85cbd69f251b9f29147b67cfe3ed2823d3f9776b3a0efd2731941d47436dc6d2b58d9e65f8438bad073000000000000000000000000000000001586c3c910d95754fef7a732df78e279c3d37431c6a2b77e67a00c7c130a8fcd4d19f159cbeb997a178108fffffcbd20", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d87845100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Name": "bls_g2add_p2+g2", + "Expected": "000000000000000000000000000000000b54a8a7b08bd6827ed9a797de216b8c9057b3a9ca93e2f88e7f04f19accc42da90d883632b9ca4dc38d013f71ede4db00000000000000000000000000000000077eba4eecf0bd764dce8ed5f45040dd8f3b3427cb35230509482c14651713282946306247866dfe39a8e33016fcbe520000000000000000000000000000000014e60a76a29ef85cbd69f251b9f29147b67cfe3ed2823d3f9776b3a0efd2731941d47436dc6d2b58d9e65f8438bad073000000000000000000000000000000001586c3c910d95754fef7a732df78e279c3d37431c6a2b77e67a00c7c130a8fcd4d19f159cbeb997a178108fffffcbd20", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000197bfd0342bbc8bee2beced2f173e1a87be576379b343e93232d6cef98d84b1d696e5612ff283ce2cfdccb2cfb65fa0c00000000000000000000000000000000184e811f55e6f9d84d77d2f79102fd7ea7422f4759df5bf7f6331d550245e3f1bcf6a30e3b29110d85e0ca16f9f6ae7a000000000000000000000000000000000f10e1eb3c1e53d2ad9cf2d398b2dc22c5842fab0a74b174f691a7e914975da3564d835cd7d2982815b8ac57f507348f000000000000000000000000000000000767d1c453890f1b9110fda82f5815c27281aba3f026ee868e4176a0654feea41a96575e0c4d58a14dbfbcc05b5010b100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Name": "bls_g2add_g2_wrong_order+g2", + "Expected": "0000000000000000000000000000000011f00077935238fc57086414804303b20fab5880bc29f35ebda22c13dd44e586c8a889fe2ba799082c8458d861ac10cf0000000000000000000000000000000007318be09b19be000fe5df77f6e664a8286887ad8373005d7f7a203fcc458c28004042780146d3e43fa542d921c69512000000000000000000000000000000001287eab085d6f8a29f1f1aedb5ad9e8546963f0b11865e05454d86b9720c281db567682a233631f63a2794432a5596ae0000000000000000000000000000000012ec87cea1bacb75aa97728bcd64b27c7a42dd2319a2e17fe3837a05f85d089c5ebbfb73c1d08b7007e2b59ec9c8e065", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2add_(g2+0=g2)", + "Expected": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d87845100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2add_(p2+0=p2)", + "Expected": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "Name": "bls_g2add_(g2-g2=0)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d87845100000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000a6296409115572426717c73668335a949829d739cff2cb4ab043710d28f8e772f6ef41aac4806c9cb273c490384032d000000000000000000000000000000000cde4e850c721fa94e8890d500e3655b442d5c0dc4fff1b694c6f8dd68f6d8dc1bc3251a37d27e7af96f65a96278265a", + "Name": "bls_g2add_(p2-p2=0)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Name": "bls_g2add_(g2+g2=2*g2)", + "Expected": "000000000000000000000000000000001638533957d540a9d2370f17cc7ed5863bc0b995b8825e0ee1ea1e1e4d00dbae81f14b0bf3611b78c952aacab827a053000000000000000000000000000000000a4edef9c1ed7f729f520e47730a124fd70662a904ba1074728114d1031e1572c6c886f6b57ec72a6178288c47c33577000000000000000000000000000000000468fb440d82b0630aeb8dca2b5256789a66da69bf91009cbfe6bd221e47aa8ae88dece9764bf3bd999d95d71e4c9899000000000000000000000000000000000f6d4552fa65dd2638b361543f887136a43253d9c66c411697003f7a13c308f5422e1aa0a59c8967acdefd8b6e36ccf3", + "Gas": 800, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d87845100000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "Name": "bls_g2add_(p2+p2=2*p2)", + "Expected": "000000000000000000000000000000000b76fcbb604082a4f2d19858a7befd6053fa181c5119a612dfec83832537f644e02454f2b70d40985ebb08042d1620d40000000000000000000000000000000019a4a02c0ae51365d964c73be7babb719db1c69e0ddbf9a8a335b5bed3b0a4b070d2d5df01d2da4a3f1e56aae2ec106d000000000000000000000000000000000d18322f821ac72d3ca92f92b000483cf5b7d9e5d06873a44071c4e7e81efd904f210208fe0b9b4824f01c65bc7e62080000000000000000000000000000000004e563d53609a2d1e216aaaee5fbc14ef460160db8d1fdc5e1bd4e8b54cd2f39abf6f925969fa405efb9e700b01c7085", + "Gas": 800, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/bench_vectors.md b/BEPs/assets/bep-439/bench_vectors.md new file mode 100644 index 000000000..5e44b4776 --- /dev/null +++ b/BEPs/assets/bep-439/bench_vectors.md @@ -0,0 +1,22 @@ +# Set of test vectors to perform benchmarking of BEP-439 + +## Inlined vectors + +Here one can find inputs (encoded with ABI from the main spec spec) that can be considered "worst cases" for "double-and-add" multiplication algorithm, and also some cases for pairing call. Those are purely for convenience of initial benchmarking of the full ABI without manual test generation. + +``` +G1 addition example input = +0000000000000000000000000000000012196c5a43d69224d8713389285f26b98f86ee910ab3dd668e413738282003cc5b7357af9a7af54bb713d62255e80f560000000000000000000000000000000006ba8102bfbeea4416b710c73e8cce3032c31c6269c44906f8ac4f7874ce99fb17559992486528963884ce429a992fee000000000000000000000000000000000001101098f5c39893765766af4512a0c74e1bb89bc7e6fdf14e3e7337d257cc0f94658179d83320b99f31ff94cd2bac0000000000000000000000000000000003e1a9f9f44ca2cdab4f43a1a3ee3470fdf90b2fc228eb3b709fcd72f014838ac82a6d797aeefed9a0804b22ed1ce8f7 +G2 addition example input = +0000000000000000000000000000000018c0ada6351b70661f053365deae56910798bd2ace6e2bf6ba4192d1a229967f6af6ca1c9a8a11ebc0a232344ee0f6d6000000000000000000000000000000000cc70a587f4652039d8117b6103858adcd9728f6aebe230578389a62da0042b7623b1c0436734f463cfdd187d20903240000000000000000000000000000000009f50bd7beedb23328818f9ffdafdb6da6a4dd80c5a9048ab8b154df3cad938ccede829f1156f769d9e149791e8e0cd900000000000000000000000000000000079ba50d2511631b20b6d6f3841e616e9d11b68ec3368cd60129d9d4787ab56c4e9145a38927e51c9cd6271d493d938800000000000000000000000000000000192fa5d8732ff9f38e0b1cf12eadfd2608f0c7a39aced7746837833ae253bb57ef9c0d98a4b69eeb2950901917e99d1e0000000000000000000000000000000009aeb10c372b5ef1010675c6a4762fda33636489c23b581c75220589afbc0cc46249f921eea02dd1b761e036ffdbae220000000000000000000000000000000002d225447600d49f932b9dd3ca1e6959697aa603e74d8666681a2dca8160c3857668ae074440366619eb8920256c4e4a00000000000000000000000000000000174882cdd3551e0ce6178861ff83e195fecbcffd53a67b6f10b4431e423e28a480327febe70276036f60bb9c99cf7633 +G1 mul double and add worst case = +0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +G2 mul double and add worst case = +00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79beffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff +Pairing case for 2 pairs = +0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be +Pairing case for 4 pairs = +0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be +Pairing case for 6 pairs = +0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be +``` diff --git a/BEPs/assets/bep-439/fail-add_G1_bls.json b/BEPs/assets/bep-439/fail-add_G1_bls.json new file mode 100644 index 000000000..e61e269d2 --- /dev/null +++ b/BEPs/assets/bep-439/fail-add_G1_bls.json @@ -0,0 +1,32 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g1add_empty_input" + }, + { + "Input": "00000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "ExpectedError": "invalid input length", + "Name": "bls_g1add_short_input" + }, + { + "Input": "000000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "ExpectedError": "invalid input length", + "Name": "bls_g1add_large_input" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g1add_point_not_on_curve" + }, + { + "Input": "0000000000000000000000000000000031f2e5916b17be2e71b10b4292f558e727dfd7d48af9cbc5087f0ce00dcca27c8b01e83eaace1aefb539f00adb2271660000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g2add_invalid_field_element" + }, + { + "Input": "1000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g1add_violate_top_bytes" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-add_G2_bls.json b/BEPs/assets/bep-439/fail-add_G2_bls.json new file mode 100644 index 000000000..9d3ab9c18 --- /dev/null +++ b/BEPs/assets/bep-439/fail-add_G2_bls.json @@ -0,0 +1,32 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g2add_empty_input" + }, + { + "Input": "000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "ExpectedError": "invalid input length", + "Name": "bls_g2add_short_input" + }, + { + "Input": "0000000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "ExpectedError": "invalid input length", + "Name": "bls_g2add_long_input" + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb800000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g2add_point_not_on_curve" + }, + { + "Input": "000000000000000000000000000000001c4bb49d2a0ef12b7123acdd7110bd292b5bc659edc54dc21b81de057194c79b2a5803255959bbef8e7f56c8c12168630000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g2add_invalid_field_element" + }, + { + "Input": "10000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g2add_violate_top_bytes" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-map_fp2_to_G2_bls.json b/BEPs/assets/bep-439/fail-map_fp2_to_G2_bls.json new file mode 100644 index 000000000..4411fdcc0 --- /dev/null +++ b/BEPs/assets/bep-439/fail-map_fp2_to_G2_bls.json @@ -0,0 +1,27 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_mapg2_empty_input" + }, + { + "Input": "0000000000000000000000000000000007355d25caf6e7f2f0cb2812ca0e513bd026ed09dda65b177500fa31714e09ea0ded3a078b526bed3307f804d4b93b040000000000000000000000000000000002829ce3c021339ccb5caf3e187f6370e1e2a311dec9b75363117063ab2015603ff52c3d3b98f19c2f65575e99e8b7", + "ExpectedError": "invalid input length", + "Name": "bls_mapg2_short_input" + }, + { + "Input": "000000000000000000000000000000000007355d25caf6e7f2f0cb2812ca0e513bd026ed09dda65b177500fa31714e09ea0ded3a078b526bed3307f804d4b93b040000000000000000000000000000000002829ce3c021339ccb5caf3e187f6370e1e2a311dec9b75363117063ab2015603ff52c3d3b98f19c2f65575e99e8b78c", + "ExpectedError": "invalid input length", + "Name": "bls_mapg2_long_input" + }, + { + "Input": "000000000000000000000000000000000007355d25caf6e7f2f0cb2812ca0e513bd026ed09dda65b177500fa31714e09ea0ded3a078b526bed3307f804d4b93b040000000000000000000000000000000002829ce3c021339ccb5caf3e187f6370e1e2a311dec9b75363117063ab2015603ff52c3d3b98f19c2f65575e99e8b7", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_mapg2_top_bytes" + }, + { + "Input": "0000000000000000000000000000000021366f100476ce8d3be6cfc90d59fe13349e388ed12b6dd6dc31ccd267ff000e2c993a063ca66beced06f804d4b8e5af0000000000000000000000000000000002829ce3c021339ccb5caf3e187f6370e1e2a311dec9b75363117063ab2015603ff52c3d3b98f19c2f65575e99e8b78c", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_mapg2_invalid_fq_element" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-map_fp_to_G1_bls.json b/BEPs/assets/bep-439/fail-map_fp_to_G1_bls.json new file mode 100644 index 000000000..2f6685693 --- /dev/null +++ b/BEPs/assets/bep-439/fail-map_fp_to_G1_bls.json @@ -0,0 +1,27 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_mapg1_empty_input" + }, + { + "Input": "00000000000000000000000000000000156c8a6a2c184569d69a76be144b5cdc5141d2d2ca4fe341f011e25e3969c55ad9e9b9ce2eb833c81a908e5fa4ac5f", + "ExpectedError": "invalid input length", + "Name": "bls_mapg1_short_input" + }, + { + "Input": "0000000000000000000000000000000000156c8a6a2c184569d69a76be144b5cdc5141d2d2ca4fe341f011e25e3969c55ad9e9b9ce2eb833c81a908e5fa4ac5f03", + "ExpectedError": "invalid input length", + "Name": "bls_mapg1_large_input" + }, + { + "Input": "1000000000000000000000000000000000156c8a6a2c184569d69a76be144b5cdc5141d2d2ca4fe341f011e25e3969c55ad9e9b9ce2eb833c81a908e5fa4ac5f", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_mapg1_top_bytes" + }, + { + "Input": "000000000000000000000000000000002f6d9c5465982c0421b61e74579709b3b5b91e57bdd4f6015742b4ff301abb7ef895b9cce00c33c7d48f8e5fa4ac09ae", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_invalid_fq_element" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-mul_G1_bls.json b/BEPs/assets/bep-439/fail-mul_G1_bls.json new file mode 100644 index 000000000..5ae8e3b53 --- /dev/null +++ b/BEPs/assets/bep-439/fail-mul_G1_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g1mul_empty_input" + }, + { + "Input": "00000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g1mul_short_input" + }, + { + "Input": "000000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g1mul_large_input" + }, + { + "Input": "0000000000000000000000000000000031f2e5916b17be2e71b10b4292f558e727dfd7d48af9cbc5087f0ce00dcca27c8b01e83eaace1aefb539f00adb2271660000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g1mul_invalid_field_element" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g1mul_point_not_on_curve" + }, + { + "Input": "1000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g1mul_violate_top_bytes" + }, + { + "Input": "000000000000000000000000000000000123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00000000000000000000000000000000193fb7cedb32b2c3adc06ec11a96bc0d661869316f5e4a577a9f7c179593987beb4fb2ee424dbb2f5dd891e228b46c4a0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "g1 point is not on correct subgroup", + "Name": "bls_g1mul_g1_not_in_correct_subgroup" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-mul_G2_bls.json b/BEPs/assets/bep-439/fail-mul_G2_bls.json new file mode 100644 index 000000000..5b4fa8a1f --- /dev/null +++ b/BEPs/assets/bep-439/fail-mul_G2_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g2mul_empty_input" + }, + { + "Input": "000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g2mul_short_input" + }, + { + "Input": "0000000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g2mul_large_input" + }, + { + "Input": "000000000000000000000000000000001c4bb49d2a0ef12b7123acdd7110bd292b5bc659edc54dc21b81de057194c79b2a5803255959bbef8e7f56c8c12168630000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g2mul_invalid_field_element" + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb800000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g2mul_point_not_on_curve" + }, + { + "Input": "10000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g2mul_violate_top_bytes" + }, + { + "Input": "00000000000000000000000000000000197bfd0342bbc8bee2beced2f173e1a87be576379b343e93232d6cef98d84b1d696e5612ff283ce2cfdccb2cfb65fa0c00000000000000000000000000000000184e811f55e6f9d84d77d2f79102fd7ea7422f4759df5bf7f6331d550245e3f1bcf6a30e3b29110d85e0ca16f9f6ae7a000000000000000000000000000000000f10e1eb3c1e53d2ad9cf2d398b2dc22c5842fab0a74b174f691a7e914975da3564d835cd7d2982815b8ac57f507348f000000000000000000000000000000000767d1c453890f1b9110fda82f5815c27281aba3f026ee868e4176a0654feea41a96575e0c4d58a14dbfbcc05b5010b10000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "g2 point is not on correct subgroup", + "Name": "bls_g2mul_g2_not_in_correct_subgroup" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-multiexp_G1_bls.json b/BEPs/assets/bep-439/fail-multiexp_G1_bls.json new file mode 100644 index 000000000..976f28c48 --- /dev/null +++ b/BEPs/assets/bep-439/fail-multiexp_G1_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g1multiexp_empty_input" + }, + { + "Input": "00000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g1multiexp_short_input" + }, + { + "Input": "000000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g1multiexp_long_input" + }, + { + "Input": "0000000000000000000000000000000031f2e5916b17be2e71b10b4292f558e727dfd7d48af9cbc5087f0ce00dcca27c8b01e83eaace1aefb539f00adb2271660000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g1multiexp_invalid_field_element" + }, + { + "Input": "1000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g1multiexp_violate_top_bytes" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g1multiexp_point_not_on_curve" + }, + { + "Input": "000000000000000000000000000000000123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00000000000000000000000000000000193fb7cedb32b2c3adc06ec11a96bc0d661869316f5e4a577a9f7c179593987beb4fb2ee424dbb2f5dd891e228b46c4a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "g1 point is not on correct subgroup", + "Name": "bls_g1multiexp_g1_not_in_correct_subgroup" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-multiexp_G2_bls.json b/BEPs/assets/bep-439/fail-multiexp_G2_bls.json new file mode 100644 index 000000000..486138985 --- /dev/null +++ b/BEPs/assets/bep-439/fail-multiexp_G2_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_g2multiexp_empty_input" + }, + { + "Input": "000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g2multiexp_short_input" + }, + { + "Input": "0000000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid input length", + "Name": "bls_g2multiexp_long_input" + }, + { + "Input": "10000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_g2multiexp_violate_top_bytes" + }, + { + "Input": "000000000000000000000000000000001c4bb49d2a0ef12b7123acdd7110bd292b5bc659edc54dc21b81de057194c79b2a5803255959bbef8e7f56c8c12168630000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_g2multiexp_invalid_field_element" + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb800000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_g2multiexp_point_not_on_curve" + }, + { + "Input": "00000000000000000000000000000000197bfd0342bbc8bee2beced2f173e1a87be576379b343e93232d6cef98d84b1d696e5612ff283ce2cfdccb2cfb65fa0c00000000000000000000000000000000184e811f55e6f9d84d77d2f79102fd7ea7422f4759df5bf7f6331d550245e3f1bcf6a30e3b29110d85e0ca16f9f6ae7a000000000000000000000000000000000f10e1eb3c1e53d2ad9cf2d398b2dc22c5842fab0a74b174f691a7e914975da3564d835cd7d2982815b8ac57f507348f000000000000000000000000000000000767d1c453890f1b9110fda82f5815c27281aba3f026ee868e4176a0654feea41a96575e0c4d58a14dbfbcc05b5010b1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "ExpectedError": "g2 point is not on correct subgroup", + "Name": "bls_pairing_g2_not_in_correct_subgroup" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fail-pairing_check_bls.json b/BEPs/assets/bep-439/fail-pairing_check_bls.json new file mode 100644 index 000000000..e14cb8e64 --- /dev/null +++ b/BEPs/assets/bep-439/fail-pairing_check_bls.json @@ -0,0 +1,47 @@ +[ + { + "Input": "", + "ExpectedError": "invalid input length", + "Name": "bls_pairing_empty_input" + }, + { + "Input": "00000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid input length", + "Name": "bls_pairing_missing_data" + }, + { + "Input": "000000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid input length", + "Name": "bls_pairing_extra_data" + }, + { + "Input": "1000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid field element top bytes", + "Name": "bls_pairing_top_bytes" + }, + { + "Input": "0000000000000000000000000000000031f2e5916b17be2e71b10b4292f558e727dfd7d48af9cbc5087f0ce00dcca27c8b01e83eaace1aefb539f00adb2271660000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid fp.Element encoding", + "Name": "bls_pairing_invalid_field_element" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_pairing_g1_not_on_curve" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb800000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "invalid point: not on curve", + "Name": "bls_pairing_g2_not_on_curve" + }, + { + "Input": "000000000000000000000000000000000123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00000000000000000000000000000000193fb7cedb32b2c3adc06ec11a96bc0d661869316f5e4a577a9f7c179593987beb4fb2ee424dbb2f5dd891e228b46c4a00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "g1 point is not on correct subgroup", + "Name": "bls_pairing_g1_not_in_correct_subgroup" + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000197bfd0342bbc8bee2beced2f173e1a87be576379b343e93232d6cef98d84b1d696e5612ff283ce2cfdccb2cfb65fa0c00000000000000000000000000000000184e811f55e6f9d84d77d2f79102fd7ea7422f4759df5bf7f6331d550245e3f1bcf6a30e3b29110d85e0ca16f9f6ae7a000000000000000000000000000000000f10e1eb3c1e53d2ad9cf2d398b2dc22c5842fab0a74b174f691a7e914975da3564d835cd7d2982815b8ac57f507348f000000000000000000000000000000000767d1c453890f1b9110fda82f5815c27281aba3f026ee868e4176a0654feea41a96575e0c4d58a14dbfbcc05b5010b10000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "ExpectedError": "g2 point is not on correct subgroup", + "Name": "bls_pairing_g2_not_in_correct_subgroup" + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/fast_subgroup_checks.md b/BEPs/assets/bep-439/fast_subgroup_checks.md new file mode 100644 index 000000000..ede7ed84f --- /dev/null +++ b/BEPs/assets/bep-439/fast_subgroup_checks.md @@ -0,0 +1,51 @@ +# Fast subgroup checks used by BEP-439 + +### Fields and Groups + +Field Fp is defined as the finite field of size `p` with elements represented as integers between 0 and p-1 (both inclusive). + +Field Fp2 is defined as `Fp[X]/(X^2-nr2)` with elements `el = c0 + c1 * v`, where `v` is the formal square root of `nr2` represented as integer pairs `(c0,c1)`. + +Group G1 is defined as a set of Fp pairs (points) `(x,y)` such that either `(x,y)` is `(0,0)` or `x,y` satisfy the curve Fp equation. + +Group G2 is defined as a set of Fp2 pairs (points) `(x',y')` such that either `(x,y)` is `(0,0)` or `(x',y')` satisfy the curve Fp2 equation. + +## Curve parameters + +The set of parameters used by fast subgroup checks: + +``` +|x| (seed) = 15132376222941642752 +x is negative = true +Cube root of unity modulo p - Beta = 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350 +r = 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437 * v +s = 2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530 + 1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257 * v +``` + +## Helper function to compute the conjugate over Fp2 - `conjugate` + +`conjugate(c0 + c1 * v) := c0 - c1 * v` + +## G1 endomorphism - `phi` + +The endomorphism `phi` transform the point from `(x,y)` to `(Beta*x,y)` where `Beta` is a precomputed cube root of unity modulo `p` given above in parameters sections: + +`phi((x,y)) := (Beta*x,y)` + +## G2 endomorphism - `psi` + +`psi((x,y)) := (conjugate(x)*r,conjugate(y)*s)` + +# The G1 case + +Before accepting a point `P` as input that purports to be a member of G1 subject the input to the following endomorphism test: `phi(P) + x^2*P = 0` + + +# The G2 case + +Before accepting a point `P` as input that purports to be a member of G2 subject the input to the following endomorphism test: `psi(P) + x*P = 0` + +# Resources + +* https://eprint.iacr.org/2021/1130.pdf, sec.4 +* https://eprint.iacr.org/2022/352.pdf, sec. 4.2 diff --git a/BEPs/assets/bep-439/field_to_curve.md b/BEPs/assets/bep-439/field_to_curve.md new file mode 100644 index 000000000..4ba27eacd --- /dev/null +++ b/BEPs/assets/bep-439/field_to_curve.md @@ -0,0 +1,245 @@ +# Field element to curve point mapping used by BEP-439 + +For a BLS12-381 implemented by BEP-439 a short Weierstrass curve equation y^2 = x^3 + A * x + B has a property that a product AB = 0, so to implement a mapping function two step algorithms is performed: +- Field element is mapped to a some other curve with AB != 0 +- Isogeny is applied to one to one map a point of this other curve to a point on BLS12-381 +- Cofactor is cleared for a point now on BLS12-381 + +Below we describe generic algorithms for mapping and isogeny application, and later on give concrete parameters for the algorithms + +## Helper function to clear a cofactor + +Later on we use a helper function to clear a cofactor of the curve point. It's implemented as + +~~~ + clear_cofactor(P) := h_eff * P +~~~ + +where values of h_eff are given below in parameters sections + +## Simplified SWU for AB != 0 + +The function map\_to\_curve\_simple\_swu(u) implements a simplification +of the Shallue-van de Woestijne-Ulas mapping described by Brier et +al., which they call the "simplified SWU" map. Wahby and Boneh generalize and optimize this mapping. + +Preconditions: A Weierstrass curve y^2 = g(x) x^3 + A * x + B where A != 0 and B != 0. + +Constants: + +- A and B, the parameters of the Weierstrass curve. + +- Z, an element of F meeting the below criteria. + The criteria are: + 1. Z is non-square in F, + 2. Z != -1 in F, + 3. the polynomial g(x) - Z is irreducible over F, and + 4. g(B / (Z * A)) is square in F. + +Sign of y: Inputs u and -u give the same x-coordinate. +Thus, we set sgn0(y) == sgn0(u). + +Exceptions: The exceptional cases are values of u such that +Z^2 * u^4 + Z * u^2 == 0. This includes u == 0, and may include +other values depending on Z. Implementations must detect +this case and set x1 = B / (Z * A), which guarantees that g(x1) +is square by the condition on Z given above. + +Operations: + +~~~ +1. tv1 = inv0(Z^2 * u^4 + Z * u^2) +2. x1 = (-B / A) * (1 + tv1) +3. If tv1 == 0, set x1 = B / (Z * A) +4. gx1 = x1^3 + A * x1 + B +5. x2 = Z * u^2 * x1 +6. gx2 = x2^3 + A * x2 + B +7. If is_square(gx1), set x = x1 and y = sqrt(gx1) +8. Else set x = x2 and y = sqrt(gx2) +9. If sgn0(u) != sgn0(y), set y = -y +10. return (x, y) +~~~ + +## Simplified SWU for AB == 0 + +Wahby and Boneh show how to adapt the simplified SWU mapping to +Weierstrass curves having A == 0 or B == 0, which the mapping of +simple SWU does not support. + +This method requires finding another elliptic curve E' given by the equation + +~~~ + y'^2 = g'(x') = x'^3 + A' * x' + B' +~~~ + +that is isogenous to E and has A' != 0 and B' != 0. +This isogeny defines a map iso\_map(x', y') given by a pair of rational functions. +iso\_map takes as input a point on E' and produces as output a point on E. + +Once E' and iso\_map are identified, this mapping works as follows: on input +u, first apply the simplified SWU mapping to get a point on E', then apply +the isogeny map to that point to get a point on E. + +Note that iso\_map is a group homomorphism, meaning that point addition +commutes with iso\_map. +Thus, when using this mapping in the hash\_to\_curve construction of {{roadmap}}, +one can effect a small optimization by first mapping u0 and u1 to E', adding +the resulting points on E', and then applying iso\_map to the sum. +This gives the same result while requiring only one evaluation of iso\_map. + +Preconditions: An elliptic curve E' with A' != 0 and B' != 0 that is +isogenous to the target curve E with isogeny map iso\_map from +E' to E. + +So the full mapping algorithm looks as: + +- map\_to\_curve\_simple\_swu is the simple SWU mapping to E' +- iso\_map is the isogeny map from E' to E + +Sign of y: for this map, the sign is determined by map\_to\_curve\_simple\_swu. +No further sign adjustments are necessary. + +Exceptions: map\_to\_curve\_simple\_swu handles its exceptional cases. +Exceptional cases of iso\_map are inputs that cause the denominator of +either rational function to evaluate to zero; such cases MUST return the +identity point on E. + +## Full algorithm restated + +~~~ +1. (x', y') = map_to_curve_simple_swu(u) # (x', y') is on E' +2. (x, y) = iso_map(x', y') # (x, y) is on E +3. (x, y) = clear_cofactor((x, y)) # clears cofactor for point (x, y) on E +4. return (x, y) +~~~ + +## Parameters for BEP-439 + +### Fp-to-G1 mapping + + +- Z: 11 +- E': y'^2 = x'^3 + A' * x' + B', where + - A' = 0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d + - B' = 0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0 +- h\_eff: 0xd201000000010001 + +The 11-isogeny map from (x', y') on E' to (x, y) on E is given by the following rational functions: + +- x = x\_num / x\_den, where + - x\_num = k\_(1,11) * x'^11 + k\_(1,10) * x'^10 + k\_(1,9) * x'^9 + ... + k\_(1,0) + - x\_den = x'^10 + k\_(2,9) * x'^9 + k\_(2,8) * x'^8 + ... + k\_(2,0) + +- y = y' * y\_num / y\_den, where + - y\_num = k\_(3,15) * x'^15 + k\_(3,14) * x'^14 + k\_(3,13) * x'^13 + ... + k\_(3,0) + - y\_den = x'^15 + k\_(4,14) * x'^14 + k\_(4,13) * x'^13 + ... + k\_(4,0) + +The constants used to compute x\_num are as follows: + +- k\_(1,0) = 0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7 +- k\_(1,1) = 0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb +- k\_(1,2) = 0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0 +- k\_(1,3) = 0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861 +- k\_(1,4) = 0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9 +- k\_(1,5) = 0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983 +- k\_(1,6) = 0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84 +- k\_(1,7) = 0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e +- k\_(1,8) = 0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317 +- k\_(1,9) = 0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e +- k\_(1,10) = 0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b +- k\_(1,11) = 0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229 + +The constants used to compute x\_den are as follows: + +- k\_(2,0) = 0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c +- k\_(2,1) = 0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff +- k\_(2,2) = 0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19 +- k\_(2,3) = 0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8 +- k\_(2,4) = 0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e +- k\_(2,5) = 0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5 +- k\_(2,6) = 0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a +- k\_(2,7) = 0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e +- k\_(2,8) = 0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641 +- k\_(2,9) = 0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a + +The constants used to compute y\_num are as follows: + +- k\_(3,0) = 0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33 +- k\_(3,1) = 0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696 +- k\_(3,2) = 0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6 +- k\_(3,3) = 0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb +- k\_(3,4) = 0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb +- k\_(3,5) = 0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0 +- k\_(3,6) = 0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2 +- k\_(3,7) = 0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29 +- k\_(3,8) = 0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587 +- k\_(3,9) = 0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30 +- k\_(3,10) = 0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132 +- k\_(3,11) = 0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e +- k\_(3,12) = 0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8 +- k\_(3,13) = 0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133 +- k\_(3,14) = 0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b +- k\_(3,15) = 0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604 + +The constants used to compute y\_den are as follows: + +- k\_(4,0) = 0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1 +- k\_(4,1) = 0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d +- k\_(4,2) = 0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2 +- k\_(4,3) = 0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416 +- k\_(4,4) = 0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d +- k\_(4,5) = 0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac +- k\_(4,6) = 0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c +- k\_(4,7) = 0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9 +- k\_(4,8) = 0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a +- k\_(4,9) = 0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55 +- k\_(4,10) = 0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8 +- k\_(4,11) = 0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092 +- k\_(4,12) = 0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc +- k\_(4,13) = 0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7 +- k\_(4,14) = 0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f + +### Fp2-to-G2 mapping + +Symbol `I` means a non-residue used to make an extension field Fp2 + +- Z: -(2 + I) +- E': y'^2 = x'^3 + A' * x' + B', where + - A' = 240 * I + - B' = 1012 * (1 + I) +- h\_eff: 0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551 + +The 3-isogeny map from (x', y') on E' to (x, y) on E is given by the following rational functions: + +- x = x\_num / x\_den, where + - x\_num = k\_(1,3) * x'^3 + k\_(1,2) * x'^2 + k\_(1,1) * x' + k\_(1,0) + - x\_den = x'^2 + k\_(2,1) * x' + k\_(2,0) + +- y = y' * y\_num / y\_den, where + - y\_num = k\_(3,3) * x'^3 + k\_(3,2) * x'^2 + k\_(3,1) * x' + k\_(3,0) + - y\_den = x'^3 + k\_(4,2) * x'^2 + k\_(4,1) * x' + k\_(4,0) + +The constants used to compute x\_num are as follows: + +- k\_(1,0) = 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6 + 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6 * I +- k\_(1,1) = 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a * I +- k\_(1,2) = 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e + 0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d * I +- k\_(1,3) = 0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1 + +The constants used to compute x\_den are as follows: + +- k\_(2,0) = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63 * I +- k\_(2,1) = 0xc + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f * I + +The constants used to compute y\_num are as follows: + +- k\_(3,0) = 0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706 + 0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706 * I +- k\_(3,1) = 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be * I +- k\_(3,2) = 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c + 0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f * I +- k\_(3,3) = 0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10 + +The constants used to compute y\_den are as follows: + +- k\_(4,0) = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb * I +- k\_(4,1) = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3 * I +- k\_(4,2) = 0x12 + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99 * I \ No newline at end of file diff --git a/BEPs/assets/bep-439/map_fp2_to_G2_bls.json b/BEPs/assets/bep-439/map_fp2_to_G2_bls.json new file mode 100644 index 000000000..fa96b288d --- /dev/null +++ b/BEPs/assets/bep-439/map_fp2_to_G2_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "0000000000000000000000000000000007355d25caf6e7f2f0cb2812ca0e513bd026ed09dda65b177500fa31714e09ea0ded3a078b526bed3307f804d4b93b040000000000000000000000000000000002829ce3c021339ccb5caf3e187f6370e1e2a311dec9b75363117063ab2015603ff52c3d3b98f19c2f65575e99e8b78c", + "Name": "bls_g2map_", + "Expected": "0000000000000000000000000000000000e7f4568a82b4b7dc1f14c6aaa055edf51502319c723c4dc2688c7fe5944c213f510328082396515734b6612c4e7bb700000000000000000000000000000000126b855e9e69b1f691f816e48ac6977664d24d99f8724868a184186469ddfd4617367e94527d4b74fc86413483afb35b000000000000000000000000000000000caead0fd7b6176c01436833c79d305c78be307da5f6af6c133c47311def6ff1e0babf57a0fb5539fce7ee12407b0a42000000000000000000000000000000001498aadcf7ae2b345243e281ae076df6de84455d766ab6fcdaad71fab60abb2e8b980a440043cd305db09d283c895e3d", + "Gas": 75000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000138879a9559e24cecee8697b8b4ad32cced053138ab913b99872772dc753a2967ed50aabc907937aefb2439ba06cc50c000000000000000000000000000000000a1ae7999ea9bab1dcc9ef8887a6cb6e8f1e22566015428d220b7eec90ffa70ad1f624018a9ad11e78d588bd3617f9f2", + "Name": "bls_g2map_616263", + "Expected": "00000000000000000000000000000000108ed59fd9fae381abfd1d6bce2fd2fa220990f0f837fa30e0f27914ed6e1454db0d1ee957b219f61da6ff8be0d6441f000000000000000000000000000000000296238ea82c6d4adb3c838ee3cb2346049c90b96d602d7bb1b469b905c9228be25c627bffee872def773d5b2a2eb57d00000000000000000000000000000000033f90f6057aadacae7963b0a0b379dd46750c1c94a6357c99b65f63b79e321ff50fe3053330911c56b6ceea08fee65600000000000000000000000000000000153606c417e59fb331b7ae6bce4fbf7c5190c33ce9402b5ebe2b70e44fca614f3f1382a3625ed5493843d0b0a652fc3f", + "Gas": 75000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000018c16fe362b7dbdfa102e42bdfd3e2f4e6191d479437a59db4eb716986bf08ee1f42634db66bde97d6c16bbfd342b3b8000000000000000000000000000000000e37812ce1b146d998d5f92bdd5ada2a31bfd63dfe18311aa91637b5f279dd045763166aa1615e46a50d8d8f475f184e", + "Name": "bls_g2map_6162636465663031", + "Expected": "00000000000000000000000000000000038af300ef34c7759a6caaa4e69363cafeed218a1f207e93b2c70d91a1263d375d6730bd6b6509dcac3ba5b567e85bf3000000000000000000000000000000000da75be60fb6aa0e9e3143e40c42796edf15685cafe0279afd2a67c3dff1c82341f17effd402e4f1af240ea90f4b659b0000000000000000000000000000000019b148cbdf163cf0894f29660d2e7bfb2b68e37d54cc83fd4e6e62c020eaa48709302ef8e746736c0e19342cc1ce3df4000000000000000000000000000000000492f4fed741b073e5a82580f7c663f9b79e036b70ab3e51162359cec4e77c78086fe879b65ca7a47d34374c8315ac5e", + "Gas": 75000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000008d4a0997b9d52fecf99427abb721f0fa779479963315fe21c6445250de7183e3f63bfdf86570da8929489e421d4ee950000000000000000000000000000000016cb4ccad91ec95aab070f22043916cd6a59c4ca94097f7f510043d48515526dc8eaaea27e586f09151ae613688d5a89", + "Name": "bls_g2map_713132385f717171", + "Expected": "000000000000000000000000000000000c5ae723be00e6c3f0efe184fdc0702b64588fe77dda152ab13099a3bacd3876767fa7bbad6d6fd90b3642e902b208f90000000000000000000000000000000012c8c05c1d5fc7bfa847f4d7d81e294e66b9a78bc9953990c358945e1f042eedafce608b67fdd3ab0cb2e6e263b9b1ad0000000000000000000000000000000004e77ddb3ede41b5ec4396b7421dd916efc68a358a0d7425bddd253547f2fb4830522358491827265dfc5bcc1928a5690000000000000000000000000000000011c624c56dbe154d759d021eec60fab3d8b852395a89de497e48504366feedd4662d023af447d66926a28076813dd646", + "Gas": 75000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000003f80ce4ff0ca2f576d797a3660e3f65b274285c054feccc3215c879e2c0589d376e83ede13f93c32f05da0f68fd6a1000000000000000000000000000000000006488a837c5413746d868d1efb7232724da10eca410b07d8b505b9363bdccf0a1fc0029bad07d65b15ccfe6dd25e20d", + "Name": "bls_g2map_613531325f616161", + "Expected": "000000000000000000000000000000000ea4e7c33d43e17cc516a72f76437c4bf81d8f4eac69ac355d3bf9b71b8138d55dc10fd458be115afa798b55dac34be1000000000000000000000000000000001565c2f625032d232f13121d3cfb476f45275c303a037faa255f9da62000c2c864ea881e2bcddd111edc4a3c0da3e88d00000000000000000000000000000000043b6f5fe4e52c839148dc66f2b3751e69a0f6ebb3d056d6465d50d4108543ecd956e10fa1640dfd9bc0030cc2558d28000000000000000000000000000000000f8991d2a1ad662e7b6f58ab787947f1fa607fce12dde171bc17903b012091b657e15333e11701edcf5b63ba2a561247", + "Gas": 75000, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/map_fp_to_G1_bls.json b/BEPs/assets/bep-439/map_fp_to_G1_bls.json new file mode 100644 index 000000000..80ca454d8 --- /dev/null +++ b/BEPs/assets/bep-439/map_fp_to_G1_bls.json @@ -0,0 +1,37 @@ +[ + { + "Input": "00000000000000000000000000000000156c8a6a2c184569d69a76be144b5cdc5141d2d2ca4fe341f011e25e3969c55ad9e9b9ce2eb833c81a908e5fa4ac5f03", + "Name": "bls_g1map_", + "Expected": "00000000000000000000000000000000184bb665c37ff561a89ec2122dd343f20e0f4cbcaec84e3c3052ea81d1834e192c426074b02ed3dca4e7676ce4ce48ba0000000000000000000000000000000004407b8d35af4dacc809927071fc0405218f1401a6d15af775810e4e460064bcc9468beeba82fdc751be70476c888bf3", + "Gas": 5500, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000147e1ed29f06e4c5079b9d14fc89d2820d32419b990c1c7bb7dbea2a36a045124b31ffbde7c99329c05c559af1c6cc82", + "Name": "bls_g1map_616263", + "Expected": "00000000000000000000000000000000009769f3ab59bfd551d53a5f846b9984c59b97d6842b20a2c565baa167945e3d026a3755b6345df8ec7e6acb6868ae6d000000000000000000000000000000001532c00cf61aa3d0ce3e5aa20c3b531a2abd2c770a790a2613818303c6b830ffc0ecf6c357af3317b9575c567f11cd2c", + "Gas": 5500, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000004090815ad598a06897dd89bcda860f25837d54e897298ce31e6947378134d3761dc59a572154963e8c954919ecfa82d", + "Name": "bls_g1map_6162636465663031", + "Expected": "000000000000000000000000000000001974dbb8e6b5d20b84df7e625e2fbfecb2cdb5f77d5eae5fb2955e5ce7313cae8364bc2fff520a6c25619739c6bdcb6a0000000000000000000000000000000015f9897e11c6441eaa676de141c8d83c37aab8667173cbe1dfd6de74d11861b961dccebcd9d289ac633455dfcc7013a3", + "Gas": 5500, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000008dccd088ca55b8bfbc96fb50bb25c592faa867a8bb78d4e94a8cc2c92306190244532e91feba2b7fed977e3c3bb5a1f", + "Name": "bls_g1map_713132385f717171", + "Expected": "000000000000000000000000000000000a7a047c4a8397b3446450642c2ac64d7239b61872c9ae7a59707a8f4f950f101e766afe58223b3bff3a19a7f754027c000000000000000000000000000000001383aebba1e4327ccff7cf9912bda0dbc77de048b71ef8c8a81111d71dc33c5e3aa6edee9cf6f5fe525d50cc50b77cc9", + "Gas": 5500, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000dd824886d2123a96447f6c56e3a3fa992fbfefdba17b6673f9f630ff19e4d326529db37e1c1be43f905bf9202e0278d", + "Name": "bls_g1map_613531325f616161", + "Expected": "000000000000000000000000000000000e7a16a975904f131682edbb03d9560d3e48214c9986bd50417a77108d13dc957500edf96462a3d01e62dc6cd468ef11000000000000000000000000000000000ae89e677711d05c30a48d6d75e76ca9fb70fe06c6dd6ff988683d89ccde29ac7d46c53bb97a59b1901abf1db66052db", + "Gas": 5500, + "NoBenchmark": false + } +] \ No newline at end of file diff --git a/BEPs/assets/bep-439/mul_G1_bls.json b/BEPs/assets/bep-439/mul_G1_bls.json new file mode 100644 index 000000000..e67f76f98 --- /dev/null +++ b/BEPs/assets/bep-439/mul_G1_bls.json @@ -0,0 +1,79 @@ +[ + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g1mul_(g1+g1=2*g1)", + "Expected": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d28", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g1mul_(p1+p1=2*p1)", + "Expected": "0000000000000000000000000000000015222cddbabdd764c4bee0b3720322a65ff4712c86fc4b1588d0c209210a0884fa9468e855d261c483091b2bf7de6a630000000000000000000000000000000009f9edb99bc3b75d7489735c98b16ab78b9386c5f7a1f76c7e96ac6eb5bbde30dbca31a74ec6e0f0b12229eecea33c39", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g1mul_(1*g1=g1)", + "Expected": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g1mul_(1*p1=p1)", + "Expected": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1mul_(0*g1=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1mul_(0*p1=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011", + "Name": "bls_g1mul_(x*inf=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e3", + "Name": "bls_g1mul_random*g1", + "Expected": "000000000000000000000000000000000491d1b0ecd9bb917989f0e74f0dea0422eac4a873e5e2644f368dffb9a6e20fd6e10c1b77654d067c0618f6e5a7f79a0000000000000000000000000000000017cd7061575d3e8034fcea62adaa1a3bc38dca4b50e4c5c01d04dd78037c9cee914e17944ea99e7ad84278e5d49f36c4", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e3", + "Name": "bls_g1mul_random*p1", + "Expected": "0000000000000000000000000000000006ee9c9331228753bcb148d0ca8623447701bb0aa6eafb0340aa7f81543923474e00f2a225de65c62dd1d8303270220c0000000000000000000000000000000018dd7be47eb4e80985d7a0d2cc96c8b004250b36a5c3ec0217705d453d3ecc6d0d3d1588722da51b40728baba1e93804", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e19a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g1mul_random*g1_unnormalized_scalar", + "Expected": "000000000000000000000000000000000491d1b0ecd9bb917989f0e74f0dea0422eac4a873e5e2644f368dffb9a6e20fd6e10c1b77654d067c0618f6e5a7f79a0000000000000000000000000000000017cd7061575d3e8034fcea62adaa1a3bc38dca4b50e4c5c01d04dd78037c9cee914e17944ea99e7ad84278e5d49f36c4", + "Gas": 12000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a219a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g1mul_random*p1_unnormalized_scalar", + "Expected": "0000000000000000000000000000000006ee9c9331228753bcb148d0ca8623447701bb0aa6eafb0340aa7f81543923474e00f2a225de65c62dd1d8303270220c0000000000000000000000000000000018dd7be47eb4e80985d7a0d2cc96c8b004250b36a5c3ec0217705d453d3ecc6d0d3d1588722da51b40728baba1e93804", + "Gas": 12000, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/mul_G2_bls.json b/BEPs/assets/bep-439/mul_G2_bls.json new file mode 100644 index 000000000..1d41f3da5 --- /dev/null +++ b/BEPs/assets/bep-439/mul_G2_bls.json @@ -0,0 +1,79 @@ +[ + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2mul_(g2+g2=2*g2)", + "Expected": "000000000000000000000000000000001638533957d540a9d2370f17cc7ed5863bc0b995b8825e0ee1ea1e1e4d00dbae81f14b0bf3611b78c952aacab827a053000000000000000000000000000000000a4edef9c1ed7f729f520e47730a124fd70662a904ba1074728114d1031e1572c6c886f6b57ec72a6178288c47c33577000000000000000000000000000000000468fb440d82b0630aeb8dca2b5256789a66da69bf91009cbfe6bd221e47aa8ae88dece9764bf3bd999d95d71e4c9899000000000000000000000000000000000f6d4552fa65dd2638b361543f887136a43253d9c66c411697003f7a13c308f5422e1aa0a59c8967acdefd8b6e36ccf3", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2mul_(p2+p2=2*p2)", + "Expected": "000000000000000000000000000000000b76fcbb604082a4f2d19858a7befd6053fa181c5119a612dfec83832537f644e02454f2b70d40985ebb08042d1620d40000000000000000000000000000000019a4a02c0ae51365d964c73be7babb719db1c69e0ddbf9a8a335b5bed3b0a4b070d2d5df01d2da4a3f1e56aae2ec106d000000000000000000000000000000000d18322f821ac72d3ca92f92b000483cf5b7d9e5d06873a44071c4e7e81efd904f210208fe0b9b4824f01c65bc7e62080000000000000000000000000000000004e563d53609a2d1e216aaaee5fbc14ef460160db8d1fdc5e1bd4e8b54cd2f39abf6f925969fa405efb9e700b01c7085", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g2mul_(1*g2=g2)", + "Expected": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g2mul_(1*p2=p2)", + "Expected": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2mul_(0*g2=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2mul_(0*p2=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011", + "Name": "bls_g2mul_(x*inf=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e3", + "Name": "bls_g2mul_random*g2", + "Expected": "0000000000000000000000000000000014856c22d8cdb2967c720e963eedc999e738373b14172f06fc915769d3cc5ab7ae0a1b9c38f48b5585fb09d4bd2733bb000000000000000000000000000000000c400b70f6f8cd35648f5c126cce5417f3be4d8eefbd42ceb4286a14df7e03135313fe5845e3a575faab3e8b949d248800000000000000000000000000000000149a0aacc34beba2beb2f2a19a440166e76e373194714f108e4ab1c3fd331e80f4e73e6b9ea65fe3ec96d7136de81544000000000000000000000000000000000e4622fef26bdb9b1e8ef6591a7cc99f5b73164500c1ee224b6a761e676b8799b09a3fd4fa7e242645cc1a34708285e4", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e3", + "Name": "bls_g2mul_random*p2", + "Expected": "00000000000000000000000000000000036074dcbbd0e987531bfe0e45ddfbe09fd015665990ee0c352e8e403fe6af971d8f42141970d9ab14b4dd04874409e600000000000000000000000000000000019705637f24ba2f398f32c3a3e20d6a1cd0fd63e6f8f071cf603a8334f255744927e7bfdfdb18519e019c49ff6e914500000000000000000000000000000000008e74fcff4c4278c9accfb60809ed69bbcbe3d6213ef2304e078d15ec7d6decb4f462b24b8e7cc38cc11b6f2c9e0486000000000000000000000000000000001331d40100f38c1070afd832445881b47cf4d63894666d9907c85ac66604aab5ad329980938cc3c167ccc5b6bc1b8f30", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be9a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g2mul_random*g2_unnormalized_scalar", + "Expected": "0000000000000000000000000000000014856c22d8cdb2967c720e963eedc999e738373b14172f06fc915769d3cc5ab7ae0a1b9c38f48b5585fb09d4bd2733bb000000000000000000000000000000000c400b70f6f8cd35648f5c126cce5417f3be4d8eefbd42ceb4286a14df7e03135313fe5845e3a575faab3e8b949d248800000000000000000000000000000000149a0aacc34beba2beb2f2a19a440166e76e373194714f108e4ab1c3fd331e80f4e73e6b9ea65fe3ec96d7136de81544000000000000000000000000000000000e4622fef26bdb9b1e8ef6591a7cc99f5b73164500c1ee224b6a761e676b8799b09a3fd4fa7e242645cc1a34708285e4", + "Gas": 45000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784519a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g2mul_random*p2_unnormalized_scalar", + "Expected": "00000000000000000000000000000000036074dcbbd0e987531bfe0e45ddfbe09fd015665990ee0c352e8e403fe6af971d8f42141970d9ab14b4dd04874409e600000000000000000000000000000000019705637f24ba2f398f32c3a3e20d6a1cd0fd63e6f8f071cf603a8334f255744927e7bfdfdb18519e019c49ff6e914500000000000000000000000000000000008e74fcff4c4278c9accfb60809ed69bbcbe3d6213ef2304e078d15ec7d6decb4f462b24b8e7cc38cc11b6f2c9e0486000000000000000000000000000000001331d40100f38c1070afd832445881b47cf4d63894666d9907c85ac66604aab5ad329980938cc3c167ccc5b6bc1b8f30", + "Gas": 45000, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/multiexp_G1_bls.json b/BEPs/assets/bep-439/multiexp_G1_bls.json new file mode 100644 index 000000000..536f0b91f --- /dev/null +++ b/BEPs/assets/bep-439/multiexp_G1_bls.json @@ -0,0 +1,93 @@ +[ + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g1multiexp_(g1+g1=2*g1)", + "Expected": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d28", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g1multiexp_(p1+p1=2*p1)", + "Expected": "0000000000000000000000000000000015222cddbabdd764c4bee0b3720322a65ff4712c86fc4b1588d0c209210a0884fa9468e855d261c483091b2bf7de6a630000000000000000000000000000000009f9edb99bc3b75d7489735c98b16ab78b9386c5f7a1f76c7e96ac6eb5bbde30dbca31a74ec6e0f0b12229eecea33c39", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g1multiexp_(1*g1=g1)", + "Expected": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g1multiexp_(1*p1=p1)", + "Expected": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a21", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1multiexp_(0*g1=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1multiexp_(0*p1=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011", + "Name": "bls_g1multiexp_(x*inf=inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1multiexp_(2g1+inf)", + "Expected": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d28", + "Gas": 21312, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1multiexp_(inf+inf)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 21312, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a210000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g1multiexp_(2g1+2p1)", + "Expected": "00000000000000000000000000000000148f92dced907361b4782ab542a75281d4b6f71f65c8abf94a5a9082388c64662d30fd6a01ced724feef3e284752038c0000000000000000000000000000000015c3634c3b67bc18e19150e12bfd8a1769306ed010f59be645a0823acb5b38f39e8e0d86e59b6353fdafc59ca971b769", + "Gas": 21312, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e300000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2147b8192d77bf871b62e87859d653922725724a5c031afeabc60bcef5ff66513800000000000000000000000000000000184bb665c37ff561a89ec2122dd343f20e0f4cbcaec84e3c3052ea81d1834e192c426074b02ed3dca4e7676ce4ce48ba0000000000000000000000000000000004407b8d35af4dacc809927071fc0405218f1401a6d15af775810e4e460064bcc9468beeba82fdc751be70476c888bf3328388aff0d4a5b7dc9205abd374e7e98f3cd9f3418edb4eafda5fb16473d21600000000000000000000000000000000009769f3ab59bfd551d53a5f846b9984c59b97d6842b20a2c565baa167945e3d026a3755b6345df8ec7e6acb6868ae6d000000000000000000000000000000001532c00cf61aa3d0ce3e5aa20c3b531a2abd2c770a790a2613818303c6b830ffc0ecf6c357af3317b9575c567f11cd2c263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e2000000000000000000000000000000001974dbb8e6b5d20b84df7e625e2fbfecb2cdb5f77d5eae5fb2955e5ce7313cae8364bc2fff520a6c25619739c6bdcb6a0000000000000000000000000000000015f9897e11c6441eaa676de141c8d83c37aab8667173cbe1dfd6de74d11861b961dccebcd9d289ac633455dfcc7013a347b8192d77bf871b62e87859d653922725724a5c031afeabc60bcef5ff665131000000000000000000000000000000000a7a047c4a8397b3446450642c2ac64d7239b61872c9ae7a59707a8f4f950f101e766afe58223b3bff3a19a7f754027c000000000000000000000000000000001383aebba1e4327ccff7cf9912bda0dbc77de048b71ef8c8a81111d71dc33c5e3aa6edee9cf6f5fe525d50cc50b77cc9328388aff0d4a5b7dc9205abd374e7e98f3cd9f3418edb4eafda5fb16473d211000000000000000000000000000000000e7a16a975904f131682edbb03d9560d3e48214c9986bd50417a77108d13dc957500edf96462a3d01e62dc6cd468ef11000000000000000000000000000000000ae89e677711d05c30a48d6d75e76ca9fb70fe06c6dd6ff988683d89ccde29ac7d46c53bb97a59b1901abf1db66052db55b53c4669f19f0fc7431929bc0363d7d8fb432435fcde2635fdba334424e9f5", + "Name": "bls_g1multiexp_multiple", + "Expected": "00000000000000000000000000000000053fbdb09b6b5faa08bfe7b7069454247ad4d8bd57e90e2d2ebaa04003dcf110aa83072c07f480ab2107cca2ccff6091000000000000000000000000000000001654537b7c96fe64d13906066679c3d45808cb666452b55d1b909c230cc4b423c3f932c58754b9b762dc49fcc825522c", + "Gas": 42000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e19a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g1multiexp_random*g1_unnormalized_scalar", + "Expected": "000000000000000000000000000000000491d1b0ecd9bb917989f0e74f0dea0422eac4a873e5e2644f368dffb9a6e20fd6e10c1b77654d067c0618f6e5a7f79a0000000000000000000000000000000017cd7061575d3e8034fcea62adaa1a3bc38dca4b50e4c5c01d04dd78037c9cee914e17944ea99e7ad84278e5d49f36c4", + "Gas": 14400, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a219a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g1multiexp_random*p1_unnormalized_scalar", + "Expected": "0000000000000000000000000000000006ee9c9331228753bcb148d0ca8623447701bb0aa6eafb0340aa7f81543923474e00f2a225de65c62dd1d8303270220c0000000000000000000000000000000018dd7be47eb4e80985d7a0d2cc96c8b004250b36a5c3ec0217705d453d3ecc6d0d3d1588722da51b40728baba1e93804", + "Gas": 14400, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/multiexp_G2_bls.json b/BEPs/assets/bep-439/multiexp_G2_bls.json new file mode 100644 index 000000000..bd16a8a89 --- /dev/null +++ b/BEPs/assets/bep-439/multiexp_G2_bls.json @@ -0,0 +1,100 @@ +[ + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2multiexp_(g2+g2=2*g2)", + "Expected": "000000000000000000000000000000001638533957d540a9d2370f17cc7ed5863bc0b995b8825e0ee1ea1e1e4d00dbae81f14b0bf3611b78c952aacab827a053000000000000000000000000000000000a4edef9c1ed7f729f520e47730a124fd70662a904ba1074728114d1031e1572c6c886f6b57ec72a6178288c47c33577000000000000000000000000000000000468fb440d82b0630aeb8dca2b5256789a66da69bf91009cbfe6bd221e47aa8ae88dece9764bf3bd999d95d71e4c9899000000000000000000000000000000000f6d4552fa65dd2638b361543f887136a43253d9c66c411697003f7a13c308f5422e1aa0a59c8967acdefd8b6e36ccf3", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2multiexp_(p2+p2=2*p2)", + "Expected": "000000000000000000000000000000000b76fcbb604082a4f2d19858a7befd6053fa181c5119a612dfec83832537f644e02454f2b70d40985ebb08042d1620d40000000000000000000000000000000019a4a02c0ae51365d964c73be7babb719db1c69e0ddbf9a8a335b5bed3b0a4b070d2d5df01d2da4a3f1e56aae2ec106d000000000000000000000000000000000d18322f821ac72d3ca92f92b000483cf5b7d9e5d06873a44071c4e7e81efd904f210208fe0b9b4824f01c65bc7e62080000000000000000000000000000000004e563d53609a2d1e216aaaee5fbc14ef460160db8d1fdc5e1bd4e8b54cd2f39abf6f925969fa405efb9e700b01c7085", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g2multiexp_(1*g2=g2)", + "Expected": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000001", + "Name": "bls_g2multiexp_(1*p2=p2)", + "Expected": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2multiexp_(0*g2=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g2multiexp_(0*p2=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011", + "Name": "bls_g2multiexp_(x*inf=inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2multiexp_(2g2+inf)", + "Expected": "000000000000000000000000000000001638533957d540a9d2370f17cc7ed5863bc0b995b8825e0ee1ea1e1e4d00dbae81f14b0bf3611b78c952aacab827a053000000000000000000000000000000000a4edef9c1ed7f729f520e47730a124fd70662a904ba1074728114d1031e1572c6c886f6b57ec72a6178288c47c33577000000000000000000000000000000000468fb440d82b0630aeb8dca2b5256789a66da69bf91009cbfe6bd221e47aa8ae88dece9764bf3bd999d95d71e4c9899000000000000000000000000000000000f6d4552fa65dd2638b361543f887136a43253d9c66c411697003f7a13c308f5422e1aa0a59c8967acdefd8b6e36ccf3", + "Gas": 79920, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2multiexp_(2p2+inf)", + "Expected": "000000000000000000000000000000000b76fcbb604082a4f2d19858a7befd6053fa181c5119a612dfec83832537f644e02454f2b70d40985ebb08042d1620d40000000000000000000000000000000019a4a02c0ae51365d964c73be7babb719db1c69e0ddbf9a8a335b5bed3b0a4b070d2d5df01d2da4a3f1e56aae2ec106d000000000000000000000000000000000d18322f821ac72d3ca92f92b000483cf5b7d9e5d06873a44071c4e7e81efd904f210208fe0b9b4824f01c65bc7e62080000000000000000000000000000000004e563d53609a2d1e216aaaee5fbc14ef460160db8d1fdc5e1bd4e8b54cd2f39abf6f925969fa405efb9e700b01c7085", + "Gas": 79920, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d878451000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000000", + "Name": "bls_g1multiexp_(inf+inf)", + "Expected": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "Gas": 79920, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784510000000000000000000000000000000000000000000000000000000000000002", + "Name": "bls_g2multiexp_(2g2+2p2)", + "Expected": "00000000000000000000000000000000009cc9ed6635623ba19b340cbc1b0eb05c3a58770623986bb7e041645175b0a38d663d929afb9a949f7524656043bccc000000000000000000000000000000000c0fb19d3f083fd5641d22a861a11979da258003f888c59c33005cb4a2df4df9e5a2868832063ac289dfa3e997f21f8a00000000000000000000000000000000168bf7d87cef37cf1707849e0a6708cb856846f5392d205ae7418dd94d94ef6c8aa5b424af2e99d957567654b9dae1d90000000000000000000000000000000017e0fa3c3b2665d52c26c7d4cea9f35443f4f9007840384163d3aa3c7d4d18b21b65ff4380cf3f3b48e94b5eecb221dd", + "Gas": 79920, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e300000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d87845147b8192d77bf871b62e87859d653922725724a5c031afeabc60bcef5ff66513800000000000000000000000000000000108ed59fd9fae381abfd1d6bce2fd2fa220990f0f837fa30e0f27914ed6e1454db0d1ee957b219f61da6ff8be0d6441f000000000000000000000000000000000296238ea82c6d4adb3c838ee3cb2346049c90b96d602d7bb1b469b905c9228be25c627bffee872def773d5b2a2eb57d00000000000000000000000000000000033f90f6057aadacae7963b0a0b379dd46750c1c94a6357c99b65f63b79e321ff50fe3053330911c56b6ceea08fee65600000000000000000000000000000000153606c417e59fb331b7ae6bce4fbf7c5190c33ce9402b5ebe2b70e44fca614f3f1382a3625ed5493843d0b0a652fc3f328388aff0d4a5b7dc9205abd374e7e98f3cd9f3418edb4eafda5fb16473d21600000000000000000000000000000000038af300ef34c7759a6caaa4e69363cafeed218a1f207e93b2c70d91a1263d375d6730bd6b6509dcac3ba5b567e85bf3000000000000000000000000000000000da75be60fb6aa0e9e3143e40c42796edf15685cafe0279afd2a67c3dff1c82341f17effd402e4f1af240ea90f4b659b0000000000000000000000000000000019b148cbdf163cf0894f29660d2e7bfb2b68e37d54cc83fd4e6e62c020eaa48709302ef8e746736c0e19342cc1ce3df4000000000000000000000000000000000492f4fed741b073e5a82580f7c663f9b79e036b70ab3e51162359cec4e77c78086fe879b65ca7a47d34374c8315ac5e263dbd792f5b1be47ed85f8938c0f29586af0d3ac7b977f21c278fe1462040e2000000000000000000000000000000000c5ae723be00e6c3f0efe184fdc0702b64588fe77dda152ab13099a3bacd3876767fa7bbad6d6fd90b3642e902b208f90000000000000000000000000000000012c8c05c1d5fc7bfa847f4d7d81e294e66b9a78bc9953990c358945e1f042eedafce608b67fdd3ab0cb2e6e263b9b1ad0000000000000000000000000000000004e77ddb3ede41b5ec4396b7421dd916efc68a358a0d7425bddd253547f2fb4830522358491827265dfc5bcc1928a5690000000000000000000000000000000011c624c56dbe154d759d021eec60fab3d8b852395a89de497e48504366feedd4662d023af447d66926a28076813dd64647b8192d77bf871b62e87859d653922725724a5c031afeabc60bcef5ff665131000000000000000000000000000000000ea4e7c33d43e17cc516a72f76437c4bf81d8f4eac69ac355d3bf9b71b8138d55dc10fd458be115afa798b55dac34be1000000000000000000000000000000001565c2f625032d232f13121d3cfb476f45275c303a037faa255f9da62000c2c864ea881e2bcddd111edc4a3c0da3e88d00000000000000000000000000000000043b6f5fe4e52c839148dc66f2b3751e69a0f6ebb3d056d6465d50d4108543ecd956e10fa1640dfd9bc0030cc2558d28000000000000000000000000000000000f8991d2a1ad662e7b6f58ab787947f1fa607fce12dde171bc17903b012091b657e15333e11701edcf5b63ba2a561247328388aff0d4a5b7dc9205abd374e7e98f3cd9f3418edb4eafda5fb16473d211", + "Name": "bls_g2multiexp_multiple", + "Expected": "0000000000000000000000000000000016cf5fd2c2f1b2e01cc48a6d03e8e6d7f3ad754d6c7d4000f806c18c28d8d559cf529dd159c74946a7713d1906894718000000000000000000000000000000000628d42142df8d620d1f3709ac01f382ba950eaf14c12863885af5838067deec4bb363ffda427fcbdd2b8ec6cc5784ae0000000000000000000000000000000018168dec2441ef462e9a769c782f81acdc7fa49dffebb996764ba9fa96b9200ceb5edd9e96b33c383bd042b4e6af191a000000000000000000000000000000001065aaea2c4aa1d2bee7f1e82a2138ae7016dbbade8383ad912d81eca5fb260086238f95f8cef8f2f491969d4cefa2c3", + "Gas": 147690, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be9a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g2multiexp_random*g2_unnormalized_scalar", + "Expected": "0000000000000000000000000000000014856c22d8cdb2967c720e963eedc999e738373b14172f06fc915769d3cc5ab7ae0a1b9c38f48b5585fb09d4bd2733bb000000000000000000000000000000000c400b70f6f8cd35648f5c126cce5417f3be4d8eefbd42ceb4286a14df7e03135313fe5845e3a575faab3e8b949d248800000000000000000000000000000000149a0aacc34beba2beb2f2a19a440166e76e373194714f108e4ab1c3fd331e80f4e73e6b9ea65fe3ec96d7136de81544000000000000000000000000000000000e4622fef26bdb9b1e8ef6591a7cc99f5b73164500c1ee224b6a761e676b8799b09a3fd4fa7e242645cc1a34708285e4", + "Gas": 54000, + "NoBenchmark": false + }, + { + "Input": "00000000000000000000000000000000103121a2ceaae586d240843a398967325f8eb5a93e8fea99b62b9f88d8556c80dd726a4b30e84a36eeabaf3592937f2700000000000000000000000000000000086b990f3da2aeac0a36143b7d7c824428215140db1bb859338764cb58458f081d92664f9053b50b3fbd2e4723121b68000000000000000000000000000000000f9e7ba9a86a8f7624aa2b42dcc8772e1af4ae115685e60abc2c9b90242167acef3d0be4050bf935eed7c3b6fc7ba77e000000000000000000000000000000000d22c3652d0dc6f0fc9316e14268477c2049ef772e852108d269d9c38dba1d4802e8dae479818184c08f9a569d8784519a2b64cc58f8992cb21237914262ca9ada6cb13dc7b7d3f11c278fe0462040e4", + "Name": "bls_g2multiexp_random*p2_unnormalized_scalar", + "Expected": "00000000000000000000000000000000036074dcbbd0e987531bfe0e45ddfbe09fd015665990ee0c352e8e403fe6af971d8f42141970d9ab14b4dd04874409e600000000000000000000000000000000019705637f24ba2f398f32c3a3e20d6a1cd0fd63e6f8f071cf603a8334f255744927e7bfdfdb18519e019c49ff6e914500000000000000000000000000000000008e74fcff4c4278c9accfb60809ed69bbcbe3d6213ef2304e078d15ec7d6decb4f462b24b8e7cc38cc11b6f2c9e0486000000000000000000000000000000001331d40100f38c1070afd832445881b47cf4d63894666d9907c85ac66604aab5ad329980938cc3c167ccc5b6bc1b8f30", + "Gas": 54000, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/pairing_check_bls.json b/BEPs/assets/bep-439/pairing_check_bls.json new file mode 100644 index 000000000..a74d84892 --- /dev/null +++ b/BEPs/assets/bep-439/pairing_check_bls.json @@ -0,0 +1,44 @@ +[ + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Name": "bls_pairing_e(G1,0)=e(0,G2)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000001", + "Gas": 151000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + "Name": "bls_pairing_non-degeneracy", + "Expected": "0000000000000000000000000000000000000000000000000000000000000000", + "Gas": 108000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be00000000000000000000000000000000112b98340eee2777cc3c14163dea3ec97977ac3dc5c70da32e6e87578f44912e902ccef9efe28d4a78b8999dfbca942600000000000000000000000000000000186b28d92356c4dfec4b5201ad099dbdede3781f8998ddf929b4cd7756192185ca7b8f4ef7088f813270ac3d48868a2100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be000000000000000000000000000000000a40300ce2dec9888b60690e9a41d3004fda4886854573974fab73b046d3147ba5b7a5bde85279ffede1b45b3918d82d0000000000000000000000000000000006d3d887e9f53b9ec4eb6cedf5607226754b07c01ace7834f57f3e7315faefb739e59018e22c492006190fba4a87002500000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "Name": "bls_pairing_bilinearity", + "Expected": "0000000000000000000000000000000000000000000000000000000000000001", + "Gas": 194000, + "NoBenchmark": false + }, + { + "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "Name": "bls_pairing_e(G1,-G2)=e(-G1,G2)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000001", + "Gas": 151000, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000491d1b0ecd9bb917989f0e74f0dea0422eac4a873e5e2644f368dffb9a6e20fd6e10c1b77654d067c0618f6e5a7f79a0000000000000000000000000000000017cd7061575d3e8034fcea62adaa1a3bc38dca4b50e4c5c01d04dd78037c9cee914e17944ea99e7ad84278e5d49f36c4000000000000000000000000000000000bc2357c6782bbb6a078d9e171fc7a81f7bd8ca73eb485e76317359908bb09bd372fd362a637512a9d48019b383e54890000000000000000000000000000000004b8f49c3bac0247a09487049492b0ed99cf90c56263141daa35f011330d3ced3f3ad78d252c51a3bb42fc7d8f182594000000000000000000000000000000000982d17b17404ac198a0ff5f2dffa56a328d95ec4732d9cca9da420ec7cf716dc63d56d0f5179a8b1ec71fe0328fe88200000000000000000000000000000000147c92cb19e43943bb20c5360a6c4347411eb8ffb3d6f19cc428a8dc0cb3fd1eb3ad02b1c21e21c78f65a7691ee63de90000000000000000000000000000000016cae74dc6523e5273dbd2d9d25c53f1e2c453e6d9ba3f605021cfb514fa0bdf721b05f2200f32591d733e739fabf438000000000000000000000000000000001405df65fb71b738510b3a2fc31c33ef3d884ccc84efb1017341a368bf40727b7ad8cdc8e3fd6b0eb94102488c5cb77000000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000d1b3cc2c7027888be51d9ef691d77bcb679afda66c73f17f9ee3837a55024f78c71363275a75d75d86bab79f74782aa0000000000000000000000000000000013fa4d4a0ad8b1ce186ed5061789213d993923066dddaf1040bc3ff59f825c78df74f2d75467e25e0f55f8a00fa030ed", + "Name": "bls_pairing_e(aG1,bG2)=e(abG1,G2)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000001", + "Gas": 151000, + "NoBenchmark": false + }, + { + "Input": "000000000000000000000000000000000491d1b0ecd9bb917989f0e74f0dea0422eac4a873e5e2644f368dffb9a6e20fd6e10c1b77654d067c0618f6e5a7f79a0000000000000000000000000000000017cd7061575d3e8034fcea62adaa1a3bc38dca4b50e4c5c01d04dd78037c9cee914e17944ea99e7ad84278e5d49f36c4000000000000000000000000000000000bc2357c6782bbb6a078d9e171fc7a81f7bd8ca73eb485e76317359908bb09bd372fd362a637512a9d48019b383e54890000000000000000000000000000000004b8f49c3bac0247a09487049492b0ed99cf90c56263141daa35f011330d3ced3f3ad78d252c51a3bb42fc7d8f182594000000000000000000000000000000000982d17b17404ac198a0ff5f2dffa56a328d95ec4732d9cca9da420ec7cf716dc63d56d0f5179a8b1ec71fe0328fe88200000000000000000000000000000000147c92cb19e43943bb20c5360a6c4347411eb8ffb3d6f19cc428a8dc0cb3fd1eb3ad02b1c21e21c78f65a7691ee63de90000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000114d1d6855d545a8aa7d76c8cf2e21f267816aef1db507c96655b9d5caac42364e6f38ba0ecb751bad54dcd6b939c2ca00000000000000000000000000000000166335679f3b3e2617b70c22c48e820e2c6a35149c4f96293035c1494a1ce4591f7a44bce94e9d76def50a71c9e7fa41000000000000000000000000000000000ef11c636091748476331159c8259c064da712ffec033c89299384b4c11b801893026726d992aacdc8e0a28db1a3ab82000000000000000000000000000000000fd8d4944030f480f44ce0d2d4fb67ff6264d30a0f3193cc218b062e5114cf9e4ce847489f7be94b0d4a9fc0c550fdc60000000000000000000000000000000000edba2c166be3d673ea77016163ae5cdf7b3c9bd480e733eb5c08a5f1c798793d339cb503005f5a9e586ea5aabf9695", + "Name": "bls_pairing_e(aG1,bG2)=e(G1,abG2)", + "Expected": "0000000000000000000000000000000000000000000000000000000000000001", + "Gas": 151000, + "NoBenchmark": false + } +] diff --git a/BEPs/assets/bep-439/test-vectors.md b/BEPs/assets/bep-439/test-vectors.md new file mode 100644 index 000000000..e39b8032a --- /dev/null +++ b/BEPs/assets/bep-439/test-vectors.md @@ -0,0 +1,22 @@ +# Test Vectors for BEP-439 - Precompile for BLS12-381 curve operations + +These test vectors are derived from [BLS 12-381 tests](https://github.com/ethereum/bls12-381-tests/tree/eip-2537) + +- [`BLS12_G1ADD` Machine-readable data](add_G1_bls.json) +- [`BLS12_G2ADD` Machine-readable data](add_G2_bls.json) +- [`BLS12_G1MUL` Machine-readable data](mul_G1_bls.json) +- [`BLS12_G2MUL` Machine-readable data](mul_G2_bls.json) +- [`BLS12_MAP_FP_TO_G1` Machine-readable data](map_fp_to_G1_bls.json) +- [`BLS12_MAP_FP2_TO_G2` Machine-readable data](map_fp2_to_G2_bls.json) +- [`BLS12_G1MULTIEXP` Machine-readable data](multiexp_G1_bls.json) +- [`BLS12_G2MULTIEXP` Machine-readable data](multiexp_G2_bls.json) +- [`BLS12_PAIRING_CHECK` Machine-readable data](pairing_check_bls.json) +- [Fail `BLS12_G1ADD` Machine-readable data](fail-add_G1_bls.json) +- [Fail `BLS12_G2ADD` Machine-readable data](fail-add_G2_bls.json) +- [Fail `BLS12_G1MUL` Machine-readable data](fail-mul_G1_bls.json) +- [Fail `BLS12_G2MUL` Machine-readable data](fail-mul_G2_bls.json) +- [Fail `BLS12_MAP_FP_TO_G1` Machine-readable data](fail-map_fp_to_G1_bls.json) +- [Fail `BLS12_MAP_FP2_TO_G2` Machine-readable data](fail-map_fp2_to_G2_bls.json) +- [Fail `BLS12_G1MULTIEXP` Machine-readable data](fail-multiexp_G1_bls.json) +- [Fail `BLS12_G2MULTIEXP` Machine-readable data](fail-multiexp_G2_bls.json) +- [Fail `BLS12_PAIRING_CHECK` Machine-readable data](fail-pairing_check_bls.json) diff --git a/BEPs/assets/bep-520/5-3.png b/BEPs/assets/bep-520/5-3.png new file mode 100644 index 000000000..e6c059baf Binary files /dev/null and b/BEPs/assets/bep-520/5-3.png differ diff --git a/README.md b/README.md index d43421324..5226970cb 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,127 @@ # BEPs -BEP stands for Binance Chain Evolution Proposal. Each BEP will be a proposal document providing information to the Binance Chain/DEX community. +BEP stands for BNB Evolution Proposal. Each BEP will be a proposal document providing information to the BNB Chain ecosystem and community. +Here is the list of subjects of BEPs: -Here are the list of subjects of BEPs: -* [BEP-1](BEP1.md): Purpose and Guidelines of BEP -* [BEP-2](BEP2.md): Tokens on Binance Chain -* [BEP-3](BEP3.md): HTLC and Atomic Peg -* [BEP-6](BEP6.md): Delist Trading Pairs on Binance Chain -* [BEP-8](BEP8.md): Mini-BEP2 Tokens -* [BEP-9](BEP9.md): Time Locking of Tokens on Binance Chain -* [BEP-10](BEP10.md): Registered Types for Transaction Source -* [BEP-12](BEP12.md): Introduce Customized Scripts and Transfer Memo Validation -* [BEP-18](BEP18.md): State sync enhancement -* [BEP-19](BEP19.md): Introduce Maker and Taker for Match Engine -* [BEP-70](BEP70.md): List and Trade BUSD Pairs -* [BEP-67](BEP67.md): Price-based Order Expiration +| Number | Title | Type | Status | +|------------------------------| --------------------------------------------------------- | --------- |-----------| +| [BEP-1](./BEPs/BEP1.md) | Purpose and Guidelines of BEP | Process | Living | +| [BEP-2](./BEPs/BEP2.md) | Tokens on BNB Beacon Chain | Standards | Enabled | +| [BEP-3](./BEPs/BEP3.md) | HTLC and Atomic Peg | Standards | Enabled | +| [BEP-6](./BEPs/BEP6.md) | Delist Trading Pairs on BNB Beacon Chain | Standards | Enabled | +| [BEP-8](./BEPs/BEP8.md) | Mini-BEP2 Tokens | Standards | Enabled | +| [BEP-9](./BEPs/BEP9.md) | Time Locking of Tokens on BNB Beacon Chain | Standards | Enabled | +| [BEP-10](./BEPs/BEP10.md) | Registered Types for Transaction Source | Standards | Enabled | +| [BEP-12](./BEPs/BEP12.md) | Introduce Customized Scripts and Transfer Memo Validation | Standards | Enabled | +| [BEP-18](./BEPs/BEP18.md) | State sync enhancement | Standards | Enabled | +| [BEP-19](./BEPs/BEP19.md) | Introduce Maker and Taker for Match Engine | Standards | Enabled | +| [BEP-20](./BEPs/BEP20.md) | Tokens on BNB Smart Chain | Standards | Enabled | +| [BEP-67](./BEPs/BEP67.md) | Price-based Order | Standards | Enabled | +| [BEP-70](./BEPs/BEP70.md) | List and Trade BUSD Pairs | Standards | Enabled | +| [BEP-82](./BEPs/BEP82.md) | Token Ownership Changes | Standards | Enabled | +| [BEP-84](./BEPs/BEP84.md) | Mirror BEP20 to BNB Beacon Chain | Standards | Enabled | +| [BEP-86](./BEPs/BEP86.md) | Dynamic Extra Incentive For BSC Relayers | Standards | Enabled | +| [BEP-87](./BEPs/BEP87.md) | Token Symbol Minimum Length Change | Standards | Enabled | +| [BEP-89](./BEPs/BEP89.md) | Visual Fork of BNB Smart Chain | Standards | Enabled | +| [BEP-91](./BEPs/BEP91.md) | Increase Block Gas Ceiling for BNB Smart Chain | Standards | Enabled | +| [BEP-95](./BEPs/BEP95.md) | Introduce Real-Time Burning Mechanism | Standards | Enabled | +| [BEP-126](./BEPs/BEP126.md) | Introduce Fast Finality Mechanism | Standards | Enabled | +| [BEP-127](./BEPs/BEP127.md) | Temporary Maintenance Mode for Validators | Standards | Enabled | +| [BEP-128](./BEPs/BEP128.md) | Improvement on BNB Smart Chain Staking Reward Distribution | Standards | Enabled | +| [BEP-131](./BEPs/BEP131.md) | Introduce candidate validators onto BNB Smart Chain | Standards | Enabled | +| [BEP-151](./BEPs/BEP151.md) | Decommission Decentralized Exchange on BNB Beacon Chain | Standards | Enabled | +| [BEP-153](./BEPs/BEP153.md) | Introduce native staking onto BNB Smart Chain | Standards | Enabled | +| [BEP-159](./BEPs/BEP159.md) | Introduce A New Staking Mechanism on BNB Beacon Chain | Standards | Draft | +| [BEP-171](./BEPs/BEP171.md) | Security Enhancement for Cross-Chain Module | Standards | Enabled | +| [BEP-172](./BEPs/BEP172.md) | Network Stability Enhancement On Slash Occur | Standards | Enabled | +| [BEP-173](./BEPs/BEP173.md) | Introduce Text Governance Proposal for BNB Smart Chain | Standards | Enabled | +| [BEP-174](./BEPs/BEP174.md) | Cross Chain Relayer Management | Standards | Enabled | +| [BEP-188](./BEPs/BEP188.md) | Early Broadcast Mature Block For In-Turn Validators | Standards | Withdrawn | +| [BEP-194](./BEPs/BEP194.md) | Node Discovery ENR filtering | Standards | Draft | +| [BEP-206](./BEPs/BEP206.md) | Hybrid Mode State Expiry | Standards | Stagnant | +| [BEP-216](./BEPs/BEP216.md) | Implement EIP 3855 PUSH0 instruction | Standards | Enabled | +| [BEP-217](./BEPs/BEP217.md) | Implement EIP3860 Limit and meter initcode | Standards | Enabled | +| [BEP-221](./BEPs/BEP221.md) | CometBFT Light Block Validation | Standards | Draft | +| [BEP-225](./BEPs/BEP-225.md) | Implement EIP2565 ModExp Gas Cost | Standards | Enabled | +| [BEP-226](./BEPs/BEP226.md) | Enable EIP-1559 with base fee of 0 | Standards | Enabled | +| [BEP-227](./BEPs/BEP227.md) | Add BASEFEE opcode | Standards | Enabled | +| [BEP-228](./BEPs/BEP228.md) | Prevent deploying contracts starting with 0xEF | Standards | Enabled | +| [BEP-229](./BEPs/BEP-229.md) | Implement EIP-2718 Typed Transaction Envelope | Standards | Enabled | +| [BEP-230](./BEPs/BEP-230.md) | Implement EIP-2929 Gas cost increases for state access opcodes | Standards | Enabled | +| [BEP-231](./BEPs/BEP231.md) | Implement EIP-2930: Optional access lists | Standards | Enabled | +| [BEP-255](./BEPs/BEP255.md) | Beacon Chain Asset Reconciliation for Security Enhancement | Standards | Enabled | +| [BEP-293](./BEPs/BEP-293.md) | Greenfield Link to opBNB | Standards | Draft | +| [BEP-294](./BEPs/BEP294.md) | BSC Native Staking after BC Fusion | Standards | Enabled | +| [BEP-297](./BEPs/BEP297.md) | BSC Native Governance Module | Standards | Enabled | +| [BEP-299](./BEPs/BEP-299.md) | Token Migration after BC Fusion | Standards | Enabled | +| [BEP-311](./BEPs/BEP-311.md) | Implement EIP-3651 Warm COINBASE | Standards | Enabled | +| [BEP-312](./BEPs/BEP-312.md) | Announce EIP-6049 Deprecate SELFDESTRUCT | Standards | Enabled | +| [BEP-319](./BEPs/BEP-319.md) | Optimize the incentive mechanism of the Fast Finality feature | Standards | Enabled | +| [BEP-322](./BEPs/BEP322.md) | Builder API Specification for BNB Smart Chain | Standards | Enabled | +| [BEP-323](./BEPs/BEP323.md) | Bundle Format for Greenfield | Standards | Enabled | +| [BEP-333](./BEPs/BEP333.md) | BNB Chain Fusion | Standards | Enabled | +| [BEP-334](./BEPs/BEP-334.md) | Greenfield CrossChain Permission Module | Standards | Enabled | +| [BEP-335](./BEPs/BEP-335.md) | Greenfield Simplify Storage Provider Exit | Standards | Enabled | +| [BEP-336](./BEPs/BEP-336.md) | Implement EIP-4844: Shard Blob Transactions | Standards | Enabled | +| [BEP-341](./BEPs/BEP-341.md) | Validators can produce consecutive blocks | Standards | Enabled | +| [BEP-342](./BEPs/BEP-342.md) | Implement EIP-5656: MCOPY | Standards | Enabled | +| [BEP-343](./BEPs/BEP-343.md) | Implement EIP-1153: Transient storage opcodes | Standards | Enabled | +| [BEP-344](./BEPs/BEP-344.md) | Implement EIP-6780: SELFDESTRUCT only in same transaction | Standards | Enabled | +| [BEP-345](./BEPs/BEP-345.md) | Implement EIP-7516: BLOBBASEFEE opcode | Standards | Enabled | +| [BEP-346](./BEPs/BEP-346.md) | Streamline off-chain authentication on Greenfield | Standards | Enabled | +| [BEP-362](./BEPs/BEP-362.md) | Greenfield Storage Fee Paymaster | Standards | Enabled | +| [BEP-364](./BEPs/BEP-364.md) | Primary Storage Provider acts as the upload agent for object creation and update on Greenfield | Standards | Enabled | +| [BEP-366](./BEPs/BEP-366.md) | PGreenfield Atomic Object Update | Standards | Candidate | +| [BEP-402](./BEPs/BEP-402.md) | Complete Missing Fields in Block Header to Generate Signature | Standards | Enabled | +| [BEP-404](./BEPs/BEP-404.md) | Clear Miner History when Switching Validator Set | Standards | Enabled | +| [BEP-410](./BEPs/BEP-410.md) | Add Agent for Validators | Standards | Enabled | +| [BEP-414](./BEPs/BEP-414.md) | EOA based Paymaster API Spec | Standards | Enabled | +| [BEP-439](./BEPs/BEP-439.md) | Implement EIP-2537: Precompile for BLS12-381 curve operations | Standards | Enabled | +| [BEP-440](./BEPs/BEP-440.md) | Implement EIP-2935: Serve historical block hashes from state | Standards | Enabled | +| [BEP-441](./BEPs/BEP-441.md) | Implement EIP-7702: Set EOA account code | Standards | Enabled | +| [BEP-466](./BEPs/BEP-466.md) | Make the block header format compatible with EIP-7685 | Standards | Enabled | +| [BEP-496](./BEPs/BEP-496.md) | Implement EIP-7623: Increase calldata cost | Standards | Enabled | +| [BEP-520](./BEPs/BEP-520.md) | Short Block Interval Phase One: 1.5 seconds | Standards | Enabled | +| [BEP-524](./BEPs/BEP-524.md) | Short Block Interval Phase Two: 0.75 seconds | Standards | Enabled | +| [BEP-563](./BEPs/BEP-563.md) | Enhanced Validator Network | Standards | Enabled | +| [BEP-564](./BEPs/BEP-564.md) | bsc/2 - New Block Fetching Messages | Standards | Enabled | +| [BEP-590](./BEPs/BEP-590.md) | Extended Voting Rules for Fast Finality Stability | Standards | Enabled | +| [BEP-592](./BEPs/BEP-592.md) | Non-Consensus Based Block-Level Access List | Standards | Candidate | +| [BEP-593](./BEPs/BEP-593.md) | Incremental Snapshot | Standards | Enabled | +| [BEP-594](./BEPs/BEP-594.md) | L2 Fast Withdrawal by TEE | Standards | Draft | +| [BEP-610](./BEPs/BEP-610.md) | Implement EVM Super Instruction | Standards | Candidate | +| [BEP-619](./BEPs/BEP-619.md) | Short Block Interval Phase Three: 0.45 Seconds | Standards | Enabled | +| [BEP-640](./BEPs/BEP-640.md) | Optional Transaction Gas Limit Cap | Standards | Candidate | +| [BEP-648](./BEPs/BEP-648.md) | Enhanced Fast Finality via In-Memory Voting Pool | Standards | Draft | +| [BEP-651](./BEPs/BEP-651.md) | Implement EIP-7823 Set upper bounds for MODEXP | Standards | Draft | +| [BEP-652](./BEPs/BEP-652.md) | Implement EIP-7825 Transaction Gas Limit Cap | Standards | Draft | +| [BEP-653](./BEPs/BEP-653.md) | Implement EIP-7883 ModExp Gas Cost Increase | Standards | Draft | +| [BEP-654](./BEPs/BEP-654.md) | Implement EIP-7939 Count Leading Zeros (CLZ) Opcode | Standards | Draft | +| [BEP-655](./BEPs/BEP-655.md) | Implement EIP-7934 RLP Execution Block Size Limit | Standards | Draft | +| [BEP-656](./BEPs/BEP-656.md) | Implement EIP-7910: eth_config JSON-RPC Method | Standards | Draft | +| [BEP-657](./BEPs/BEP-657.md) | Limit Blob Transaction Inclusion by Block Number | Standards | Draft | +| [BEP-658](./BEPs/BEP-658.md) | Hardfork Meta-Osaka/Mendel | Information | Draft | +| [BEP-659](./BEPs/BEP-659.md) | Implement EIP-7951 Precompile for secp256r1 Curve Support | Standards | Draft | +# BAPs +BAP (BNB Application Proposal) defines standards for application layer interactions on BNB Chain. Unlike BEPs which govern core protocol changes, BAPs focus on establishing conventions and interfaces for how applications communicate and interact with each other within the BNB Chain ecosystem. + +The process for submitting and managing BAPs follows the standardized workflow outlined in [BEP-1: Purpose and Guidelines](https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP1.md). BAP numbers are assigned based on the PR number, ensuring no overlap with BEP numbers. + +Here is the list of subjects of BAPs: + + +| Number | Title | Type | Status | +|------------------------------| --------------------------------------------------------- | --------- |-----------| +| [BAP-578](./BAPs/BAP-578.md) | BAP-578: Non-Fungible Agent (NFA) Token Standard | Application | Draft | + +# BNB Chain Upgrades +[BNB Chain Upgrades(Mainnet): History & Forecast](https://forum.bnbchain.org/t/bnb-chain-upgrades-mainnet/936) + +[BNB Chain Upgrades(Testnet): History & Forecast](https://forum.bnbchain.org/t/bnb-chain-upgrades-testnet/934) + + +# How To Contribute +If you have an idea and want to make it a BEP/BAP, you may refer [BEP-1](./BEPs/BEP1.md) \ No newline at end of file