-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdna_sdk.go
544 lines (521 loc) · 13.5 KB
/
dna_sdk.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright 2019 DNA Dev team
//
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ontology is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ontology. If not, see <http://www.gnu.org/licenses/>.
*/
//DNA sdk in golang. Using for operation with ontology
package DNA_go_sdk
import (
"encoding/hex"
"fmt"
"github.com/DNAProject/DNA-go-sdk/bip44"
"github.com/DNAProject/DNA/smartcontract/event"
"github.com/ontio/go-bip32"
"github.com/tyler-smith/go-bip39"
"io"
"math/rand"
"time"
"github.com/DNAProject/DNA-go-sdk/client"
common3 "github.com/DNAProject/DNA-go-sdk/common"
"github.com/DNAProject/DNA-go-sdk/utils"
"github.com/DNAProject/DNA/common"
common2 "github.com/DNAProject/DNA/common"
"github.com/DNAProject/DNA/common/constants"
"github.com/DNAProject/DNA/core/payload"
"github.com/DNAProject/DNA/core/types"
"github.com/ontio/ontology-crypto/keypair"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
//DNASdk is the main struct for user
type DNASdk struct {
client.ClientMgr
Native *NativeContract
NeoVM *NeoVMContract
}
//NewDNASdk return DNASdk.
func NewDNASdk() *DNASdk {
dnaSdk := &DNASdk{}
native := newNativeContract(dnaSdk)
dnaSdk.Native = native
neoVM := newNeoVMContract(dnaSdk)
dnaSdk.NeoVM = neoVM
return dnaSdk
}
//CreateWallet return a new wallet
func (this *DNASdk) CreateWallet(walletFile string) (*Wallet, error) {
if utils.IsFileExist(walletFile) {
return nil, fmt.Errorf("wallet:%s has already exist", walletFile)
}
return NewWallet(walletFile), nil
}
//OpenWallet return a wallet instance
func (this *DNASdk) OpenWallet(walletFile string) (*Wallet, error) {
return OpenWallet(walletFile)
}
func ParseNativeTxPayload(raw []byte) (map[string]interface{}, error) {
tx, err := types.TransactionFromRawBytes(raw)
if err != nil {
return nil, err
}
invokeCode, ok := tx.Payload.(*payload.InvokeCode)
if !ok {
return nil, fmt.Errorf("error payload")
}
code := invokeCode.Code
return ParsePayload(code)
}
func ParsePayload(code []byte) (map[string]interface{}, error) {
l := len(code)
if l > 44 && string(code[l-22:]) == "System.Native.Invoke" {
//46 = 22 "System.Native.Invoke"
// +1 length
// +1 SYSCALL
// +1 version
// +20 address
// +1 length
//TODO if version>15, there will be bug
if l > 54 && string(code[l-46-8:l-46]) == "transfer" {
param := make([]common3.StateInfo, 0)
source := common.NewZeroCopySource(code)
for {
zeroByte, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
if zeroByte != 0 {
break
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
amount, err := getValue(source)
if err != nil {
return nil, err
}
state := common3.StateInfo{
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
param = append(param, state)
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
var isend bool
if isend, err = isEnd(source); err != nil {
return nil, err
}
if isend {
break
}
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transfer"
res["contractAddress"] = contractAddress
res["param"] = param
if contractAddress == GAS_CONTRACT_ADDRESS {
res["asset"] = "gas"
}
return res, nil
} else if l > 58 && string(code[l-46-12:l-46]) == "transferFrom" {
source := common.NewZeroCopySource(code)
//ignore 00
_, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
sender, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
amount, err := getValue(source)
if err != nil {
return nil, err
}
tf := common3.TransferFromInfo{
Sender: sender.ToBase58(),
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transferFrom"
res["contractAddress"] = contractAddress
res["param"] = tf
if contractAddress == GAS_CONTRACT_ADDRESS {
res["asset"] = "gas"
}
return res, nil
}
}
return nil, fmt.Errorf("not native transfer and transferFrom transaction")
}
func getValue(source *common.ZeroCopySource) (uint64, error) {
var amount = uint64(0)
zeroByte, eof := source.NextByte()
if eof {
return 0, io.ErrUnexpectedEOF
}
if zeroByte == 0 {
amount = 0
} else if zeroByte >= 0x51 && zeroByte <= 0x5f {
b := common.BigIntFromNeoBytes([]byte{zeroByte})
amount = b.Uint64() - 0x50
} else {
source.BackUp(1)
amountBytes, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return 0, io.ErrUnexpectedEOF
}
amount = common.BigIntFromNeoBytes(amountBytes).Uint64()
}
return amount, nil
}
func isEnd(source *common.ZeroCopySource) (bool, error) {
by, eof := source.NextByte()
if eof {
return true, io.EOF
}
if by == 0x00 || by >= 0x14 && by < 0x51 {
source.BackUp(1)
return false, nil
} else {
if by >= 0x51 && by <= 0x5f {
return true, nil
} else {
_, _, irregular, eof := source.NextVarUint()
if irregular || eof {
return true, io.ErrUnexpectedEOF
}
return true, nil
}
}
}
func readAddress(source *common.ZeroCopySource) (common2.Address, error) {
senderBytes, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return common.ADDRESS_EMPTY, io.ErrUnexpectedEOF
}
sender, err := utils.AddressParseFromBytes(senderBytes)
if err != nil {
return common.ADDRESS_EMPTY, err
}
return sender, nil
}
func ignoreOpCode(source *common.ZeroCopySource) error {
s := source.Size()
start := source.Pos()
for {
if source.Pos() >= s {
return nil
}
by, eof := source.NextByte()
if eof {
return io.EOF
}
if OPCODE_IN_PAYLOAD[by] {
continue
} else {
if start < source.Pos() {
source.BackUp(1)
}
return nil
}
}
}
func (this *DNASdk) GenerateMnemonicCodesStr() (string, error) {
entropy, err := bip39.NewEntropy(128)
if err != nil {
return "", err
}
return bip39.NewMnemonic(entropy)
}
func (this *DNASdk) GetPrivateKeyFromMnemonicCodesStrBip44(mnemonicCodesStr string, index uint32) ([]byte, error) {
if mnemonicCodesStr == "" {
return nil, fmt.Errorf("mnemonicCodesStr should not be nil")
}
//address_index
if index < 0 {
return nil, fmt.Errorf("index should be bigger than 0")
}
seed := bip39.NewSeed(mnemonicCodesStr, "")
masterKey, err := bip32.NewMasterKey(seed)
if err != nil {
return nil, err
}
//m / purpose' / coin_type' / account' / change / address_index
//coin type 1024'
coin := 0x80000400
//account 0'
account := 0x80000000
key, err := bip44.NewKeyFromMasterKey(masterKey, uint32(coin), uint32(account), 0, index)
if err != nil {
return nil, err
}
keyBytes, err := key.Serialize()
if err != nil {
return nil, err
}
return keyBytes[46:78], nil
}
//NewInvokeTransaction return smart contract invoke transaction
func (this *DNASdk) NewInvokeTransaction(gasPrice, gasLimit uint64, invokeCode []byte) *types.MutableTransaction {
invokePayload := &payload.InvokeCode{
Code: invokeCode,
}
tx := &types.MutableTransaction{
GasPrice: gasPrice,
GasLimit: gasLimit,
TxType: types.InvokeNeo,
Nonce: rand.Uint32(),
Payload: invokePayload,
Sigs: make([]types.Sig, 0, 0),
}
return tx
}
func (this *DNASdk) SignToTransaction(tx *types.MutableTransaction, signer Signer) error {
if tx.Payer == common.ADDRESS_EMPTY {
account, ok := signer.(*Account)
if ok {
tx.Payer = account.Address
}
}
for _, sigs := range tx.Sigs {
if utils.PubKeysEqual([]keypair.PublicKey{signer.GetPublicKey()}, sigs.PubKeys) {
//have already signed
return nil
}
}
txHash := tx.Hash()
sigData, err := signer.Sign(txHash.ToArray())
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
if tx.Sigs == nil {
tx.Sigs = make([]types.Sig, 0)
}
tx.Sigs = append(tx.Sigs, types.Sig{
PubKeys: []keypair.PublicKey{signer.GetPublicKey()},
M: 1,
SigData: [][]byte{sigData},
})
return nil
}
func (this *DNASdk) MultiSignToTransaction(tx *types.MutableTransaction, m uint16, pubKeys []keypair.PublicKey, signer Signer) error {
pkSize := len(pubKeys)
if m == 0 || int(m) > pkSize || pkSize > constants.MULTI_SIG_MAX_PUBKEY_SIZE {
return fmt.Errorf("both m and number of pub key must larger than 0, and small than %d, and m must smaller than pub key number", constants.MULTI_SIG_MAX_PUBKEY_SIZE)
}
validPubKey := false
for _, pk := range pubKeys {
if keypair.ComparePublicKey(pk, signer.GetPublicKey()) {
validPubKey = true
break
}
}
if !validPubKey {
return fmt.Errorf("invalid signer")
}
if tx.Payer == common.ADDRESS_EMPTY {
payer, err := types.AddressFromMultiPubKeys(pubKeys, int(m))
if err != nil {
return fmt.Errorf("AddressFromMultiPubKeys error:%s", err)
}
tx.Payer = payer
}
txHash := tx.Hash()
if len(tx.Sigs) == 0 {
tx.Sigs = make([]types.Sig, 0)
}
sigData, err := signer.Sign(txHash.ToArray())
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
hasMutilSig := false
for i, sigs := range tx.Sigs {
if utils.PubKeysEqual(sigs.PubKeys, pubKeys) {
hasMutilSig = true
if utils.HasAlreadySig(txHash.ToArray(), signer.GetPublicKey(), sigs.SigData) {
break
}
sigs.SigData = append(sigs.SigData, sigData)
tx.Sigs[i] = sigs
break
}
}
if !hasMutilSig {
tx.Sigs = append(tx.Sigs, types.Sig{
PubKeys: pubKeys,
M: m,
SigData: [][]byte{sigData},
})
}
return nil
}
func (this *DNASdk) GetTxData(tx *types.MutableTransaction) (string, error) {
txData, err := tx.IntoImmutable()
if err != nil {
return "", fmt.Errorf("IntoImmutable error:%s", err)
}
sink := common2.ZeroCopySink{}
txData.Serialization(&sink)
rawtx := hex.EncodeToString(sink.Bytes())
return rawtx, nil
}
type TransferEvent struct {
FuncName string
From string
To string
Amount uint64
}
func (this *DNASdk) ParseNaitveTransferEvent(event *event.NotifyEventInfo) (*TransferEvent, error) {
if event == nil {
return nil, fmt.Errorf("event is nil")
}
state, ok := event.States.([]interface{})
if !ok {
return nil, fmt.Errorf("state.States is not []interface")
}
if len(state) != 4 {
return nil, fmt.Errorf("state length is not 4")
}
funcName, ok := state[0].(string)
if !ok {
return nil, fmt.Errorf("state.States[0] is not string")
}
if funcName != "transfer" {
return nil, fmt.Errorf("funcName is not transfer")
} else {
from, ok := state[1].(string)
if !ok {
return nil, fmt.Errorf("state[1] is not string")
}
to, ok := state[2].(string)
if !ok {
return nil, fmt.Errorf("state[2] is not string")
}
amount, ok := state[3].(uint64)
if !ok {
return nil, fmt.Errorf("state[3] is not uint64")
}
return &TransferEvent{
FuncName: "transfer",
From: from,
To: to,
Amount: uint64(amount),
}, nil
}
}
func (this *DNASdk) GetMutableTx(rawTx string) (*types.MutableTransaction, error) {
txData, err := hex.DecodeString(rawTx)
if err != nil {
return nil, fmt.Errorf("RawTx hex decode error:%s", err)
}
tx, err := types.TransactionFromRawBytes(txData)
if err != nil {
return nil, fmt.Errorf("TransactionFromRawBytes error:%s", err)
}
mutTx, err := tx.IntoMutable()
if err != nil {
return nil, fmt.Errorf("IntoMutable error:%s", err)
}
return mutTx, nil
}
func (this *DNASdk) GetMultiAddr(pubkeys []keypair.PublicKey, m int) (string, error) {
addr, err := types.AddressFromMultiPubKeys(pubkeys, m)
if err != nil {
return "", fmt.Errorf("GetMultiAddrs error:%s", err)
}
return addr.ToBase58(), nil
}
func (this *DNASdk) GetAdddrByPubKey(pubKey keypair.PublicKey) string {
address := types.AddressFromPubKey(pubKey)
return address.ToBase58()
}