forked from DNAProject/DNA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ont.go
934 lines (870 loc) · 25.7 KB
/
ont.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
/*
* Copyright (C) 2018 The DNA Authors
* This file is part of The DNA library.
*
* The DNA 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 DNA 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 DNA. If not, see <http://www.gnu.org/licenses/>.
*/
package utils
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/dnaproject2/DNA/account"
"github.com/dnaproject2/DNA/common"
"github.com/dnaproject2/DNA/common/constants"
"github.com/dnaproject2/DNA/common/serialization"
"github.com/dnaproject2/DNA/core/payload"
"github.com/dnaproject2/DNA/core/signature"
"github.com/dnaproject2/DNA/core/types"
cutils "github.com/dnaproject2/DNA/core/utils"
httpcom "github.com/dnaproject2/DNA/http/base/common"
rpccommon "github.com/dnaproject2/DNA/http/base/common"
"github.com/dnaproject2/DNA/smartcontract/service/native/ont"
"github.com/dnaproject2/DNA/smartcontract/service/native/utils"
"github.com/dnaproject2/DNA/smartcontract/service/wasmvm"
cstates "github.com/dnaproject2/DNA/smartcontract/states"
"github.com/dnaproject2/DNA/vm/wasmvm/exec"
"github.com/ontio/ontology-crypto/keypair"
sig "github.com/ontio/ontology-crypto/signature"
"math/rand"
"sort"
"strconv"
"strings"
"time"
)
const (
VERSION_TRANSACTION = byte(0)
VERSION_CONTRACT_ONT = byte(0)
VERSION_CONTRACT_ONG = byte(0)
CONTRACT_TRANSFER = "transfer"
CONTRACT_TRANSFER_FROM = "transferFrom"
CONTRACT_APPROVE = "approve"
ASSET_ONT = "ont"
ASSET_ONG = "ong"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
//Return balance of address in base58 code
func GetBalance(address string) (*httpcom.BalanceOfRsp, error) {
result, ontErr := sendRpcRequest("getbalance", []interface{}{address})
if ontErr != nil {
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid address:%s", address)
}
return nil, ontErr.Error
}
balance := &httpcom.BalanceOfRsp{}
err := json.Unmarshal(result, balance)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal error:%s", err)
}
return balance, nil
}
func GetAccountBalance(address, asset string) (uint64, error) {
balances, err := GetBalance(address)
if err != nil {
return 0, err
}
var balance uint64
switch strings.ToLower(asset) {
case "ont":
balance, err = strconv.ParseUint(balances.Ont, 10, 64)
case "ong":
balance, err = strconv.ParseUint(balances.Ong, 10, 64)
default:
return 0, fmt.Errorf("unsupport asset:%s", asset)
}
if err != nil {
return 0, err
}
return balance, nil
}
func GetAllowance(asset, from, to string) (string, error) {
result, ontErr := sendRpcRequest("getallowance", []interface{}{asset, from, to})
if ontErr != nil {
return "", ontErr.Error
}
balance := ""
err := json.Unmarshal(result, &balance)
if err != nil {
return "", fmt.Errorf("json.Unmarshal error:%s", err)
}
return balance, nil
}
//Transfer ont|ong from account to another account
func Transfer(gasPrice, gasLimit uint64, signer *account.Account, asset, from, to string, amount uint64) (string, error) {
mutable, err := TransferTx(gasPrice, gasLimit, asset, signer.Address.ToBase58(), to, amount)
if err != nil {
return "", err
}
err = SignTransaction(signer, mutable)
if err != nil {
return "", fmt.Errorf("SignTransaction error:%s", err)
}
tx, err := mutable.IntoImmutable()
if err != nil {
return "", fmt.Errorf("convert immutable transaction error:%s", err)
}
txHash, err := SendRawTransaction(tx)
if err != nil {
return "", fmt.Errorf("SendTransaction error:%s", err)
}
return txHash, nil
}
func TransferFrom(gasPrice, gasLimit uint64, signer *account.Account, asset, sender, from, to string, amount uint64) (string, error) {
mutable, err := TransferFromTx(gasPrice, gasLimit, asset, sender, from, to, amount)
if err != nil {
return "", err
}
err = SignTransaction(signer, mutable)
if err != nil {
return "", fmt.Errorf("SignTransaction error:%s", err)
}
tx, err := mutable.IntoImmutable()
if err != nil {
return "", fmt.Errorf("convert to immutable transaction error:%s", err)
}
txHash, err := SendRawTransaction(tx)
if err != nil {
return "", fmt.Errorf("SendTransaction error:%s", err)
}
return txHash, nil
}
func Approve(gasPrice, gasLimit uint64, signer *account.Account, asset, from, to string, amount uint64) (string, error) {
mutable, err := ApproveTx(gasPrice, gasLimit, asset, from, to, amount)
if err != nil {
return "", err
}
err = SignTransaction(signer, mutable)
if err != nil {
return "", fmt.Errorf("SignTransaction error:%s", err)
}
tx, err := mutable.IntoImmutable()
if err != nil {
return "", fmt.Errorf("convert to immutable transaction error:%s", err)
}
txHash, err := SendRawTransaction(tx)
if err != nil {
return "", fmt.Errorf("SendTransaction error:%s", err)
}
return txHash, nil
}
func ApproveTx(gasPrice, gasLimit uint64, asset string, from, to string, amount uint64) (*types.MutableTransaction, error) {
fromAddr, err := common.AddressFromBase58(from)
if err != nil {
return nil, fmt.Errorf("from address:%s invalid:%s", from, err)
}
toAddr, err := common.AddressFromBase58(to)
if err != nil {
return nil, fmt.Errorf("To address:%s invalid:%s", to, err)
}
var state = &ont.State{
From: fromAddr,
To: toAddr,
Value: amount,
}
var version byte
var contractAddr common.Address
switch strings.ToLower(asset) {
case ASSET_ONT:
version = VERSION_CONTRACT_ONT
contractAddr = utils.OntContractAddress
case ASSET_ONG:
version = VERSION_CONTRACT_ONG
contractAddr = utils.OngContractAddress
default:
return nil, fmt.Errorf("Unsupport asset:%s", asset)
}
invokeCode, err := cutils.BuildNativeInvokeCode(contractAddr, version, CONTRACT_APPROVE, []interface{}{state})
if err != nil {
return nil, fmt.Errorf("build invoke code error:%s", err)
}
mutableTx := NewInvokeTransaction(gasPrice, gasLimit, invokeCode)
return mutableTx, nil
}
func TransferTx(gasPrice, gasLimit uint64, asset, from, to string, amount uint64) (*types.MutableTransaction, error) {
fromAddr, err := common.AddressFromBase58(from)
if err != nil {
return nil, fmt.Errorf("from address:%s invalid:%s", from, err)
}
toAddr, err := common.AddressFromBase58(to)
if err != nil {
return nil, fmt.Errorf("to address:%s invalid:%s", to, err)
}
var sts []*ont.State
sts = append(sts, &ont.State{
From: fromAddr,
To: toAddr,
Value: amount,
})
var version byte
var contractAddr common.Address
switch strings.ToLower(asset) {
case ASSET_ONT:
version = VERSION_CONTRACT_ONT
contractAddr = utils.OntContractAddress
case ASSET_ONG:
version = VERSION_CONTRACT_ONG
contractAddr = utils.OngContractAddress
default:
return nil, fmt.Errorf("unsupport asset:%s", asset)
}
invokeCode, err := cutils.BuildNativeInvokeCode(contractAddr, version, CONTRACT_TRANSFER, []interface{}{sts})
if err != nil {
return nil, fmt.Errorf("build invoke code error:%s", err)
}
mutableTx := NewInvokeTransaction(gasPrice, gasLimit, invokeCode)
return mutableTx, nil
}
func TransferFromTx(gasPrice, gasLimit uint64, asset, sender, from, to string, amount uint64) (*types.MutableTransaction, error) {
senderAddr, err := common.AddressFromBase58(sender)
if err != nil {
return nil, fmt.Errorf("sender address:%s invalid:%s", to, err)
}
fromAddr, err := common.AddressFromBase58(from)
if err != nil {
return nil, fmt.Errorf("from address:%s invalid:%s", from, err)
}
toAddr, err := common.AddressFromBase58(to)
if err != nil {
return nil, fmt.Errorf("to address:%s invalid:%s", to, err)
}
transferFrom := &ont.TransferFrom{
Sender: senderAddr,
From: fromAddr,
To: toAddr,
Value: amount,
}
var version byte
var contractAddr common.Address
switch strings.ToLower(asset) {
case ASSET_ONT:
version = VERSION_CONTRACT_ONT
contractAddr = utils.OntContractAddress
case ASSET_ONG:
version = VERSION_CONTRACT_ONG
contractAddr = utils.OngContractAddress
default:
return nil, fmt.Errorf("unsupport asset:%s", asset)
}
invokeCode, err := cutils.BuildNativeInvokeCode(contractAddr, version, CONTRACT_TRANSFER_FROM, []interface{}{transferFrom})
if err != nil {
return nil, fmt.Errorf("build invoke code error:%s", err)
}
mutableTx := NewInvokeTransaction(gasPrice, gasLimit, invokeCode)
return mutableTx, nil
}
//NewInvokeTransaction return smart contract invoke transaction
func NewInvokeTransaction(gasPrice, gasLimit uint64, invokeCode []byte) *types.MutableTransaction {
invokePayload := &payload.InvokeCode{
Code: invokeCode,
}
tx := &types.MutableTransaction{
GasPrice: gasPrice,
GasLimit: gasLimit,
TxType: types.Invoke,
Nonce: rand.Uint32(),
Payload: invokePayload,
Sigs: make([]types.Sig, 0, 0),
}
return tx
}
func SignTransaction(signer *account.Account, tx *types.MutableTransaction) error {
if tx.Payer == common.ADDRESS_EMPTY {
tx.Payer = signer.Address
}
txHash := tx.Hash()
sigData, err := Sign(txHash.ToArray(), signer)
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
hasSig := false
for i, sig := range tx.Sigs {
if len(sig.PubKeys) == 1 && pubKeysEqual(sig.PubKeys, []keypair.PublicKey{signer.PublicKey}) {
if hasAlreadySig(txHash.ToArray(), signer.PublicKey, sig.SigData) {
//has already signed
return nil
}
hasSig = true
//replace
tx.Sigs[i].SigData = [][]byte{sigData}
}
}
if !hasSig {
tx.Sigs = append(tx.Sigs, types.Sig{
PubKeys: []keypair.PublicKey{signer.PublicKey},
M: 1,
SigData: [][]byte{sigData},
})
}
return nil
}
func MultiSigTransaction(mutTx *types.MutableTransaction, m uint16, pubKeys []keypair.PublicKey, signer *account.Account) error {
pkSize := len(pubKeys)
if m == 0 || int(m) > pkSize || pkSize > constants.MULTI_SIG_MAX_PUBKEY_SIZE {
return fmt.Errorf("invalid params")
}
validPubKey := false
for _, pk := range pubKeys {
if keypair.ComparePublicKey(pk, signer.PublicKey) {
validPubKey = true
break
}
}
if !validPubKey {
return fmt.Errorf("invalid signer")
}
if mutTx.Payer == common.ADDRESS_EMPTY {
payer, err := types.AddressFromMultiPubKeys(pubKeys, int(m))
if err != nil {
return fmt.Errorf("AddressFromMultiPubKeys error:%s", err)
}
mutTx.Payer = payer
}
if len(mutTx.Sigs) == 0 {
mutTx.Sigs = make([]types.Sig, 0)
}
txHash := mutTx.Hash()
sigData, err := Sign(txHash.ToArray(), signer)
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
hasMutilSig := false
for i, sigs := range mutTx.Sigs {
if !pubKeysEqual(sigs.PubKeys, pubKeys) {
continue
}
hasMutilSig = true
if hasAlreadySig(txHash.ToArray(), signer.PublicKey, sigs.SigData) {
break
}
sigs.SigData = append(sigs.SigData, sigData)
mutTx.Sigs[i] = sigs
break
}
if !hasMutilSig {
mutTx.Sigs = append(mutTx.Sigs, types.Sig{
PubKeys: pubKeys,
M: uint16(m),
SigData: [][]byte{sigData},
})
}
return nil
}
func hasAlreadySig(data []byte, pk keypair.PublicKey, sigDatas [][]byte) bool {
for _, sigData := range sigDatas {
err := signature.Verify(pk, data, sigData)
if err == nil {
return true
}
}
return false
}
func pubKeysEqual(pks1, pks2 []keypair.PublicKey) bool {
if len(pks1) != len(pks2) {
return false
}
size := len(pks1)
if size == 0 {
return true
}
pkstr1 := make([]string, 0, size)
for _, pk := range pks1 {
pkstr1 = append(pkstr1, hex.EncodeToString(keypair.SerializePublicKey(pk)))
}
pkstr2 := make([]string, 0, size)
for _, pk := range pks2 {
pkstr2 = append(pkstr2, hex.EncodeToString(keypair.SerializePublicKey(pk)))
}
sort.Strings(pkstr1)
sort.Strings(pkstr2)
for i := 0; i < size; i++ {
if pkstr1[i] != pkstr2[i] {
return false
}
}
return true
}
//Sign sign return the signature to the data of private key
func Sign(data []byte, signer *account.Account) ([]byte, error) {
s, err := sig.Sign(signer.SigScheme, signer.PrivateKey, data, nil)
if err != nil {
return nil, err
}
sigData, err := sig.Serialize(s)
if err != nil {
return nil, fmt.Errorf("sig.Serialize error:%s", err)
}
return sigData, nil
}
//SendRawTransaction send a transaction to DNA network, and return hash of the transaction
func SendRawTransaction(tx *types.Transaction) (string, error) {
var buffer bytes.Buffer
err := tx.Serialize(&buffer)
if err != nil {
return "", fmt.Errorf("serialize error:%s", err)
}
txData := hex.EncodeToString(buffer.Bytes())
return SendRawTransactionData(txData)
}
func SendRawTransactionData(txData string) (string, error) {
data, ontErr := sendRpcRequest("sendrawtransaction", []interface{}{txData})
if ontErr != nil {
return "", ontErr.Error
}
hexHash := ""
err := json.Unmarshal(data, &hexHash)
if err != nil {
return "", fmt.Errorf("json.Unmarshal hash:%s error:%s", data, err)
}
return hexHash, nil
}
func PrepareSendRawTransaction(txData string) (*cstates.PreExecResult, error) {
data, ontErr := sendRpcRequest("sendrawtransaction", []interface{}{txData, 1})
if ontErr != nil {
return nil, ontErr.Error
}
preResult := &cstates.PreExecResult{}
err := json.Unmarshal(data, &preResult)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal PreExecResult:%s error:%s", data, err)
}
return preResult, nil
}
//GetSmartContractEvent return smart contract event execute by invoke transaction by hex string code
func GetSmartContractEvent(txHash string) (*rpccommon.ExecuteNotify, error) {
data, ontErr := sendRpcRequest("getsmartcodeevent", []interface{}{txHash})
if ontErr != nil {
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid TxHash:%s", txHash)
}
return nil, ontErr.Error
}
notifies := &rpccommon.ExecuteNotify{}
err := json.Unmarshal(data, ¬ifies)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal SmartContactEvent:%s error:%s", data, err)
}
return notifies, nil
}
func GetSmartContractEventInfo(txHash string) ([]byte, error) {
data, ontErr := sendRpcRequest("getsmartcodeevent", []interface{}{txHash})
if ontErr == nil {
return data, nil
}
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid TxHash:%s", txHash)
}
return nil, ontErr.Error
}
func GetRawTransaction(txHash string) ([]byte, error) {
data, ontErr := sendRpcRequest("getrawtransaction", []interface{}{txHash, 1})
if ontErr == nil {
return data, nil
}
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid TxHash:%s", txHash)
}
return nil, ontErr.Error
}
func GetBlock(hashOrHeight interface{}) ([]byte, error) {
data, ontErr := sendRpcRequest("getblock", []interface{}{hashOrHeight, 1})
if ontErr == nil {
return data, nil
}
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid block hash or block height:%v", hashOrHeight)
}
return nil, ontErr.Error
}
func GetNetworkId() (uint32, error) {
data, ontErr := sendRpcRequest("getnetworkid", []interface{}{})
if ontErr != nil {
return 0, ontErr.Error
}
var networkId uint32
err := json.Unmarshal(data, &networkId)
if err != nil {
return 0, fmt.Errorf("json.Unmarshal networkId error:%s", err)
}
return networkId, nil
}
func GetBlockData(hashOrHeight interface{}) ([]byte, error) {
data, ontErr := sendRpcRequest("getblock", []interface{}{hashOrHeight})
if ontErr != nil {
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return nil, fmt.Errorf("invalid block hash or block height:%v", hashOrHeight)
}
return nil, ontErr.Error
}
hexStr := ""
err := json.Unmarshal(data, &hexStr)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal error:%s", err)
}
blockData, err := hex.DecodeString(hexStr)
if err != nil {
return nil, fmt.Errorf("hex.DecodeString error:%s", err)
}
return blockData, nil
}
func GetBlockCount() (uint32, error) {
data, ontErr := sendRpcRequest("getblockcount", []interface{}{})
if ontErr != nil {
return 0, ontErr.Error
}
num := uint32(0)
err := json.Unmarshal(data, &num)
if err != nil {
return 0, fmt.Errorf("json.Unmarshal:%s error:%s", data, err)
}
return num, nil
}
func GetTxHeight(txHash string) (uint32, error) {
data, ontErr := sendRpcRequest("getblockheightbytxhash", []interface{}{txHash})
if ontErr != nil {
switch ontErr.ErrorCode {
case ERROR_INVALID_PARAMS:
return 0, fmt.Errorf("cannot find tx by:%s", txHash)
}
return 0, ontErr.Error
}
height := uint32(0)
err := json.Unmarshal(data, &height)
if err != nil {
return 0, fmt.Errorf("json.Unmarshal error:%s", err)
}
return height, nil
}
func DeployContract(
gasPrice,
gasLimit uint64,
signer *account.Account,
needStorage bool,
code,
cname,
cversion,
cauthor,
cemail,
cdesc string) (string, error) {
c, err := hex.DecodeString(code)
if err != nil {
return "", fmt.Errorf("hex.DecodeString error:%s", err)
}
mutable := NewDeployCodeTransaction(gasPrice, gasLimit, c, needStorage, cname, cversion, cauthor, cemail, cdesc)
err = SignTransaction(signer, mutable)
if err != nil {
return "", err
}
tx, err := mutable.IntoImmutable()
if err != nil {
return "", fmt.Errorf("convert to immutable transation error:%v", err)
}
txHash, err := SendRawTransaction(tx)
if err != nil {
return "", fmt.Errorf("SendRawTransaction error:%s", err)
}
return txHash, nil
}
func PrepareDeployContract(
needStorage bool,
code,
cname,
cversion,
cauthor,
cemail,
cdesc string) (*cstates.PreExecResult, error) {
c, err := hex.DecodeString(code)
if err != nil {
return nil, fmt.Errorf("hex.DecodeString error:%s", err)
}
mutable := NewDeployCodeTransaction(0, 0, c, needStorage, cname, cversion, cauthor, cemail, cdesc)
tx, _ := mutable.IntoImmutable()
var buffer bytes.Buffer
err = tx.Serialize(&buffer)
if err != nil {
return nil, fmt.Errorf("tx serialize error:%s", err)
}
txData := hex.EncodeToString(buffer.Bytes())
return PrepareSendRawTransaction(txData)
}
func InvokeNativeContract(
gasPrice,
gasLimit uint64,
signer *account.Account,
contractAddress common.Address,
version byte,
method string,
params []interface{},
) (string, error) {
tx, err := httpcom.NewNativeInvokeTransaction(gasPrice, gasLimit, contractAddress, version, method, params)
if err != nil {
return "", err
}
return InvokeSmartContract(signer, tx)
}
//Invoke wasm smart contract
//methodName is wasm contract action name
//paramType is Json or Raw format
//version should be greater than 0 (0 is reserved for test)
func InvokeWasmVMContract(
gasPrice,
gasLimit uint64,
siger *account.Account,
cversion byte, //version of contract
contractAddress common.Address,
method string,
paramType wasmvm.ParamType,
params []interface{}) (string, error) {
invokeCode, err := BuildWasmVMInvokeCode(contractAddress, method, paramType, cversion, params)
if err != nil {
return "", err
}
tx, err := httpcom.NewSmartContractTransaction(gasPrice, gasLimit, invokeCode)
if err != nil {
return "", err
}
return InvokeSmartContract(siger, tx)
}
//Invoke neo vm smart contract. if isPreExec is true, the invoke will not really execute
func InvokeNeoVMContract(
gasPrice,
gasLimit uint64,
signer *account.Account,
smartcodeAddress common.Address,
params []interface{}) (string, error) {
tx, err := httpcom.NewNeovmInvokeTransaction(gasPrice, gasLimit, smartcodeAddress, params)
if err != nil {
return "", err
}
return InvokeSmartContract(signer, tx)
}
//InvokeSmartContract is low level method to invoke contact.
func InvokeSmartContract(signer *account.Account, tx *types.MutableTransaction) (string, error) {
err := SignTransaction(signer, tx)
if err != nil {
return "", fmt.Errorf("SignTransaction error:%s", err)
}
immut, err := tx.IntoImmutable()
if err != nil {
return "", err
}
txHash, err := SendRawTransaction(immut)
if err != nil {
return "", fmt.Errorf("SendTransaction error:%s", err)
}
return txHash, nil
}
func PrepareInvokeNeoVMContract(
contractAddress common.Address,
params []interface{},
) (*cstates.PreExecResult, error) {
mutable, err := httpcom.NewNeovmInvokeTransaction(0, 0, contractAddress, params)
if err != nil {
return nil, err
}
tx, err := mutable.IntoImmutable()
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tx.Serialize(&buffer)
if err != nil {
return nil, fmt.Errorf("tx serialize error:%s", err)
}
txData := hex.EncodeToString(buffer.Bytes())
return PrepareSendRawTransaction(txData)
}
func PrepareInvokeCodeNeoVMContract(code []byte) (*cstates.PreExecResult, error) {
mutable, err := httpcom.NewSmartContractTransaction(0, 0, code)
if err != nil {
return nil, err
}
tx, err := mutable.IntoImmutable()
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tx.Serialize(&buffer)
if err != nil {
return nil, fmt.Errorf("tx serialize error:%s", err)
}
txData := hex.EncodeToString(buffer.Bytes())
return PrepareSendRawTransaction(txData)
}
func PrepareInvokeNativeContract(
contractAddress common.Address,
version byte,
method string,
params []interface{}) (*cstates.PreExecResult, error) {
mutable, err := httpcom.NewNativeInvokeTransaction(0, 0, contractAddress, version, method, params)
if err != nil {
return nil, err
}
tx, err := mutable.IntoImmutable()
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tx.Serialize(&buffer)
if err != nil {
return nil, fmt.Errorf("tx serialize error:%s", err)
}
txData := hex.EncodeToString(buffer.Bytes())
return PrepareSendRawTransaction(txData)
}
//NewDeployCodeTransaction return a smart contract deploy transaction instance
func NewDeployCodeTransaction(gasPrice, gasLimit uint64, code []byte, needStorage bool,
cname, cversion, cauthor, cemail, cdesc string) *types.MutableTransaction {
deployPayload := &payload.DeployCode{
Code: code,
NeedStorage: needStorage,
Name: cname,
Version: cversion,
Author: cauthor,
Email: cemail,
Description: cdesc,
}
tx := &types.MutableTransaction{
Version: VERSION_TRANSACTION,
TxType: types.Deploy,
Nonce: uint32(time.Now().Unix()),
Payload: deployPayload,
GasPrice: gasPrice,
GasLimit: gasLimit,
Sigs: make([]types.Sig, 0, 0),
}
return tx
}
//for wasm vm
//build param bytes for wasm contract
func buildWasmContractParam(params []interface{}, paramType wasmvm.ParamType) ([]byte, error) {
switch paramType {
case wasmvm.Json:
args := make([]exec.Param, len(params))
for i, param := range params {
switch param.(type) {
case string:
arg := exec.Param{Ptype: "string", Pval: param.(string)}
args[i] = arg
case int:
arg := exec.Param{Ptype: "int", Pval: strconv.Itoa(param.(int))}
args[i] = arg
case int64:
arg := exec.Param{Ptype: "int64", Pval: strconv.FormatInt(param.(int64), 10)}
args[i] = arg
case []int:
bf := bytes.NewBuffer(nil)
array := param.([]int)
for i, tmp := range array {
bf.WriteString(strconv.Itoa(tmp))
if i != len(array)-1 {
bf.WriteString(",")
}
}
arg := exec.Param{Ptype: "int_array", Pval: bf.String()}
args[i] = arg
case []int64:
bf := bytes.NewBuffer(nil)
array := param.([]int64)
for i, tmp := range array {
bf.WriteString(strconv.FormatInt(tmp, 10))
if i != len(array)-1 {
bf.WriteString(",")
}
}
arg := exec.Param{Ptype: "int_array", Pval: bf.String()}
args[i] = arg
default:
return nil, fmt.Errorf("not a supported type :%v\n", param)
}
}
bs, err := json.Marshal(exec.Args{args})
if err != nil {
return nil, err
}
return bs, nil
case wasmvm.Raw:
bf := bytes.NewBuffer(nil)
for _, param := range params {
switch param.(type) {
case string:
tmp := bytes.NewBuffer(nil)
serialization.WriteString(tmp, param.(string))
bf.Write(tmp.Bytes())
case int:
tmpBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(tmpBytes, uint32(param.(int)))
bf.Write(tmpBytes)
case int64:
tmpBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(tmpBytes, uint64(param.(int64)))
bf.Write(tmpBytes)
default:
return nil, fmt.Errorf("not a supported type :%v\n", param)
}
}
return bf.Bytes(), nil
default:
return nil, fmt.Errorf("unsupported type")
}
}
//BuildWasmVMInvokeCode return wasn vm invoke code
func BuildWasmVMInvokeCode(smartcodeAddress common.Address, methodName string, paramType wasmvm.ParamType, version byte, params []interface{}) ([]byte, error) {
contract := &cstates.ContractInvokeParam{}
contract.Address = smartcodeAddress
contract.Method = methodName
contract.Version = version
argbytes, err := buildWasmContractParam(params, paramType)
if err != nil {
return nil, fmt.Errorf("build wasm contract param failed:%s", err)
}
contract.Args = argbytes
bf := bytes.NewBuffer(nil)
contract.Serialize(bf)
return bf.Bytes(), nil
}
//ParseNeoVMContractReturnTypeBool return bool value of smart contract execute code.
func ParseNeoVMContractReturnTypeBool(hexStr string) (bool, error) {
return hexStr == "01", nil
}
//ParseNeoVMContractReturnTypeInteger return integer value of smart contract execute code.
func ParseNeoVMContractReturnTypeInteger(hexStr string) (int64, error) {
data, err := hex.DecodeString(hexStr)
if err != nil {
return 0, fmt.Errorf("hex.DecodeString error:%s", err)
}
return common.BigIntFromNeoBytes(data).Int64(), nil
}
//ParseNeoVMContractReturnTypeByteArray return []byte value of smart contract execute code.
func ParseNeoVMContractReturnTypeByteArray(hexStr string) (string, error) {
return hexStr, nil
}
//ParseNeoVMContractReturnTypeString return string value of smart contract execute code.
func ParseNeoVMContractReturnTypeString(hexStr string) (string, error) {
data, err := hex.DecodeString(hexStr)
if err != nil {
return "", fmt.Errorf("hex.DecodeString:%s error:%s", hexStr, err)
}
return string(data), nil
}