-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtransaction.go
1621 lines (1420 loc) · 46.1 KB
/
transaction.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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package zcncore
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/0chain/errors"
"github.com/0chain/gosdk/core/block"
"github.com/0chain/gosdk/core/common"
"github.com/0chain/gosdk/core/encryption"
"github.com/0chain/gosdk/core/transaction"
"github.com/0chain/gosdk/core/util"
"github.com/0chain/gosdk/core/zcncrypto"
"github.com/0chain/gosdk/zboxcore/blockchain"
"github.com/0chain/gosdk/zboxcore/sdk"
)
// compiler time check
var (
_ TransactionScheme = (*Transaction)(nil)
_ TransactionScheme = (*TransactionWithAuth)(nil)
)
var (
errNetwork = errors.New("", "network error. host not reachable")
errUserRejected = errors.New("", "rejected by user")
errAuthVerifyFailed = errors.New("", "verfication failed for auth response")
errAuthTimeout = errors.New("", "auth timed out")
errAddSignature = errors.New("", "error adding signature")
)
// TransactionCallback needs to be implemented by the caller for transaction related APIs
type TransactionCallback interface {
OnTransactionComplete(t *Transaction, status int)
OnVerifyComplete(t *Transaction, status int)
OnAuthComplete(t *Transaction, status int)
}
/*Confirmation - a data structure that provides the confirmation that a transaction is included into the block chain */
type confirmation struct {
Version string `json:"version"`
Hash string `json:"hash"`
BlockHash string `json:"block_hash"`
PreviousBlockHash string `json:"previous_block_hash"`
Transaction *transaction.Transaction `json:"txn,omitempty"`
CreationDate int64 `json:"creation_date,omitempty"`
MinerID string `json:"miner_id"`
Round int64 `json:"round"`
Status int `json:"transaction_status" msgpack:"sot"`
RoundRandomSeed int64 `json:"round_random_seed"`
MerkleTreeRoot string `json:"merkle_tree_root"`
MerkleTreePath *util.MTPath `json:"merkle_tree_path"`
ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"`
ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"`
}
type blockHeader struct {
Version string `json:"version,omitempty"`
CreationDate int64 `json:"creation_date,omitempty"`
Hash string `json:"hash,omitempty"`
MinerId string `json:"miner_id,omitempty"`
Round int64 `json:"round,omitempty"`
RoundRandomSeed int64 `json:"round_random_seed,omitempy"`
MerkleTreeRoot string `json:"merkle_tree_root,omitempty"`
StateHash string `json:"state_hash,omitempty"`
ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root,omitempty"`
NumTxns int64 `json:"num_txns,omitempty"`
}
type Transaction struct {
txn *transaction.Transaction
txnOut string
txnHash string
txnStatus int
txnError error
txnCb TransactionCallback
verifyStatus int
verifyOut string
verifyError error
}
// TransactionScheme implements few methods for block chain.
//
// Note: to be buildable on MacOSX all arguments should have names.
type TransactionScheme interface {
// SetTransactionCallback implements storing the callback
// used to call after the transaction or verification is completed
SetTransactionCallback(cb TransactionCallback) error
// Send implements sending token to a given clientid
Send(toClientID string, val int64, desc string) error
// StoreData implements store the data to blockchain
StoreData(data string) error
// ExecuteSmartContract impements the Faucet Smart contract
ExecuteSmartContract(address, methodName, jsoninput string, val int64) error
// ExecuteFaucetSCWallet impements the Faucet Smart contract for a given wallet
ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error
// GetTransactionHash implements retrieval of hash of the submitted transaction
GetTransactionHash() string
// LockTokens implements the lock token.
LockTokens(val int64, durationHr int64, durationMin int) error
// UnlockTokens implements unlocking of earlier locked tokens.
UnlockTokens(poolID string) error
//RegisterMultiSig registers a group wallet and subwallets with MultisigSC
RegisterMultiSig(walletstr, mswallet string) error
// SetTransactionHash implements verify a previous transation status
SetTransactionHash(hash string) error
// SetTransactionFee implements method to set the transaction fee
SetTransactionFee(txnFee int64) error
// Verify implements verify the transaction
Verify() error
// GetVerifyOutput implements the verifcation output from sharders
GetVerifyOutput() string
// GetTransactionError implements error string incase of transaction failure
GetTransactionError() string
// GetVerifyError implements error string incase of verify failure error
GetVerifyError() string
// Output of transaction.
Output() []byte
// vesting SC
VestingTrigger(poolID string) error
VestingStop(sr *VestingStopRequest) error
VestingUnlock(poolID string) error
VestingAdd(ar *VestingAddRequest, value int64) error
VestingDelete(poolID string) error
VestingUpdateConfig(vscc *VestingSCConfig) error
// Miner SC
MinerSCSettings(*MinerSCMinerInfo) error
MinerSCLock(minerID string, lock int64) error
MienrSCUnlock(minerID, poolID string) error
// Storage SC
FinalizeAllocation(allocID string, fee int64) error
CancelAllocation(allocID string, fee int64) error
CreateAllocation(car *CreateAllocationRequest, lock, fee int64) error //
CreateReadPool(fee int64) error
ReadPoolLock(allocID string, blobberID string, duration int64, lock, fee int64) error
ReadPoolUnlock(poolID string, fee int64) error
StakePoolLock(blobberID string, lock, fee int64) error
StakePoolUnlock(blobberID string, poolID string, fee int64) error
StakePoolPayInterests(blobberID string, fee int64) error
UpdateBlobberSettings(blobber *Blobber, fee int64) error
UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock, fee int64) error
WritePoolLock(allocID string, blobberID string, duration int64, lock, fee int64) error
WritePoolUnlock(poolID string, fee int64) error
}
func signFn(hash string) (string, error) {
sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme)
sigScheme.SetPrivateKey(_config.wallet.Keys[0].PrivateKey)
return sigScheme.Sign(hash)
}
func signWithWallet(hash string, wi interface{}) (string, error) {
w, ok := wi.(*zcncrypto.Wallet)
if !ok {
fmt.Printf("Error in casting to wallet")
return "", errors.New("", "error in casting to wallet")
}
sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme)
sigScheme.SetPrivateKey(w.Keys[0].PrivateKey)
return sigScheme.Sign(hash)
}
func txnTypeString(t int) string {
switch t {
case transaction.TxnTypeSend:
return "send"
case transaction.TxnTypeLockIn:
return "lock-in"
case transaction.TxnTypeData:
return "data"
case transaction.TxnTypeSmartContract:
return "smart contract"
default:
return "unknown"
}
}
func (t *Transaction) Output() []byte {
return []byte(t.txnOut)
}
func (t *Transaction) completeTxn(status int, out string, err error) {
t.txnStatus = status
t.txnOut = out
t.txnError = err
if t.txnCb != nil {
t.txnCb.OnTransactionComplete(t, t.txnStatus)
}
}
func (t *Transaction) completeVerify(status int, out string, err error) {
t.verifyStatus = status
t.verifyOut = out
t.verifyError = err
if t.txnCb != nil {
t.txnCb.OnVerifyComplete(t, t.verifyStatus)
}
}
func (t *Transaction) submitTxn() {
// Clear the status, incase transaction object reused
t.txnStatus = StatusUnknown
t.txnOut = ""
t.txnError = nil
// If Signature is not passed compute signature
if t.txn.Signature == "" {
err := t.txn.ComputeHashAndSign(signFn)
if err != nil {
t.completeTxn(StatusError, "", err)
return
}
}
result := make(chan *util.PostResponse, len(_config.chain.Miners))
defer close(result)
var tSuccessRsp string
var tFailureRsp string
randomMiners := util.GetRandom(_config.chain.Miners, getMinMinersSubmit())
for _, miner := range randomMiners {
go func(minerurl string) {
url := minerurl + PUT_TRANSACTION
Logger.Info("Submitting ", txnTypeString(t.txn.TransactionType), " transaction to ", minerurl)
req, err := util.NewHTTPPostRequest(url, t.txn)
if err != nil {
Logger.Error(minerurl, " new post request failed. ", err.Error())
return
}
res, err := req.Post()
if err != nil {
Logger.Error(minerurl, " submit transaction error. ", err.Error())
}
result <- res
return
}(miner)
}
consensus := float32(0)
for range randomMiners {
select {
case rsp := <-result:
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode == http.StatusOK {
consensus++
tSuccessRsp = rsp.Body
} else {
Logger.Error(rsp.Body)
tFailureRsp = rsp.Body
}
}
}
rate := consensus * 100 / float32(len(randomMiners))
if rate < consensusThresh {
t.completeTxn(StatusError, "", fmt.Errorf("submit transaction failed. %s", tFailureRsp))
return
}
time.Sleep(3 * time.Second)
t.completeTxn(StatusSuccess, tSuccessRsp, nil)
}
func newTransaction(cb TransactionCallback, txnFee int64) (*Transaction, error) {
t := &Transaction{}
t.txn = transaction.NewTransactionEntity(_config.wallet.ClientID, _config.chain.ChainID, _config.wallet.ClientKey)
t.txnStatus, t.verifyStatus = StatusUnknown, StatusUnknown
t.txnCb = cb
t.txn.TransactionFee = txnFee
return t, nil
}
// NewTransaction allocation new generic transaction object for any operation
func NewTransaction(cb TransactionCallback, txnFee int64) (TransactionScheme, error) {
err := checkConfig()
if err != nil {
return nil, err
}
if _config.isSplitWallet {
if _config.authUrl == "" {
return nil, errors.New("", "auth url not set")
}
Logger.Info("New transaction interface with auth")
return newTransactionWithAuth(cb, txnFee)
}
Logger.Info("New transaction interface")
return newTransaction(cb, txnFee)
}
func (t *Transaction) SetTransactionCallback(cb TransactionCallback) error {
if t.txnStatus != StatusUnknown {
return errors.New("", "transaction already exists. cannot set transaction hash.")
}
t.txnCb = cb
return nil
}
func (t *Transaction) SetTransactionFee(txnFee int64) error {
if t.txnStatus != StatusUnknown {
return errors.New("", "transaction already exists. cannot set transaction fee.")
}
t.txn.TransactionFee = txnFee
return nil
}
func (t *Transaction) Send(toClientID string, val int64, desc string) error {
go func() {
t.txn.TransactionType = transaction.TxnTypeSend
t.txn.ToClientID = toClientID
t.txn.Value = val
t.txn.TransactionData = desc
t.submitTxn()
}()
return nil
}
func (t *Transaction) SendWithSignatureHash(toClientID string, val int64, desc string, sig string, CreationDate int64, hash string) error {
go func() {
t.txn.TransactionType = transaction.TxnTypeSend
t.txn.ToClientID = toClientID
t.txn.Value = val
t.txn.Hash = hash
t.txn.TransactionData = desc
t.txn.Signature = sig
t.txn.CreationDate = CreationDate
t.submitTxn()
}()
return nil
}
func (t *Transaction) StoreData(data string) error {
go func() {
t.txn.TransactionType = transaction.TxnTypeData
t.txn.TransactionData = data
t.submitTxn()
}()
return nil
}
func (t *Transaction) createSmartContractTxn(address, methodName string, input interface{}, value int64) error {
sn := transaction.SmartContractTxnData{Name: methodName, InputArgs: input}
snBytes, err := json.Marshal(sn)
if err != nil {
return errors.Wrap(err, "create smart contract failed due to invalid data.")
}
t.txn.TransactionType = transaction.TxnTypeSmartContract
t.txn.ToClientID = address
t.txn.TransactionData = string(snBytes)
t.txn.Value = value
return nil
}
func (t *Transaction) createFaucetSCWallet(walletStr string, methodName string, input []byte) (*zcncrypto.Wallet, error) {
w, err := GetWallet(walletStr)
if err != nil {
fmt.Printf("Error while parsing the wallet. %v\n", err)
return nil, err
}
err = t.createSmartContractTxn(FaucetSmartContractAddress, methodName, input, 0)
if err != nil {
return nil, err
}
return w, nil
}
// ExecuteFaucetSCWallet impements the Faucet Smart contract for a given wallet
func (t *Transaction) ExecuteFaucetSCWallet(walletStr string, methodName string, input []byte) error {
w, err := t.createFaucetSCWallet(walletStr, methodName, input)
if err != nil {
return err
}
go func() {
t.txn.ComputeHashAndSignWithWallet(signWithWallet, w)
fmt.Printf("submitted transaction\n")
t.submitTxn()
}()
return nil
}
func (t *Transaction) ExecuteSmartContract(address, methodName, jsoninput string, val int64) error {
scData := make(map[string]interface{})
json.Unmarshal([]byte(jsoninput), &scData)
err := t.createSmartContractTxn(address, methodName, scData, val)
if err != nil {
return err
}
go func() {
t.submitTxn()
}()
return nil
}
func (t *Transaction) SetTransactionHash(hash string) error {
if t.txnStatus != StatusUnknown {
return errors.New("", "transaction already exists. cannot set transaction hash.")
}
t.txnHash = hash
return nil
}
func (t *Transaction) GetTransactionHash() string {
if t.txnHash != "" {
return t.txnHash
}
if t.txnStatus != StatusSuccess {
return ""
}
var txnout map[string]json.RawMessage
err := json.Unmarshal([]byte(t.txnOut), &txnout)
if err != nil {
fmt.Println("Error in parsing", err)
}
var entity map[string]interface{}
err = json.Unmarshal(txnout["entity"], &entity)
if err != nil {
Logger.Error("json unmarshal error on GetTransactionHash()")
return t.txnHash
}
if hash, ok := entity["hash"].(string); ok {
t.txnHash = hash
}
return t.txnHash
}
func queryFromSharders(numSharders int, query string,
result chan *util.GetResponse) {
queryFromShardersContext(context.Background(), numSharders, query, result)
}
func queryFromShardersContext(ctx context.Context, numSharders int,
query string, result chan *util.GetResponse) {
for _, sharder := range util.Shuffle(_config.chain.Sharders) {
go func(sharderurl string) {
Logger.Info("Query from ", sharderurl+query)
url := fmt.Sprintf("%v%v", sharderurl, query)
req, err := util.NewHTTPGetRequestContext(ctx, url)
if err != nil {
Logger.Error(sharderurl, " new get request failed. ", err.Error())
return
}
res, err := req.Get()
if err != nil {
Logger.Error(sharderurl, " get error. ", err.Error())
}
result <- res
return
}(sharder)
}
}
func getBlockHeaderFromTransactionConfirmation(txnHash string, cfmBlock map[string]json.RawMessage) (*blockHeader, error) {
block := &blockHeader{}
if cfmBytes, ok := cfmBlock["confirmation"]; ok {
var cfm confirmation
err := json.Unmarshal(cfmBytes, &cfm)
if err != nil {
return nil, errors.Wrap(err, "txn confirmation parse error.")
}
if cfm.Transaction == nil {
return nil, fmt.Errorf("missing transaction %s in block confirmation", txnHash)
}
if txnHash != cfm.Transaction.Hash {
return nil, fmt.Errorf("invalid transaction hash. Expected: %s. Received: %s", txnHash, cfm.Transaction.Hash)
}
if !util.VerifyMerklePath(cfm.Transaction.Hash, cfm.MerkleTreePath, cfm.MerkleTreeRoot) {
return nil, errors.New("", "txn merkle validation failed.")
}
txnRcpt := transaction.NewTransactionReceipt(cfm.Transaction)
if !util.VerifyMerklePath(txnRcpt.GetHash(), cfm.ReceiptMerkleTreePath, cfm.ReceiptMerkleTreeRoot) {
return nil, errors.New("", "txn receipt cmerkle validation failed.")
}
prevBlockHash := cfm.PreviousBlockHash
block.MinerId = cfm.MinerID
block.Hash = cfm.BlockHash
block.CreationDate = cfm.CreationDate
block.Round = cfm.Round
block.RoundRandomSeed = cfm.RoundRandomSeed
block.MerkleTreeRoot = cfm.MerkleTreeRoot
block.ReceiptMerkleTreeRoot = cfm.ReceiptMerkleTreeRoot
// Verify the block
if isBlockExtends(prevBlockHash, block) {
return block, nil
} else {
return nil, errors.New("", "block hash verification failed in confirmation")
}
}
return nil, errors.New("", "txn confirmation not found.")
}
func getTransactionConfirmation(numSharders int, txnHash string) (*blockHeader, map[string]json.RawMessage, *blockHeader, error) {
result := make(chan *util.GetResponse)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromSharders(numSharders, fmt.Sprintf("%v%v&content=lfb", TXN_VERIFY_URL, txnHash), result)
maxConfirmation := int(0)
txnConfirmations := make(map[string]int)
var blockHdr *blockHeader
var lfb blockHeader
var confirmation map[string]json.RawMessage
for i := 0; i < numSharders; i++ {
select {
case rsp := <-result:
Logger.Debug(rsp.Url + " " + rsp.Status)
Logger.Debug(rsp.Body)
if rsp.StatusCode == http.StatusOK {
var cfmLfb map[string]json.RawMessage
err := json.Unmarshal([]byte(rsp.Body), &cfmLfb)
if err != nil {
Logger.Error("txn confirmation parse error", err)
continue
}
bH, err := getBlockHeaderFromTransactionConfirmation(txnHash, cfmLfb)
if err != nil {
Logger.Error(err)
}
if err == nil {
txnConfirmations[bH.Hash]++
if txnConfirmations[bH.Hash] > maxConfirmation {
maxConfirmation = txnConfirmations[bH.Hash]
blockHdr = bH
confirmation = cfmLfb
}
} else if lfbRaw, ok := cfmLfb["latest_finalized_block"]; ok {
err := json.Unmarshal([]byte(lfbRaw), &lfb)
if err != nil {
Logger.Error("round info parse error.", err)
continue
}
}
}
}
}
if maxConfirmation == 0 {
return nil, confirmation, &lfb, errors.New("", "transaction not found")
}
return blockHdr, confirmation, &lfb, nil
}
func GetLatestFinalized(ctx context.Context, numSharders int) (b *block.Header, err error) {
var result = make(chan *util.GetResponse, numSharders)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result)
var (
maxConsensus int
roundConsensus = make(map[string]int)
)
for i := 0; i < numSharders; i++ {
var rsp = <-result
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode != http.StatusOK {
Logger.Error(rsp.Body)
continue
}
if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil {
Logger.Error("block parse error: ", err)
err = nil
continue
}
var h = encryption.FastHash([]byte(b.Hash))
if roundConsensus[h]++; roundConsensus[h] > maxConsensus {
maxConsensus = roundConsensus[h]
}
}
if maxConsensus == 0 {
return nil, errors.New("", "block info not found")
}
return
}
func GetLatestFinalizedMagicBlock(ctx context.Context, numSharders int) (m *block.MagicBlock, err error) {
var result = make(chan *util.GetResponse, numSharders)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result)
var (
maxConsensus int
roundConsensus = make(map[string]int)
)
type respObj struct {
MagicBlock *block.MagicBlock `json:"magic_block"`
}
for i := 0; i < numSharders; i++ {
var rsp = <-result
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode != http.StatusOK {
Logger.Error(rsp.Body)
continue
}
var respo respObj
if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil {
Logger.Error(" magic block parse error: ", err)
err = nil
continue
}
m = respo.MagicBlock
var h = encryption.FastHash([]byte(respo.MagicBlock.Hash))
if roundConsensus[h]++; roundConsensus[h] > maxConsensus {
maxConsensus = roundConsensus[h]
}
}
if maxConsensus == 0 {
return nil, errors.New("", "magic block info not found")
}
return
}
func GetChainStats(ctx context.Context) (b *block.ChainStats, err error) {
var result = make(chan *util.GetResponse, 1)
defer close(result)
var numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result)
var rsp *util.GetResponse
for i := 0; i < numSharders; i++ {
var x = <-result
if x.StatusCode != http.StatusOK {
continue
}
rsp = x
}
if rsp == nil {
return nil, errors.New("http_request_failed", "Request failed with status not 200")
}
if err = json.Unmarshal([]byte(rsp.Body), &b); err != nil {
return nil, err
}
return
}
func GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *block.Block, err error) {
var result = make(chan *util.GetResponse, numSharders)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromShardersContext(ctx, numSharders,
fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round),
result)
var (
maxConsensus int
roundConsensus = make(map[string]int)
)
type respObj struct {
Block *block.Block `json:"block"`
Header *block.Header `json:"header"`
}
for i := 0; i < numSharders; i++ {
var rsp = <-result
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode != http.StatusOK {
Logger.Error(rsp.Body)
continue
}
var respo respObj
if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil {
Logger.Error("block parse error: ", err)
err = nil
continue
}
if respo.Block == nil {
Logger.Debug(rsp.Url, "no block in response:", rsp.Body)
continue
}
if respo.Header == nil {
Logger.Debug(rsp.Url, "no block header in response:", rsp.Body)
continue
}
if respo.Header.Hash != string(respo.Block.Hash) {
Logger.Debug(rsp.Url, "header and block hash mismatch:", rsp.Body)
continue
}
b = respo.Block
b.Header = respo.Header
var h = encryption.FastHash([]byte(b.Hash))
if roundConsensus[h]++; roundConsensus[h] > maxConsensus {
maxConsensus = roundConsensus[h]
}
}
if maxConsensus == 0 {
return nil, errors.New("", "round info not found")
}
return
}
func GetMagicBlockByNumber(ctx context.Context, numSharders int, number int64) (m *block.MagicBlock, err error) {
var result = make(chan *util.GetResponse, numSharders)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromShardersContext(ctx, numSharders,
fmt.Sprintf("%smagic_block_number=%d", GET_MAGIC_BLOCK_INFO, number),
result)
var (
maxConsensus int
roundConsensus = make(map[string]int)
)
type respObj struct {
MagicBlock *block.MagicBlock `json:"magic_block"`
}
for i := 0; i < numSharders; i++ {
var rsp = <-result
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode != http.StatusOK {
Logger.Error(rsp.Body)
continue
}
var respo respObj
if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil {
Logger.Error(" magic block parse error: ", err)
err = nil
continue
}
m = respo.MagicBlock
var h = encryption.FastHash([]byte(respo.MagicBlock.Hash))
if roundConsensus[h]++; roundConsensus[h] > maxConsensus {
maxConsensus = roundConsensus[h]
}
}
if maxConsensus == 0 {
return nil, errors.New("", "magic block info not found")
}
return
}
func getBlockInfoByRound(numSharders int, round int64, content string) (*blockHeader, error) {
result := make(chan *util.GetResponse)
defer close(result)
numSharders = len(_config.chain.Sharders) // overwrite, use all
queryFromSharders(numSharders, fmt.Sprintf("%vround=%v&content=%v", GET_BLOCK_INFO, round, content), result)
maxConsensus := int(0)
roundConsensus := make(map[string]int)
var blkHdr blockHeader
for i := 0; i < numSharders; i++ {
select {
case rsp := <-result:
Logger.Debug(rsp.Url, rsp.Status)
if rsp.StatusCode == http.StatusOK {
var objmap map[string]json.RawMessage
err := json.Unmarshal([]byte(rsp.Body), &objmap)
if err != nil {
Logger.Error("round info parse error. ", err)
continue
}
if header, ok := objmap["header"]; ok {
err := json.Unmarshal([]byte(header), &objmap)
if err != nil {
Logger.Error("round info parse error. ", err)
continue
}
if hash, ok := objmap["hash"]; ok {
h := encryption.FastHash([]byte(hash))
roundConsensus[h]++
if roundConsensus[h] > maxConsensus {
maxConsensus = roundConsensus[h]
err := json.Unmarshal([]byte(header), &blkHdr)
if err != nil {
Logger.Error("round info parse error. ", err)
continue
}
}
}
} else {
Logger.Debug(rsp.Url, "no round confirmation. Resp:", rsp.Body)
}
} else {
Logger.Error(rsp.Body)
}
}
}
if maxConsensus == 0 {
return nil, errors.New("", "round info not found.")
}
return &blkHdr, nil
}
func isBlockExtends(prevHash string, block *blockHeader) bool {
data := fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v", block.MinerId, prevHash, block.CreationDate, block.Round,
block.RoundRandomSeed, block.MerkleTreeRoot, block.ReceiptMerkleTreeRoot)
h := encryption.Hash(data)
if block.Hash == h {
return true
}
return false
}
func validateChain(confirmBlock *blockHeader) bool {
confirmRound := confirmBlock.Round
Logger.Debug("Confirmation round: ", confirmRound)
currentBlockHash := confirmBlock.Hash
round := confirmRound + 1
for {
nextBlock, err := getBlockInfoByRound(1, round, "header")
if err != nil {
Logger.Info(err, " after a second falling thru to ", getMinShardersVerify(), "of ", len(_config.chain.Sharders), "Sharders")
time.Sleep(1 * time.Second)
nextBlock, err = getBlockInfoByRound(getMinShardersVerify(), round, "header")
if err != nil {
Logger.Error(err, " block chain stalled. waiting", defaultWaitSeconds, "...")
time.Sleep(defaultWaitSeconds)
continue
}
}
if isBlockExtends(currentBlockHash, nextBlock) {
currentBlockHash = nextBlock.Hash
round++
}
if (round > confirmRound) && (round-confirmRound < getMinRequiredChainLength()) {
continue
}
if round < confirmRound {
return false
}
// Validation success
break
}
return true
}
func (t *Transaction) isTransactionExpired(lfbCreationTime, currentTime int64) bool {
// latest finalized block zero implies no response. use currentTime as lfb
if lfbCreationTime == 0 {
lfbCreationTime = currentTime
}
if util.MinInt64(lfbCreationTime, currentTime) > (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) {
return true
}
// Wait for next retry
time.Sleep(defaultWaitSeconds)
return false
}
func (t *Transaction) Verify() error {
if t.txnHash == "" && t.txnStatus == StatusUnknown {
return errors.New("", "invalid transaction. cannot be verified.")
}
if t.txnHash == "" && t.txnStatus == StatusSuccess {
h := t.GetTransactionHash()
if h == "" {
return errors.New("", "invalid transaction. cannot be verified.")
}
}
// If transaction is verify only start from current time
if t.txn.CreationDate == 0 {
t.txn.CreationDate = int64(common.Now())
}
go func() {
for {
// Get transaction confirmation from random sharder
confirmBlock, confirmation, lfb, err := getTransactionConfirmation(1, t.txnHash)
if err != nil {
tn := int64(common.Now())
Logger.Info(err, " now: ", tn, ", LFB creation time:", lfb.CreationDate)
if util.MaxInt64(lfb.CreationDate, tn) < (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) {
Logger.Info("falling back to ", getMinShardersVerify(), " of ", len(_config.chain.Sharders), " Sharders")
confirmBlock, confirmation, lfb, err = getTransactionConfirmation(getMinShardersVerify(), t.txnHash)
if err != nil {
if t.isTransactionExpired(lfb.CreationDate, tn) {
t.completeVerify(StatusError, "", errors.New("", `{"error": "verify transaction failed"}`))
return
}
continue
}
} else {
if t.isTransactionExpired(lfb.CreationDate, tn) {
t.completeVerify(StatusError, "", errors.New("", `{"error": "verify transaction failed"}`))
return
}
continue
}
}
valid := validateChain(confirmBlock)
if valid {
output, err := json.Marshal(confirmation)
if err != nil {
t.completeVerify(StatusError, "", errors.New("", `{"error": "transaction confirmation json marshal error"`))
return
}
t.completeVerify(StatusSuccess, string(output), nil)
return
}
}
}()
return nil
}
func (t *Transaction) GetVerifyOutput() string {
if t.verifyStatus == StatusSuccess {
return t.verifyOut
}
return ""
}
func (t *Transaction) GetTransactionError() string {
if t.txnStatus != StatusSuccess {
return t.txnError.Error()
}
return ""
}
func (t *Transaction) GetVerifyError() string {
if t.verifyStatus != StatusSuccess {
return t.verifyError.Error()
}
return ""
}
// ========================================================================== //
// vesting pool //
// ========================================================================== //
type vestingRequest struct {
PoolID common.Key `json:"pool_id"`
}
func (t *Transaction) vestingPoolTxn(function string, poolID string,
value int64) error {
return t.createSmartContractTxn(VestingSmartContractAddress,
function, vestingRequest{PoolID: common.Key(poolID)}, int64(value))
}
func (t *Transaction) VestingTrigger(poolID string) (err error) {
err = t.vestingPoolTxn(transaction.VESTING_TRIGGER, poolID, 0)
if err != nil {
Logger.Error(err)
return
}
go func() { t.submitTxn() }()
return
}
type VestingStopRequest struct {
PoolID common.Key `json:"pool_id"`
Destination common.Key `json:"destination"`
}
func (t *Transaction) VestingStop(sr *VestingStopRequest) (err error) {
err = t.createSmartContractTxn(VestingSmartContractAddress,
transaction.VESTING_STOP, sr, 0)
if err != nil {
Logger.Error(err)
return
}
go func() { t.submitTxn() }()