-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathutils.go
107 lines (94 loc) · 2.45 KB
/
utils.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
package main
import (
"crypto/sha256"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/kzg4844"
"github.com/ethereum/go-ethereum/params"
"github.com/holiman/uint256"
)
func encodeBlobs(data []byte) []kzg4844.Blob {
blobs := []kzg4844.Blob{{}}
blobIndex := 0
fieldIndex := -1
for i := 0; i < len(data); i += 31 {
fieldIndex++
if fieldIndex == params.BlobTxFieldElementsPerBlob {
blobs = append(blobs, kzg4844.Blob{})
blobIndex++
fieldIndex = 0
}
max := i + 31
if max > len(data) {
max = len(data)
}
copy(blobs[blobIndex][fieldIndex*32:], data[i:max])
}
return blobs
}
func EncodeBlobs(data []byte) ([]kzg4844.Blob, []kzg4844.Commitment, []kzg4844.Proof, []common.Hash, error) {
var (
blobs = encodeBlobs(data)
commits []kzg4844.Commitment
proofs []kzg4844.Proof
versionedHashes []common.Hash
)
for _, blob := range blobs {
commit, err := kzg4844.BlobToCommitment(blob)
if err != nil {
return nil, nil, nil, nil, err
}
commits = append(commits, commit)
proof, err := kzg4844.ComputeBlobProof(blob, commit)
if err != nil {
return nil, nil, nil, nil, err
}
proofs = append(proofs, proof)
versionedHashes = append(versionedHashes, kZGToVersionedHash(commit))
}
return blobs, commits, proofs, versionedHashes, nil
}
var blobCommitmentVersionKZG uint8 = 0x01
// kZGToVersionedHash implements kzg_to_versioned_hash from EIP-4844
func kZGToVersionedHash(kzg kzg4844.Commitment) common.Hash {
h := sha256.Sum256(kzg[:])
h[0] = blobCommitmentVersionKZG
return h
}
func DecodeBlob(blob []byte) []byte {
if len(blob) != params.BlobTxFieldElementsPerBlob*32 {
panic("invalid blob encoding")
}
var data []byte
// XXX: the following removes trailing 0s in each field element (see EncodeBlobs), which could be unexpected for certain blobs
j := 0
for i := 0; i < params.BlobTxFieldElementsPerBlob; i++ {
data = append(data, blob[j:j+31]...)
j += 32
}
i := len(data) - 1
for ; i >= 0; i-- {
if data[i] != 0x00 {
break
}
}
data = data[:i+1]
return data
}
func DecodeUint256String(hexOrDecimal string) (*uint256.Int, error) {
var base = 10
if strings.HasPrefix(hexOrDecimal, "0x") {
base = 16
}
b, ok := new(big.Int).SetString(hexOrDecimal, base)
if !ok {
return nil, fmt.Errorf("invalid value")
}
val256, nok := uint256.FromBig(b)
if nok {
return nil, fmt.Errorf("value is too big")
}
return val256, nil
}