-
Notifications
You must be signed in to change notification settings - Fork 5
/
credentials.go
315 lines (265 loc) · 8.2 KB
/
credentials.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package eth2deposit
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"regexp"
"strconv"
"strings"
"github.com/awnumar/memguard"
"github.com/herumi/bls-eth-go-binary/bls"
)
func init() {
bls.Init(bls.BLS12_381)
bls.SetETHmode(bls.EthModeDraft07)
}
func _path_to_nodes(path string) ([]uint32, error) {
path = strings.ReplaceAll(path, " ", "")
matched, err := regexp.MatchString("[m1234567890/]", path)
if err != nil {
return nil, err
}
if !matched {
return nil, fmt.Errorf("Invalid path:%v", path)
}
indices := strings.Split(path, "/")
if indices[0] != "m" {
return nil, fmt.Errorf("The first character of path should be `m`. Got %v", indices[0])
}
var indicesList []uint32
for i := 1; i < len(indices); i++ {
d, err := strconv.ParseUint(indices[i], 10, 32)
if err != nil {
return nil, err
}
indicesList = append(indicesList, uint32(d))
}
return indicesList, nil
}
func _seed_and_path_to_key(seed *big.Int, path string) (*big.Int, error) {
bts := seed.Bytes()
if len(bts) < 32 {
extend := make([]byte, 32)
copy(extend[32-len(bts):], bts)
bts = extend
}
sk, err := _derive_master_SK(bts)
if err != nil {
return nil, err
}
nodes, err := _path_to_nodes(path)
if err != nil {
return nil, err
}
for k := range nodes {
sk, err = _derive_child_SK(sk, nodes[k])
if err != nil {
return nil, err
}
}
return sk, nil
}
// Credential defines a ETH2 bls signing credential
type Credential struct {
chain BaseChainSetting
eth1_withdrawal_address []byte
withdrawal_sk *memguard.Enclave // stores based-10 string of seed key
signing_sk *memguard.Enclave // stores based-10 string of seed key
}
// NewCredential creates an ETH2 BLS signing credential
func NewCredential(buf *memguard.LockedBuffer, account uint32, hex_eth1_withdrawal_address []byte, chain BaseChainSetting) (*Credential, error) {
seed := new(big.Int).SetBytes(buf.Bytes())
defer buf.Destroy()
cred := new(Credential)
cred.chain = chain
cred.eth1_withdrawal_address = hex_eth1_withdrawal_address
withdrawal_key_path := fmt.Sprintf("m/%v/%v/%d/0", purpose, coin_type, account)
withdrawal_sk, err := _seed_and_path_to_key(seed, withdrawal_key_path)
if err != nil {
return nil, err
}
cred.withdrawal_sk = memguard.NewEnclave([]byte(withdrawal_sk.String()))
signing_key_path := fmt.Sprintf("%s/0", withdrawal_key_path)
signing_sk, err := _seed_and_path_to_key(seed, signing_key_path)
if err != nil {
return nil, err
}
cred.signing_sk = memguard.NewEnclave([]byte(signing_sk.String()))
return cred, nil
}
func (cred *Credential) withdrawPrefix() byte {
if cred.eth1_withdrawal_address != nil {
return eth1AddressWithdrawalPrefix
}
return blsWithdrawalPrefix
}
func (cred *Credential) withdrawType() (WithdrawType, error) {
prefix := cred.withdrawPrefix()
if prefix == blsWithdrawalPrefix {
return blsWithdrawal, nil
} else if prefix == eth1AddressWithdrawalPrefix {
return eth1AddressWithdrawal, nil
}
return invalidWithdrawal, errorWithdrawPrefix
}
/*******************************************************************************
*
* Public methods for credential
*
*******************************************************************************/
type CompactDepositData struct {
PubKey string `json:"pubkey"`
WithdrawCredential string `json:"withdrawal_credentials"`
Amount int `json:"amount"`
Signature string `json:"signature"`
DepositMessageRoot string `json:"deposit_message_root"`
DepositDataRoot string `json:"deposit_data_root"`
ForkVersion string `json:"fork_version"`
Eth2NetworkName string `json:"network_name"`
DepositCliVersion string `json:"deposit_cli_version"`
}
// String returns json string compatible with eth2deposit
func (cred *Credential) MarshalText() ([]byte, error) {
msg := new(CompactDepositData)
withdraw_credential, err := cred.WithdrawCredentials()
if err != nil {
return nil, err
}
signed_deposit, err := cred.SignedDeposit()
if err != nil {
return nil, err
}
signed_deposit_root, err := signed_deposit.HashTreeRoot()
if err != nil {
return nil, err
}
pubkey, err := cred.SigningPK()
if err != nil {
return nil, err
}
deposit_message, err := cred.DepositMessage()
if err != nil {
return nil, err
}
deposit_message_root, err := deposit_message.HashTreeRoot()
if err != nil {
return nil, err
}
msg.PubKey = hex.EncodeToString(pubkey)
msg.WithdrawCredential = hex.EncodeToString(withdraw_credential)
msg.Amount = 32000000000
msg.Signature = hex.EncodeToString(signed_deposit.Signature[:])
msg.DepositMessageRoot = hex.EncodeToString(deposit_message_root[:])
msg.DepositDataRoot = hex.EncodeToString(signed_deposit_root[:])
msg.ForkVersion = hex.EncodeToString(cred.chain.GENESIS_FORK_VERSION[:])
msg.Eth2NetworkName = cred.chain.ETH2_NETWORK_NAME
msg.DepositCliVersion = DEPOSIT_CLI_VERSION
return json.Marshal([]*CompactDepositData{msg})
}
// WithdrawalSK returns locked withdraw secret key in 10-based string
func (cred *Credential) WithdrawalSK() (*memguard.LockedBuffer, error) {
return cred.withdrawal_sk.Open()
}
// SigningSK returns locked signing secret key in 10-based string
func (cred *Credential) SigningSK() (*memguard.LockedBuffer, error) {
return cred.signing_sk.Open()
}
// DepositMessage retrieves deposit message
func (cred *Credential) DepositMessage() (*DepositMessage, error) {
msg := new(DepositMessage)
pubkey, err := cred.SigningPK()
if err != nil {
return nil, err
}
withdrawCredential, err := cred.WithdrawCredentials()
if err != nil {
return nil, err
}
copy(msg.Pubkey[:], pubkey)
copy(msg.WithdrawalCredentials[:], withdrawCredential)
msg.Amount = uint64(1e9 * 32)
return msg, nil
}
// SigningPK returns public key of BLS signing account
func (cred *Credential) SigningPK() (pub []byte, err error) {
sec := new(bls.SecretKey)
buf, err := cred.signing_sk.Open()
defer buf.Destroy()
err = sec.SetDecString(buf.String())
if err != nil {
return nil, err
}
return sec.GetPublicKey().Serialize(), nil
}
// WithdrawalPK returns public key of BLS withdrawal account
func (cred *Credential) WithdrawalPK() (pub []byte, err error) {
buf, err := cred.withdrawal_sk.Open()
defer buf.Destroy()
sec := new(bls.SecretKey)
err = sec.SetDecString(buf.String())
if err != nil {
return nil, err
}
return sec.GetPublicKey().Serialize(), nil
}
// SignedDeposit returns the deposit data
func (cred *Credential) SignedDeposit() (*DepositData, error) {
// deposit message
depositMessage, err := cred.DepositMessage()
// deposit domain
domain, err := ComputeDepositDomain(cred.chain.GENESIS_FORK_VERSION)
if err != nil {
return nil, err
}
// sign
messageToSign, err := ComputeSigningRoot(depositMessage, domain)
if err != nil {
return nil, err
}
// open encalve
sec := new(bls.SecretKey)
buf, err := cred.signing_sk.Open()
if err != nil {
return nil, err
}
defer buf.Destroy()
// sign
err = sec.SetDecString(buf.String())
if err != nil {
return nil, err
}
sig := sec.SignByte(messageToSign[:])
// deposit data
depositData := new(DepositData)
depositData.Amount = depositMessage.Amount
depositData.WithdrawalCredentials = depositMessage.WithdrawalCredentials
depositData.Pubkey = depositMessage.Pubkey
copy(depositData.Signature[:], sig.Serialize())
return depositData, nil
}
// WithdrawCredentials returns credential bytes
func (cred *Credential) WithdrawCredentials() ([]byte, error) {
var withdrawal_credentials []byte
withdrawType, err := cred.withdrawType()
if err != nil {
return nil, err
}
if withdrawType == blsWithdrawal {
withdrawal_credentials = append(withdrawal_credentials, blsWithdrawalPrefix)
pub, err := cred.WithdrawalPK()
if err != nil {
return nil, err
}
sum := sha256.Sum256(pub)
withdrawal_credentials = append(withdrawal_credentials, sum[1:]...)
} else if withdrawType == eth1AddressWithdrawal && cred.eth1_withdrawal_address != nil {
withdrawal_credentials = append(withdrawal_credentials, eth1AddressWithdrawalPrefix)
withdrawal_credentials = append(withdrawal_credentials, make([]byte, 11)...)
withdrawal_credentials = append(withdrawal_credentials, cred.eth1_withdrawal_address...)
} else {
return nil, errorWithdrawType
}
return withdrawal_credentials, nil
}