forked from colinlyguo/EIP-4844-dev-usage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
276 lines (227 loc) · 7.72 KB
/
main.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"github.com/consensys/gnark-crypto/ecc/bls12-381/fr"
gokzg4844 "github.com/crate-crypto/go-kzg-4844"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/misc/eip4844"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/kzg4844"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/log"
"github.com/holiman/uint256"
"github.com/joho/godotenv"
)
const escalateMultiplier = 10
func main() {
glogger := log.NewGlogHandler(log.NewTerminalHandler(os.Stderr, true))
glogger.Verbosity(log.LevelInfo)
log.SetDefault(log.NewLogger(glogger))
err := godotenv.Load("../.env")
if err != nil {
log.Crit("failed to load .env file", "err", err)
}
privateKey, err := crypto.HexToECDSA(os.Getenv("PRIVATE_KEY"))
if err != nil {
log.Crit("failed to create private key", "err", err)
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Crit("failed to cast public key to ECDSA")
}
fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
client, err := ethclient.Dial(os.Getenv("RPC_PROVIDER_URL"))
if err != nil {
log.Crit("failed to connect to network", "err", err)
}
chainID, err := client.NetworkID(context.Background())
if err != nil {
log.Crit("failed to get network ID", "err", err)
}
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
log.Crit("failed to get pending nonce", "err", err)
}
gasTipCap, err := client.SuggestGasTipCap(context.Background())
if err != nil {
log.Crit("failed to get suggest gas tip cap", "err", err)
}
gasFeeCap, err := client.SuggestGasPrice(context.Background())
if err != nil {
log.Crit("failed to get suggest gas price", "err", err)
}
blsModulo, ok := new(big.Int).SetString("52435875175126190479447740508185965837690552500527637822603658699938581184513", 10)
if !ok {
log.Crit("failed to initialize bls_modulo")
}
demoContractAddress := common.HexToAddress("0x45d38deD8a95656f72be2bD4de44F33E10EBA1da")
blob := randBlob()
sideCar := makeSidecar([]kzg4844.Blob{blob})
versionedHash := sideCar.BlobHashes()[0]
pointHash := crypto.Keccak256Hash(versionedHash.Bytes())
pointBigInt := new(big.Int).SetBytes(pointHash.Bytes())
point := kzg4844.Point(new(big.Int).Mod(pointBigInt, blsModulo).Bytes())
commitment := sideCar.Commitments[0]
proof, claim, err := kzg4844.ComputeProof(blob, point)
if err != nil {
log.Crit("failed to create KZG proof at point", "err", err)
}
var mockRunCalldata []byte
mockRunCalldata = append(mockRunCalldata, versionedHash.Bytes()...)
mockRunCalldata = append(mockRunCalldata, point[:]...)
mockRunCalldata = append(mockRunCalldata, claim[:]...)
mockRunCalldata = append(mockRunCalldata, commitment[:]...)
mockRunCalldata = append(mockRunCalldata, proof[:]...)
// Verify proof locally: the same implementation as the precompile.
if err := mockRun(mockRunCalldata); err != nil {
log.Crit("failed to verify KZG proof at point", "err", err)
}
abiFile, err := os.ReadFile("./abi.json")
if err != nil {
log.Crit("Unable to read ABI file", "err", err)
}
var demoContractABI abi.ABI
err = json.Unmarshal(abiFile, &demoContractABI)
if err != nil {
log.Crit("Unable to parse ABI", "err", err)
}
fmt.Println(demoContractABI)
var claimArray [32]byte
copy(claimArray[:], claim[:])
txCalldata, err := demoContractABI.Pack(
"verifyProofAndEmitEvent",
claimArray,
commitment[:],
proof[:],
)
if err != nil {
log.Crit("failed to pack calldata", "err", err)
}
// Estimate pending block's blobFeeCap.
parentHeader, err := client.HeaderByNumber(context.Background(), nil)
if err != nil {
log.Crit("failed to get previous block header", "err", err)
}
parentExcessBlobGas := eip4844.CalcExcessBlobGas(*parentHeader.ExcessBlobGas, *parentHeader.BlobGasUsed)
blobFeeCap := eip4844.CalcBlobFee(parentExcessBlobGas)
log.Info("blob gas info", "excessBlobGas", parentExcessBlobGas, "blobFeeCap", blobFeeCap)
gasTipCap = new(big.Int).Mul(gasTipCap, big.NewInt(escalateMultiplier))
gasFeeCap = new(big.Int).Mul(gasFeeCap, big.NewInt(escalateMultiplier))
blobFeeCap = new(big.Int).Mul(blobFeeCap, big.NewInt(escalateMultiplier))
tx := types.NewTx(&types.BlobTx{
ChainID: uint256.MustFromBig(chainID),
Nonce: nonce,
GasTipCap: uint256.MustFromBig(gasTipCap),
GasFeeCap: uint256.MustFromBig(gasFeeCap),
Gas: 200000,
To: demoContractAddress,
BlobFeeCap: uint256.MustFromBig(blobFeeCap),
BlobHashes: sideCar.BlobHashes(),
Sidecar: sideCar,
Data: txCalldata,
})
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
log.Crit("failed to create transactor", "chainID", chainID, "err", err)
}
signedTx, err := auth.Signer(auth.From, tx)
if err != nil {
log.Crit("failed to sign the transaction", "err", err)
}
err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
log.Crit("failed to send transaction", "err", err)
}
log.Info("transaction sent", "txHash", signedTx.Hash().Hex())
}
func makeSidecar(blobs []kzg4844.Blob) *types.BlobTxSidecar {
var (
commitments []kzg4844.Commitment
proofs []kzg4844.Proof
)
for _, blob := range blobs {
c, _ := kzg4844.BlobToCommitment(blob)
p, _ := kzg4844.ComputeBlobProof(blob, c)
commitments = append(commitments, c)
proofs = append(proofs, p)
}
return &types.BlobTxSidecar{
Blobs: blobs,
Commitments: commitments,
Proofs: proofs,
}
}
func randBlob() kzg4844.Blob {
var blob kzg4844.Blob
for i := 0; i < len(blob); i += gokzg4844.SerializedScalarSize {
fieldElementBytes := randFieldElement()
copy(blob[i:i+gokzg4844.SerializedScalarSize], fieldElementBytes[:])
}
return blob
}
func randFieldElement() [32]byte {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
panic("failed to get random field element")
}
var r fr.Element
r.SetBytes(bytes)
return gokzg4844.SerializeScalar(r)
}
const (
blobVerifyInputLength = 192 // Max input length for the point evaluation precompile.
blobCommitmentVersionKZG uint8 = 0x01 // Version byte for the point evaluation precompile.
blobPrecompileReturnValue = "000000000000000000000000000000000000000000000000000000000000100073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"
)
var (
errBlobVerifyInvalidInputLength = errors.New("invalid input length")
errBlobVerifyMismatchedVersion = errors.New("mismatched versioned hash")
errBlobVerifyKZGProof = errors.New("error verifying kzg proof")
)
func mockRun(input []byte) error {
if len(input) != blobVerifyInputLength {
return errBlobVerifyInvalidInputLength
}
// versioned hash: first 32 bytes
var versionedHash common.Hash
copy(versionedHash[:], input[:])
var (
point kzg4844.Point
claim kzg4844.Claim
)
// Evaluation point: next 32 bytes
copy(point[:], input[32:])
// Expected output: next 32 bytes
copy(claim[:], input[64:])
// input kzg point: next 48 bytes
var commitment kzg4844.Commitment
copy(commitment[:], input[96:])
if kZGToVersionedHash(commitment) != versionedHash {
return errBlobVerifyMismatchedVersion
}
// Proof: next 48 bytes
var proof kzg4844.Proof
copy(proof[:], input[144:])
if err := kzg4844.VerifyProof(commitment, point, claim, proof); err != nil {
return fmt.Errorf("%w: %v", errBlobVerifyKZGProof, err)
}
return nil
}
func kZGToVersionedHash(kzg kzg4844.Commitment) common.Hash {
h := sha256.Sum256(kzg[:])
h[0] = blobCommitmentVersionKZG
return h
}