Repository navigation
Expand file tree
/
Copy pathPrecompiles.sol
More file actions
100 lines (76 loc) · 3.24 KB
/
Copy pathPrecompiles.sol
File metadata and controls
100 lines (76 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/**
* @title 以太坊预编译合约使用示例
* @dev 展示如何使用预编译合约进行 Gas 优化
*/
contract PrecompilesExample {
// ============ 预编译合约地址常量 ============
address constant ECRECOVER = address(0x01); // 椭圆曲线签名恢复
address constant SHA256 = address(0x02); // SHA-256 哈希
address constant RIPEMD160 = address(0x03); // RIPEMD-160 哈希
address constant IDENTITY = address(0x04); // 数据复制
address constant MODEXP = address(0x05); // 模幂运算
address constant ECADD = address(0x06); // 椭圆曲线加法
address constant ECMUL = address(0x07); // 椭圆曲线乘法
address constant ECPAIRING = address(0x08); // 椭圆曲线配对
address constant BLAKE2F = address(0x09); // BLAKE2b F 函数
// ============ 事件定义 ============
event HashResult(bytes32 hash, string method);
event SignatureRecovered(address signer);
// ============ 1. ECRECOVER (地址: 0x01) ============
/**
* @dev 使用预编译合约恢复签名者地址
* @param hash 消息哈希
* @param v 签名参数 v
* @param r 签名参数 r
* @param s 签名参数 s
*/
function recoverSigner(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) public returns (address) {
// 使用预编译合约
address signer = ecrecover(hash, v, r, s);
emit SignatureRecovered(signer);
return signer;
}
// ============ 2. SHA256 (地址: 0x02) ============
/**
* @dev 使用 SHA256 预编译合约进行哈希
*/
function hashWithSHA256(bytes memory data) public returns (bytes32) {
// 调用 SHA256 预编译合约
(bool success, bytes memory result) = SHA256.staticcall(data);
require(success, "SHA256 precompile failed");
bytes32 hash = bytes32(result);
// 对比:使用 Solidity 内置 sha256()
bytes32 hash1 = sha256(data);
require(hash == hash1, "SHA256 precompile failed!!!");
emit HashResult(hash, "SHA256");
return hash;
}
// ============ 3. RIPEMD160 (地址: 0x03) ============
/**
* @dev 使用 RIPEMD160 预编译合约
*/
function hashWithRIPEMD160(bytes memory data) public view returns (bytes20) {
(bool success, bytes memory result) = RIPEMD160.staticcall(data);
require(success, "RIPEMD160 precompile failed");
bytes20 hash = bytes20(result);
return hash;
}
// ============ 4. IDENTITY (地址: 0x04) - 数据复制 ============
/**
* @dev 使用 IDENTITY 预编译合约进行大量数据复制
* 对于大量内存复制,预编译合约更高效
*/
function copyLargeData(bytes memory data) public view returns (bytes memory) {
// 使用预编译合约复制数据
(bool success, bytes memory copied) = IDENTITY.staticcall(data);
require(success, "Identity precompile failed");
return copied;
}
}