/
wallet.go
389 lines (330 loc) · 9.69 KB
/
wallet.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package interactors
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"encoding/hex"
"encoding/json"
"encoding/pem"
"io"
"os"
"github.com/multiversx/mx-chain-crypto-go/signing"
"github.com/multiversx/mx-chain-crypto-go/signing/ed25519"
"github.com/multiversx/mx-sdk-go/core"
"github.com/multiversx/mx-sdk-go/data"
"github.com/pborman/uuid"
"github.com/tyler-smith/go-bip39"
"golang.org/x/crypto/scrypt"
)
const (
mnemonicBitSize = 256
egldCoinType = uint32(508)
hardened = uint32(0x80000000)
keystoreVersion = 4
keyHeaderKDF = "scrypt"
scryptN = 4096
scryptR = 8
scryptP = 1
scryptDKLen = 32
addressLen = 32
mnemonicKind = "mnemonic"
)
type bip32Path []uint32
type bip32 struct {
Key []byte
ChainCode []byte
}
var suite = ed25519.NewEd25519()
var keyGenerator = signing.NewKeyGenerator(suite)
type encryptedKeyJSONV4 struct {
Address string `json:"address"`
Bech32 string `json:"bech32"`
Kind string `json:"kind"`
Crypto struct {
Cipher string `json:"cipher"`
CipherText string `json:"ciphertext"`
CipherParams struct {
IV string `json:"iv"`
} `json:"cipherparams"`
KDF string `json:"kdf"`
KDFParams struct {
DkLen int `json:"dklen"`
Salt string `json:"salt"`
N int `json:"n"`
R int `json:"r"`
P int `json:"p"`
} `json:"kdfparams"`
MAC string `json:"mac"`
} `json:"crypto"`
Id string `json:"id"`
Version int `json:"version"`
}
type wallet struct {
}
// NewWallet creates a new wallet instance
func NewWallet() *wallet {
return &wallet{}
}
// GenerateMnemonic will generate a new mnemonic value using the bip39 implementation
func (w *wallet) GenerateMnemonic() (data.Mnemonic, error) {
entropy, err := bip39.NewEntropy(mnemonicBitSize)
if err != nil {
return "", err
}
mnemonicString, err := bip39.NewMnemonic(entropy)
if err != nil {
return "", err
}
return data.Mnemonic(mnemonicString), nil
}
// GetPrivateKeyFromMnemonic generates a private key based on mnemonic, account and address index
func (w *wallet) GetPrivateKeyFromMnemonic(mnemonic data.Mnemonic, account, addressIndex uint32) []byte {
seed := w.CreateSeedFromMnemonic(mnemonic)
privateKey := w.GetPrivateKeyFromSeed(seed, account, addressIndex)
return privateKey
}
// GetPrivateKeyFromSeed generates a private key based on seed, account and address index
func (w *wallet) GetPrivateKeyFromSeed(seed []byte, account, addressIndex uint32) []byte {
var egldPath = bip32Path{
44 | hardened,
egldCoinType | hardened,
hardened, // account
hardened,
hardened, // addressIndex
}
egldPath[2] = account | hardened
egldPath[4] = addressIndex | hardened
keyData := derivePrivateKey(seed, egldPath)
return keyData.Key
}
// CreateSeedFromMnemonic creates a seed for a given mnemonic
func (w *wallet) CreateSeedFromMnemonic(mnemonic data.Mnemonic) []byte {
seed := bip39.NewSeed(string(mnemonic), "")
return seed
}
func derivePrivateKey(seed []byte, path bip32Path) *bip32 {
b := &bip32{}
digest := hmac.New(sha512.New, []byte("ed25519 seed"))
digest.Write(seed)
intermediary := digest.Sum(nil)
serializedKeyLen := 32
serializedChildIndexLen := 4
hardenedChildPadding := byte(0x00)
b.Key = intermediary[:serializedKeyLen]
b.ChainCode = intermediary[serializedKeyLen:]
for _, childIdx := range path {
buff := make([]byte, 1+serializedKeyLen+4)
buff[0] = hardenedChildPadding
copy(buff[1:1+serializedKeyLen], b.Key)
binary.BigEndian.PutUint32(buff[1+serializedKeyLen:1+serializedKeyLen+serializedChildIndexLen], childIdx)
digest = hmac.New(sha512.New, b.ChainCode)
digest.Write(buff)
intermediary = digest.Sum(nil)
b.Key = intermediary[:serializedKeyLen]
b.ChainCode = intermediary[serializedKeyLen:]
}
return b
}
// GetAddressFromPrivateKey generates the bech32 address from a private key
func (w *wallet) GetAddressFromPrivateKey(privateKeyBytes []byte) (core.AddressHandler, error) {
privateKey, err := keyGenerator.PrivateKeyFromByteArray(privateKeyBytes)
if err != nil {
return nil, err
}
publicKey := privateKey.GeneratePublic()
publicKeyBytes, err := publicKey.ToByteArray()
if err != nil {
return nil, err
}
return data.NewAddressFromBytes(publicKeyBytes), nil
}
// LoadPrivateKeyFromJsonFile loads a password encrypted private key from a .json file
func (w *wallet) LoadPrivateKeyFromJsonFile(filename string, password string) ([]byte, error) {
buff, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
key := &encryptedKeyJSONV4{}
err = json.Unmarshal(buff, key)
if err != nil {
return nil, err
}
mac, err := hex.DecodeString(key.Crypto.MAC)
if err != nil {
return nil, err
}
iv, err := hex.DecodeString(key.Crypto.CipherParams.IV)
if err != nil {
return nil, err
}
cipherText, err := hex.DecodeString(key.Crypto.CipherText)
if err != nil {
return nil, err
}
salt, err := hex.DecodeString(key.Crypto.KDFParams.Salt)
if err != nil {
return nil, err
}
derivedKey, err := scrypt.Key([]byte(password), salt,
key.Crypto.KDFParams.N,
key.Crypto.KDFParams.R,
key.Crypto.KDFParams.P,
key.Crypto.KDFParams.DkLen)
if err != nil {
return nil, err
}
hash := hmac.New(sha256.New, derivedKey[16:32])
_, err = hash.Write(cipherText)
if err != nil {
return nil, err
}
sha := hash.Sum(nil)
if !bytes.Equal(sha, mac) {
return nil, ErrWrongPassword
}
aesBlock, err := aes.NewCipher(derivedKey[:16])
if err != nil {
return nil, err
}
stream := cipher.NewCTR(aesBlock, iv)
decryptedData := make([]byte, len(cipherText))
stream.XORKeyStream(decryptedData, cipherText)
if key.Kind != mnemonicKind { // wallets with the old JSON format
return w.secretKeyAfterChecks(key, decryptedData)
} else {
return w.secretKeyFromMnemonic(decryptedData), nil
}
}
func (w *wallet) secretKeyAfterChecks(key *encryptedKeyJSONV4, secretKey []byte) ([]byte, error) {
if len(secretKey) > 32 {
secretKey = secretKey[:32]
}
address, errGetAddr := w.GetAddressFromPrivateKey(secretKey)
if errGetAddr != nil {
return nil, errGetAddr
}
addressAsBech32String, err := address.AddressAsBech32String()
if err != nil {
return nil, err
}
isSameAccount := hex.EncodeToString(address.AddressBytes()) == key.Address &&
addressAsBech32String == key.Bech32
if !isSameAccount {
return nil, ErrDifferentAccountRecovered
}
return secretKey, nil
}
func (w *wallet) secretKeyFromMnemonic(mnemonic []byte) []byte {
return w.GetPrivateKeyFromMnemonic(data.Mnemonic(mnemonic), 0, 0)
}
// SavePrivateKeyToJsonFile saves a password encrypted private key to a .json file
func (w *wallet) SavePrivateKeyToJsonFile(privateKey []byte, password string, filename string) error {
salt := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, salt)
if err != nil {
return err
}
derivedKey, err := scrypt.Key([]byte(password), salt, scryptN, scryptR, scryptP, scryptDKLen)
if err != nil {
return err
}
encryptKey := derivedKey[:16]
iv := make([]byte, aes.BlockSize) // 16
_, err = io.ReadFull(rand.Reader, iv)
if err != nil {
return err
}
aesBlock, err := aes.NewCipher(encryptKey)
if err != nil {
return err
}
stream := cipher.NewCTR(aesBlock, iv)
cipherText := make([]byte, len(privateKey))
stream.XORKeyStream(cipherText, privateKey)
hash := hmac.New(sha256.New, derivedKey[16:32])
_, err = hash.Write(cipherText)
if err != nil {
return err
}
mac := hash.Sum(nil)
address, err := w.GetAddressFromPrivateKey(privateKey)
if err != nil {
return err
}
addressAsBech32String, err := address.AddressAsBech32String()
if err != nil {
return err
}
keystoreJson := &encryptedKeyJSONV4{
Bech32: addressAsBech32String,
Address: hex.EncodeToString(address.AddressBytes()),
Version: keystoreVersion,
Id: uuid.New(),
}
keystoreJson.Crypto.CipherParams.IV = hex.EncodeToString(iv)
keystoreJson.Crypto.Cipher = "aes-128-ctr"
keystoreJson.Crypto.CipherText = hex.EncodeToString(cipherText)
keystoreJson.Crypto.KDF = keyHeaderKDF
keystoreJson.Crypto.MAC = hex.EncodeToString(mac)
keystoreJson.Crypto.KDFParams.N = scryptN
keystoreJson.Crypto.KDFParams.R = scryptR
keystoreJson.Crypto.KDFParams.P = scryptP
keystoreJson.Crypto.KDFParams.DkLen = scryptDKLen
keystoreJson.Crypto.KDFParams.Salt = hex.EncodeToString(salt)
buff, err := json.Marshal(keystoreJson)
if err != nil {
return err
}
return os.WriteFile(filename, buff, 0644)
}
// LoadPrivateKeyFromPemFile loads a private key from a .pem file
func (w *wallet) LoadPrivateKeyFromPemFile(filename string) ([]byte, error) {
buff, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return w.LoadPrivateKeyFromPemData(buff)
}
// LoadPrivateKeyFromPemData returns the private key from decoded pem data
func (w *wallet) LoadPrivateKeyFromPemData(buff []byte) ([]byte, error) {
blk, _ := pem.Decode(buff)
if blk == nil {
return nil, ErrInvalidPemFile
}
privKey := blk.Bytes
if len(privKey) > addressLen*2 {
privKey = privKey[:addressLen*2]
}
return hex.DecodeString(string(privKey))
}
// SavePrivateKeyToPemFile saves the private key in a .pem file
func (w *wallet) SavePrivateKeyToPemFile(privateKey []byte, filename string) error {
address, err := w.GetAddressFromPrivateKey(privateKey)
if err != nil {
return err
}
if len(privateKey) == addressLen {
privateKey = append(privateKey, address.AddressBytes()...)
}
addressAsBech32String, err := address.AddressAsBech32String()
if err != nil {
return err
}
blk := pem.Block{
Type: "PRIVATE KEY for " + addressAsBech32String,
Bytes: []byte(hex.EncodeToString(privateKey)),
}
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
return pem.Encode(file, &blk)
}