/
state_transition.go
1500 lines (1342 loc) · 55.2 KB
/
state_transition.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
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library 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 go-ethereum library 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package core
import (
"encoding/json"
"fmt"
cmath "github.com/FusionFoundation/efsn/v4/common/math"
"math"
"math/big"
"reflect"
"time"
"github.com/FusionFoundation/efsn/v4/common"
"github.com/FusionFoundation/efsn/v4/common/hexutil"
"github.com/FusionFoundation/efsn/v4/consensus/datong"
"github.com/FusionFoundation/efsn/v4/core/types"
"github.com/FusionFoundation/efsn/v4/core/vm"
"github.com/FusionFoundation/efsn/v4/crypto"
"github.com/FusionFoundation/efsn/v4/log"
"github.com/FusionFoundation/efsn/v4/params"
"github.com/FusionFoundation/efsn/v4/rlp"
)
var emptyCodeHash = crypto.Keccak256Hash(nil)
/*
The State Transitioning Model
A state transition is a change made when a transaction is applied to the current world state
The state transitioning model does all the necessary work to work out a valid new state root.
1) Nonce handling
2) Pre pay gas
3) Create a new state object if the recipient is \0*32
4) Value transfer
== If contract creation ==
4a) Attempt to run transaction data
4b) If valid, use result as code for the new state object
== end ==
5) Run Script section
6) Derive new state root
*/
type StateTransition struct {
gp *GasPool
msg Message
gas uint64
gasPrice *big.Int
gasFeeCap *big.Int
gasTipCap *big.Int
initialGas uint64
fee *big.Int
value *big.Int
data []byte
state vm.StateDB
evm *vm.EVM
}
// Message represents a message sent to a contract.
type Message interface {
From() common.Address
To() *common.Address
GasPrice() *big.Int
GasFeeCap() *big.Int
GasTipCap() *big.Int
Gas() uint64
Value() *big.Int
Nonce() uint64
IsFake() bool
Data() []byte
AccessList() types.AccessList
AsTransaction() *types.Transaction
}
// ExecutionResult includes all output after executing given evm
// message no matter the execution itself is successful or not.
type ExecutionResult struct {
UsedGas uint64 // Total used gas but include the refunded gas
Err error // Any error encountered during the execution(listed in core/vm/errors.go)
ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
}
// Unwrap returns the internal evm error which allows us for further
// analysis outside.
func (result *ExecutionResult) Unwrap() error {
return result.Err
}
// Failed returns the indicator whether the execution is successful or not
func (result *ExecutionResult) Failed() bool { return result.Err != nil }
// Return is a helper function to help caller distinguish between revert reason
// and function return. Return returns the data after execution if no error occurs.
func (result *ExecutionResult) Return() []byte {
if result.Err != nil {
return nil
}
return common.CopyBytes(result.ReturnData)
}
// Revert returns the concrete revert reason if the execution is aborted by `REVERT`
// opcode. Note the reason can be nil if no data supplied with revert opcode.
func (result *ExecutionResult) Revert() []byte {
if result.Err != vm.ErrExecutionReverted {
return nil
}
return common.CopyBytes(result.ReturnData)
}
// IntrinsicGas computes the 'intrinsic gas' for a message with the given data.
func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, isHomestead, isEIP2028 bool) (uint64, error) {
// Set the starting gas for the raw transaction
var gas uint64
if isContractCreation && isHomestead {
gas = params.TxGasContractCreation
} else {
gas = params.TxGas
}
// Bump the required gas by the amount of transactional data
if len(data) > 0 {
// Zero and non-zero bytes are priced differently
var nz uint64
for _, byt := range data {
if byt != 0 {
nz++
}
}
// Make sure we don't exceed uint64 for all data combinations
nonZeroGas := params.TxDataNonZeroGasFrontier
if isEIP2028 {
nonZeroGas = params.TxDataNonZeroGasEIP2028
}
if (math.MaxUint64-gas)/nonZeroGas < nz {
return 0, ErrGasUintOverflow
}
gas += nz * nonZeroGas
z := uint64(len(data)) - nz
if (math.MaxUint64-gas)/params.TxDataZeroGas < z {
return 0, ErrGasUintOverflow
}
gas += z * params.TxDataZeroGas
}
if accessList != nil {
gas += uint64(len(accessList)) * params.TxAccessListAddressGas
gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas
}
return gas, nil
}
// NewStateTransition initialises and returns a new state transition object.
func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
return &StateTransition{
gp: gp,
evm: evm,
msg: msg,
gasPrice: msg.GasPrice(),
gasFeeCap: msg.GasFeeCap(),
gasTipCap: msg.GasTipCap(),
value: msg.Value(),
data: msg.Data(),
state: evm.StateDB,
fee: big.NewInt(0),
}
}
// ApplyMessage computes the new state by applying the given message
// against the old state within the environment.
//
// ApplyMessage returns the bytes returned by any EVM execution (if it took place),
// the gas used (which includes gas refunds) and an error if it failed. An error always
// indicates a core error meaning that the message would always fail for that particular
// state and would never be accepted within a block.
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) (*ExecutionResult, error) {
return NewStateTransition(evm, msg, gp).TransitionDb()
}
// to returns the recipient of the message.
func (st *StateTransition) to() common.Address {
if st.msg == nil || st.msg.To() == nil /* contract creation */ {
return common.Address{}
}
return *st.msg.To()
}
func (st *StateTransition) buyGas() error {
mgval := new(big.Int).SetUint64(st.msg.Gas())
mgval = mgval.Mul(mgval, st.gasPrice)
// Fusion Call Fee
mgval.Add(mgval, st.fee)
balanceCheck := mgval
if st.gasFeeCap != nil {
balanceCheck = new(big.Int).SetUint64(st.msg.Gas())
balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap)
balanceCheck.Add(balanceCheck, st.value)
}
if have, want := st.state.GetBalance(common.SystemAssetID, st.msg.From()), balanceCheck; have.Cmp(want) < 0 {
return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want)
}
if err := st.gp.SubGas(st.msg.Gas()); err != nil {
return err
}
st.gas += st.msg.Gas()
st.initialGas = st.msg.Gas()
st.state.SubBalance(st.msg.From(), common.SystemAssetID, mgval)
return nil
}
func (st *StateTransition) preCheck() error {
// Only check transactions that are not fake
if !st.msg.IsFake() {
// Make sure this transaction's nonce is correct.
stNonce := st.state.GetNonce(st.msg.From())
if msgNonce := st.msg.Nonce(); stNonce < msgNonce {
return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooHigh,
st.msg.From().Hex(), msgNonce, stNonce)
} else if stNonce > msgNonce {
return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow,
st.msg.From().Hex(), msgNonce, stNonce)
}
// Make sure the sender is an EOA
if codeHash := st.state.GetCodeHash(st.msg.From()); codeHash != emptyCodeHash && codeHash != (common.Hash{}) {
return fmt.Errorf("%w: address %v, codehash: %s", ErrSenderNoEOA,
st.msg.From().Hex(), codeHash)
}
}
// Make sure that transaction gasFeeCap is greater than the baseFee (post london)
if st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber) {
// Skip the checks if gas fields are zero and baseFee was explicitly disabled (eth_call)
if !st.evm.Config.NoBaseFee || st.gasFeeCap.BitLen() > 0 || st.gasTipCap.BitLen() > 0 {
if l := st.gasFeeCap.BitLen(); l > 256 {
return fmt.Errorf("%w: address %v, maxFeePerGas bit length: %d", ErrFeeCapVeryHigh,
st.msg.From().Hex(), l)
}
if l := st.gasTipCap.BitLen(); l > 256 {
return fmt.Errorf("%w: address %v, maxPriorityFeePerGas bit length: %d", ErrTipVeryHigh,
st.msg.From().Hex(), l)
}
if st.gasFeeCap.Cmp(st.gasTipCap) < 0 {
return fmt.Errorf("%w: address %v, maxPriorityFeePerGas: %s, maxFeePerGas: %s", ErrTipAboveFeeCap,
st.msg.From().Hex(), st.gasTipCap, st.gasFeeCap)
}
// This will panic if baseFee is nil, but basefee presence is verified
// as part of header validation.
if st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 {
return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow,
st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee)
}
}
}
return st.buyGas()
}
// TransitionDb will transition the state by applying the current message and
// returning the evm execution result with following fields.
//
// - used gas:
// total gas used (including gas being refunded)
// - returndata:
// the returned data from evm
// - concrete execution error:
// various **EVM** error which aborts the execution,
// e.g. ErrOutOfGas, ErrExecutionReverted
//
// However if any consensus issue encountered, return the error directly with
// nil evm execution result.
func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
msg := st.msg
var fsnCallParam *common.FSNCallParam
if common.IsFsnCall(msg.To()) {
fsnCallParam = &common.FSNCallParam{}
rlp.DecodeBytes(msg.Data(), fsnCallParam)
st.fee = common.GetFsnCallFee(msg.To(), fsnCallParam.Func)
}
// First check this message satisfies all consensus rules before
// applying the message. The rules include these clauses
//
// 1. the nonce of the message caller is correct
// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
// 3. the amount of gas required is available in the block
// 4. the purchased gas is enough to cover intrinsic usage
// 5. there is no overflow when calculating intrinsic gas
// 6. caller has enough balance to cover asset transfer for **topmost** call
// Check clauses 1-3, buy gas if everything is correct
if err := st.preCheck(); err != nil {
return nil, err
}
sender := vm.AccountRef(msg.From())
homestead := st.evm.ChainConfig().IsHomestead(st.evm.Context.BlockNumber)
istanbul := st.evm.ChainConfig().IsIstanbul(st.evm.Context.BlockNumber)
london := st.evm.ChainConfig().IsLondon(st.evm.Context.BlockNumber)
contractCreation := msg.To() == nil
// Check clauses 4-5, subtract intrinsic gas if everything is correct
gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, istanbul)
if err != nil {
return nil, err
}
if st.gas < gas {
return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
}
st.gas -= gas
// Check clause 6
if msg.Value().Sign() > 0 && !st.evm.Context.CanTransfer(st.state, msg.From(), msg.Value()) {
return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
}
// Set up the initial access list.
if rules := st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber); rules.IsBerlin {
st.state.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList())
}
var (
ret []byte
vmerr error // vm errors do not effect consensus and are therefore not assigned to err
)
if contractCreation {
ret, _, st.gas, vmerr = st.evm.Create(sender, st.data, st.gas, st.value)
} else {
// Increment the nonce for the next transaction
st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
if fsnCallParam != nil {
errc := st.handleFsnCall(fsnCallParam)
if errc != nil {
isInMining := st.evm.Context.MixDigest == (common.Hash{})
if isInMining {
// don't pack tx if handle FsnCall meet error
return nil, errc
}
common.DebugInfo("handleFsnCall error", "number", st.evm.Context.BlockNumber, "Func", fsnCallParam.Func, "err", errc)
}
}
ret, st.gas, vmerr = st.evm.Call(sender, st.to(), st.data, st.gas, st.value)
}
if !london {
// Before EIP-3529: refunds were capped to gasUsed / 2
st.refundGas(params.RefundQuotient)
} else {
// After EIP-3529: refunds are capped to gasUsed / 5
st.refundGas(params.RefundQuotientEIP3529)
}
effectiveTip := st.gasPrice
if london {
effectiveTip = cmath.BigMin(st.gasTipCap, new(big.Int).Sub(st.gasFeeCap, st.evm.Context.BaseFee))
// Fusion don't burn the base fee
effectiveTip.Add(effectiveTip, st.evm.Context.BaseFee)
}
minerFees := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip)
if st.fee.Sign() > 0 {
minerFees.Add(minerFees, st.fee)
}
st.state.AddBalance(st.evm.Context.Coinbase, common.SystemAssetID, minerFees)
return &ExecutionResult{
UsedGas: st.gasUsed(),
Err: vmerr,
ReturnData: ret,
}, nil
}
func (st *StateTransition) refundGas(refundQuotient uint64) {
// Apply refund counter, capped to half of the used gas.
refund := st.gasUsed() / refundQuotient
if refund > st.state.GetRefund() {
refund = st.state.GetRefund()
}
st.gas += refund
// Return ETH for remaining gas, exchanged at the original rate.
remaining := new(big.Int).Mul(new(big.Int).SetUint64(st.gas), st.gasPrice)
st.state.AddBalance(st.msg.From(), common.SystemAssetID, remaining)
// Also return remaining gas to the block gas counter so it is
// available for the next transaction.
st.gp.AddGas(st.gas)
}
// gasUsed returns the amount of gas used up by the state transition.
func (st *StateTransition) gasUsed() uint64 {
return st.initialGas - st.gas
}
var outputCommands = false
func outputCommandInfo(param1 string, param2 string, param3 interface{}) {
if outputCommands {
log.Info(param1, param2, param3)
}
}
func (st *StateTransition) handleFsnCall(param *common.FSNCallParam) error {
height := st.evm.Context.BlockNumber
timestamp := st.evm.Context.ParentTime.Uint64()
switch param.Func {
case common.GenNotationFunc:
outputCommandInfo("GenNotationFunc", "from", st.msg.From())
if err := st.state.GenNotation(st.msg.From()); err != nil {
st.addLog(common.GenNotationFunc, param, common.NewKeyValue("Error", err.Error()))
return err
}
st.addLog(common.GenNotationFunc, param, common.NewKeyValue("notation", st.state.GetNotation(st.msg.From())))
return nil
case common.GenAssetFunc:
outputCommandInfo("GenAssetFunc", "from", st.msg.From())
genAssetParam := common.GenAssetParam{}
rlp.DecodeBytes(param.Data, &genAssetParam)
if err := genAssetParam.Check(height); err != nil {
st.addLog(common.GenAssetFunc, genAssetParam, common.NewKeyValue("Error", err.Error()))
return err
}
asset := genAssetParam.ToAsset()
asset.ID = st.msg.AsTransaction().Hash()
asset.Owner = st.msg.From()
if err := st.state.GenAsset(asset); err != nil {
st.addLog(common.GenAssetFunc, genAssetParam, common.NewKeyValue("Error", "unable to gen asset"))
return err
}
st.state.AddBalance(st.msg.From(), asset.ID, asset.Total)
st.addLog(common.GenAssetFunc, genAssetParam, common.NewKeyValue("AssetID", asset.ID))
return nil
case common.SendAssetFunc:
outputCommandInfo("SendAssetFunc", "from", st.msg.From())
sendAssetParam := common.SendAssetParam{}
rlp.DecodeBytes(param.Data, &sendAssetParam)
if err := sendAssetParam.Check(height); err != nil {
st.addLog(common.SendAssetFunc, sendAssetParam, common.NewKeyValue("Error", err.Error()))
return err
}
if st.state.GetBalance(sendAssetParam.AssetID, st.msg.From()).Cmp(sendAssetParam.Value) < 0 {
st.addLog(common.SendAssetFunc, sendAssetParam, common.NewKeyValue("Error", "not enough asset"))
return fmt.Errorf("not enough asset")
}
st.state.SubBalance(st.msg.From(), sendAssetParam.AssetID, sendAssetParam.Value)
st.state.AddBalance(sendAssetParam.To, sendAssetParam.AssetID, sendAssetParam.Value)
st.addLog(common.SendAssetFunc, sendAssetParam, common.NewKeyValue("AssetID", sendAssetParam.AssetID))
return nil
case common.TimeLockFunc:
outputCommandInfo("TimeLockFunc", "from", st.msg.From())
timeLockParam := common.TimeLockParam{}
rlp.DecodeBytes(param.Data, &timeLockParam)
// adjust param
if timeLockParam.Type == common.TimeLockToAsset {
if timeLockParam.StartTime > uint64(time.Now().Unix()) {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "TimeLockToAsset"), common.NewKeyValue("Error", "Start time must be less than now"))
return fmt.Errorf("Start time must be less than now")
}
timeLockParam.EndTime = common.TimeLockForever
}
if err := timeLockParam.Check(height, timestamp); err != nil {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("Error", err.Error()))
return err
}
start := timeLockParam.StartTime
end := timeLockParam.EndTime
if start < timestamp {
start = timestamp
}
needValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: start,
EndTime: end,
Value: new(big.Int).SetBytes(timeLockParam.Value.Bytes()),
})
if err := needValue.IsValid(); err != nil {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("Error", err.Error()))
return fmt.Errorf(err.Error())
}
switch timeLockParam.Type {
case common.AssetToTimeLock:
if st.state.GetBalance(timeLockParam.AssetID, st.msg.From()).Cmp(timeLockParam.Value) < 0 {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "AssetToTimeLock"), common.NewKeyValue("Error", "not enough asset"))
return fmt.Errorf("not enough asset")
}
st.state.SubBalance(st.msg.From(), timeLockParam.AssetID, timeLockParam.Value)
totalValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: timestamp,
EndTime: common.TimeLockForever,
Value: new(big.Int).SetBytes(timeLockParam.Value.Bytes()),
})
if st.msg.From() == timeLockParam.To {
st.state.AddTimeLockBalance(timeLockParam.To, timeLockParam.AssetID, totalValue, height, timestamp)
} else {
surplusValue := new(common.TimeLock).Sub(totalValue, needValue)
if !surplusValue.IsEmpty() {
st.state.AddTimeLockBalance(st.msg.From(), timeLockParam.AssetID, surplusValue, height, timestamp)
}
st.state.AddTimeLockBalance(timeLockParam.To, timeLockParam.AssetID, needValue, height, timestamp)
}
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "AssetToTimeLock"), common.NewKeyValue("AssetID", timeLockParam.AssetID))
return nil
case common.TimeLockToTimeLock:
if st.state.GetTimeLockBalance(timeLockParam.AssetID, st.msg.From()).Cmp(needValue) < 0 {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "TimeLockToTimeLock"), common.NewKeyValue("Error", "not enough time lock balance"))
return fmt.Errorf("not enough time lock balance")
}
st.state.SubTimeLockBalance(st.msg.From(), timeLockParam.AssetID, needValue, height, timestamp)
st.state.AddTimeLockBalance(timeLockParam.To, timeLockParam.AssetID, needValue, height, timestamp)
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "TimeLockToTimeLock"), common.NewKeyValue("AssetID", timeLockParam.AssetID))
return nil
case common.TimeLockToAsset:
if st.state.GetTimeLockBalance(timeLockParam.AssetID, st.msg.From()).Cmp(needValue) < 0 {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "TimeLockToAsset"), common.NewKeyValue("Error", "not enough time lock balance"))
return fmt.Errorf("not enough time lock balance")
}
st.state.SubTimeLockBalance(st.msg.From(), timeLockParam.AssetID, needValue, height, timestamp)
st.state.AddBalance(timeLockParam.To, timeLockParam.AssetID, timeLockParam.Value)
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "TimeLockToAsset"), common.NewKeyValue("AssetID", timeLockParam.AssetID))
return nil
case common.SmartTransfer:
if !common.IsSmartTransferEnabled(height) {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "SmartTransfer"), common.NewKeyValue("Error", "not enabled"))
return fmt.Errorf("SendTimeLock not enabled")
}
timeLockBalance := st.state.GetTimeLockBalance(timeLockParam.AssetID, st.msg.From())
if timeLockBalance.Cmp(needValue) < 0 {
timeLockValue := timeLockBalance.GetSpendableValue(start, end)
assetBalance := st.state.GetBalance(timeLockParam.AssetID, st.msg.From())
if new(big.Int).Add(timeLockValue, assetBalance).Cmp(timeLockParam.Value) < 0 {
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "SmartTransfer"), common.NewKeyValue("Error", "not enough balance"))
return fmt.Errorf("not enough balance")
}
if timeLockValue.Sign() > 0 {
subTimeLock := common.GetTimeLock(timeLockValue, start, end)
st.state.SubTimeLockBalance(st.msg.From(), timeLockParam.AssetID, subTimeLock, height, timestamp)
}
useAssetAmount := new(big.Int).Sub(timeLockParam.Value, timeLockValue)
st.state.SubBalance(st.msg.From(), timeLockParam.AssetID, useAssetAmount)
surplus := common.GetSurplusTimeLock(useAssetAmount, start, end, timestamp)
if !surplus.IsEmpty() {
st.state.AddTimeLockBalance(st.msg.From(), timeLockParam.AssetID, surplus, height, timestamp)
}
} else {
st.state.SubTimeLockBalance(st.msg.From(), timeLockParam.AssetID, needValue, height, timestamp)
}
if !common.IsWholeAsset(start, end, timestamp) {
st.state.AddTimeLockBalance(timeLockParam.To, timeLockParam.AssetID, needValue, height, timestamp)
} else {
st.state.AddBalance(timeLockParam.To, timeLockParam.AssetID, timeLockParam.Value)
}
st.addLog(common.TimeLockFunc, timeLockParam, common.NewKeyValue("LockType", "SmartTransfer"), common.NewKeyValue("AssetID", timeLockParam.AssetID))
return nil
}
case common.BuyTicketFunc:
outputCommandInfo("BuyTicketFunc", "from", st.msg.From())
from := st.msg.From()
hash := st.evm.Context.GetHash(height.Uint64() - 1)
id := crypto.Keccak256Hash(from[:], hash[:])
if st.state.IsTicketExist(id) {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", "Ticket already exist"))
return fmt.Errorf(id.String() + " Ticket already exist")
}
buyTicketParam := common.BuyTicketParam{}
rlp.DecodeBytes(param.Data, &buyTicketParam)
// check buy ticket param
if common.IsHardFork(2, height) {
if err := buyTicketParam.Check(height, timestamp); err != nil {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", err.Error()))
return err
}
} else {
if err := buyTicketParam.Check(height, 0); err != nil {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", err.Error()))
return err
}
}
start := buyTicketParam.Start
end := buyTicketParam.End
value := common.TicketPrice(height)
var needValue *common.TimeLock
needValue = common.NewTimeLock(&common.TimeLockItem{
StartTime: common.MaxUint64(start, timestamp),
EndTime: end,
Value: value,
})
if err := needValue.IsValid(); err != nil {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", err.Error()))
return fmt.Errorf(err.Error())
}
ticket := common.Ticket{
Owner: from,
TicketBody: common.TicketBody{
ID: id,
Height: height.Uint64(),
StartTime: start,
ExpireTime: end,
},
}
useAsset := false
if st.state.GetTimeLockBalance(common.SystemAssetID, from).Cmp(needValue) < 0 {
if st.state.GetBalance(common.SystemAssetID, from).Cmp(value) < 0 {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", "not enough time lock or asset balance"))
return fmt.Errorf("not enough time lock or asset balance")
}
useAsset = true
}
if useAsset {
st.state.SubBalance(from, common.SystemAssetID, value)
totalValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: timestamp,
EndTime: common.TimeLockForever,
Value: value,
})
surplusValue := new(common.TimeLock).Sub(totalValue, needValue)
if !surplusValue.IsEmpty() {
st.state.AddTimeLockBalance(from, common.SystemAssetID, surplusValue, height, timestamp)
}
} else {
st.state.SubTimeLockBalance(from, common.SystemAssetID, needValue, height, timestamp)
}
if err := st.state.AddTicket(ticket); err != nil {
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("Error", "unable to add ticket"))
return err
}
st.addLog(common.BuyTicketFunc, param.Data, common.NewKeyValue("TicketID", ticket.ID), common.NewKeyValue("TicketOwner", ticket.Owner))
return nil
case common.AssetValueChangeFunc:
outputCommandInfo("AssetValueChangeFunc", "from", st.msg.From())
assetValueChangeParamEx := common.AssetValueChangeExParam{}
rlp.DecodeBytes(param.Data, &assetValueChangeParamEx)
if err := assetValueChangeParamEx.Check(height); err != nil {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", err.Error()))
return err
}
asset, err := st.state.GetAsset(assetValueChangeParamEx.AssetID)
if err != nil {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", "asset not found"))
return fmt.Errorf("asset not found")
}
if !asset.CanChange {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", "asset can't inc or dec"))
return fmt.Errorf("asset can't inc or dec")
}
if asset.Owner != st.msg.From() {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", "can only be changed by owner"))
return fmt.Errorf("can only be changed by owner")
}
if asset.Owner != assetValueChangeParamEx.To && !assetValueChangeParamEx.IsInc {
err := fmt.Errorf("decrement can only happen to asset's own account")
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", err.Error()))
return err
}
if assetValueChangeParamEx.IsInc {
st.state.AddBalance(assetValueChangeParamEx.To, assetValueChangeParamEx.AssetID, assetValueChangeParamEx.Value)
asset.Total = asset.Total.Add(asset.Total, assetValueChangeParamEx.Value)
} else {
if st.state.GetBalance(assetValueChangeParamEx.AssetID, assetValueChangeParamEx.To).Cmp(assetValueChangeParamEx.Value) < 0 {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", "not enough asset"))
return fmt.Errorf("not enough asset")
}
st.state.SubBalance(assetValueChangeParamEx.To, assetValueChangeParamEx.AssetID, assetValueChangeParamEx.Value)
asset.Total = asset.Total.Sub(asset.Total, assetValueChangeParamEx.Value)
}
err = st.state.UpdateAsset(asset)
if err == nil {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("AssetID", assetValueChangeParamEx.AssetID))
} else {
st.addLog(common.AssetValueChangeFunc, assetValueChangeParamEx, common.NewKeyValue("Error", "error update asset"))
}
return err
case common.EmptyFunc:
case common.MakeSwapFunc, common.MakeSwapFuncExt:
outputCommandInfo("MakeSwapFunc", "from", st.msg.From())
notation := st.state.GetNotation(st.msg.From())
makeSwapParam := common.MakeSwapParam{}
rlp.DecodeBytes(param.Data, &makeSwapParam)
swapId := st.msg.AsTransaction().Hash()
_, err := st.state.GetSwap(swapId)
if err == nil {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "Swap already exist"))
return fmt.Errorf("Swap already exist")
}
if err := makeSwapParam.Check(height, timestamp); err != nil {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
var useAsset bool
var total *big.Int
var needValue *common.TimeLock
if _, err := st.state.GetAsset(makeSwapParam.ToAssetID); err != nil {
err := fmt.Errorf("ToAssetID's asset not found")
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
if makeSwapParam.FromAssetID == common.OwnerUSANAssetID {
if notation == 0 {
err := fmt.Errorf("the from address does not have a notation")
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
makeSwapParam.MinFromAmount = big.NewInt(1)
makeSwapParam.SwapSize = big.NewInt(1)
makeSwapParam.FromStartTime = common.TimeLockNow
makeSwapParam.FromEndTime = common.TimeLockForever
useAsset = true
total = new(big.Int).Mul(makeSwapParam.MinFromAmount, makeSwapParam.SwapSize)
} else {
total = new(big.Int).Mul(makeSwapParam.MinFromAmount, makeSwapParam.SwapSize)
start := makeSwapParam.FromStartTime
end := makeSwapParam.FromEndTime
useAsset = start == common.TimeLockNow && end == common.TimeLockForever
if useAsset == false {
needValue = common.NewTimeLock(&common.TimeLockItem{
StartTime: common.MaxUint64(start, timestamp),
EndTime: end,
Value: total,
})
if err := needValue.IsValid(); err != nil {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", err.Error()))
return fmt.Errorf(err.Error())
}
}
}
swap := common.Swap{
ID: swapId,
Owner: st.msg.From(),
FromAssetID: makeSwapParam.FromAssetID,
FromStartTime: makeSwapParam.FromStartTime,
FromEndTime: makeSwapParam.FromEndTime,
MinFromAmount: makeSwapParam.MinFromAmount,
ToAssetID: makeSwapParam.ToAssetID,
ToStartTime: makeSwapParam.ToStartTime,
ToEndTime: makeSwapParam.ToEndTime,
MinToAmount: makeSwapParam.MinToAmount,
SwapSize: makeSwapParam.SwapSize,
Targes: makeSwapParam.Targes,
Time: makeSwapParam.Time, // this will mean the block time
Description: makeSwapParam.Description,
Notation: notation,
}
if makeSwapParam.FromAssetID == common.OwnerUSANAssetID {
if err := st.state.AddSwap(swap); err != nil {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "System error can't add swap"))
return err
}
} else {
if useAsset == true {
if st.state.GetBalance(makeSwapParam.FromAssetID, st.msg.From()).Cmp(total) < 0 {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "not enough from asset"))
return fmt.Errorf("not enough from asset")
}
} else {
available := st.state.GetTimeLockBalance(makeSwapParam.FromAssetID, st.msg.From())
if available.Cmp(needValue) < 0 {
if param.Func == common.MakeSwapFunc {
// this was the legacy swap do not do
// time lock and just return an error
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "not enough time lock or asset balance"))
return fmt.Errorf("not enough time lock balance")
}
if st.state.GetBalance(makeSwapParam.FromAssetID, st.msg.From()).Cmp(total) < 0 {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "not enough time lock or asset balance"))
return fmt.Errorf("not enough time lock or asset balance")
}
// subtract the asset from the balance
st.state.SubBalance(st.msg.From(), makeSwapParam.FromAssetID, total)
totalValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: timestamp,
EndTime: common.TimeLockForever,
Value: total,
})
st.state.AddTimeLockBalance(st.msg.From(), makeSwapParam.FromAssetID, totalValue, height, timestamp)
}
}
if err := st.state.AddSwap(swap); err != nil {
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("Error", "System error can't add swap"))
return err
}
// take from the owner the asset
if useAsset == true {
st.state.SubBalance(st.msg.From(), makeSwapParam.FromAssetID, total)
} else {
st.state.SubTimeLockBalance(st.msg.From(), makeSwapParam.FromAssetID, needValue, height, timestamp)
}
}
st.addLog(common.MakeSwapFunc, makeSwapParam, common.NewKeyValue("SwapID", swap.ID))
return nil
case common.RecallSwapFunc:
outputCommandInfo("RecallSwapFunc", "from", st.msg.From())
recallSwapParam := common.RecallSwapParam{}
rlp.DecodeBytes(param.Data, &recallSwapParam)
swap, err := st.state.GetSwap(recallSwapParam.SwapID)
if err != nil {
st.addLog(common.RecallSwapFunc, recallSwapParam, common.NewKeyValue("Error", "Swap not found"))
return fmt.Errorf("Swap not found")
}
if swap.Owner != st.msg.From() {
st.addLog(common.RecallSwapFunc, recallSwapParam, common.NewKeyValue("Error", "Must be swap onwer can recall"))
return fmt.Errorf("Must be swap onwer can recall")
}
if err := recallSwapParam.Check(height, &swap); err != nil {
st.addLog(common.RecallSwapFunc, recallSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
if err := st.state.RemoveSwap(swap.ID); err != nil {
st.addLog(common.RecallSwapFunc, recallSwapParam, common.NewKeyValue("Error", "Unable to remove swap"))
return err
}
if swap.FromAssetID != common.OwnerUSANAssetID {
total := new(big.Int).Mul(swap.MinFromAmount, swap.SwapSize)
start := swap.FromStartTime
end := swap.FromEndTime
useAsset := start == common.TimeLockNow && end == common.TimeLockForever
// return to the owner the balance
if useAsset == true {
st.state.AddBalance(st.msg.From(), swap.FromAssetID, total)
} else {
needValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: common.MaxUint64(start, timestamp),
EndTime: end,
Value: total,
})
if err := needValue.IsValid(); err == nil {
st.state.AddTimeLockBalance(st.msg.From(), swap.FromAssetID, needValue, height, timestamp)
}
}
}
st.addLog(common.RecallSwapFunc, recallSwapParam, common.NewKeyValue("SwapID", swap.ID))
return nil
case common.TakeSwapFunc, common.TakeSwapFuncExt:
outputCommandInfo("TakeSwapFunc", "from", st.msg.From())
takeSwapParam := common.TakeSwapParam{}
rlp.DecodeBytes(param.Data, &takeSwapParam)
swap, err := st.state.GetSwap(takeSwapParam.SwapID)
if err != nil {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "swap not found"))
return fmt.Errorf("Swap not found")
}
if err := takeSwapParam.Check(height, &swap, timestamp); err != nil {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
if common.IsPrivateSwapCheckingEnabled(height) {
if err := common.CheckSwapTargets(swap.Targes, st.msg.From()); err != nil {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
}
var usanSwap bool
if swap.FromAssetID == common.OwnerUSANAssetID {
notation := st.state.GetNotation(swap.Owner)
if notation == 0 || notation != swap.Notation {
err := fmt.Errorf("notation in swap is no longer valid")
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", err.Error()))
return err
}
usanSwap = true
} else {
usanSwap = false
}
fromTotal := new(big.Int).Mul(swap.MinFromAmount, takeSwapParam.Size)
fromStart := swap.FromStartTime
fromEnd := swap.FromEndTime
fromUseAsset := fromStart == common.TimeLockNow && fromEnd == common.TimeLockForever
toTotal := new(big.Int).Mul(swap.MinToAmount, takeSwapParam.Size)
toStart := swap.ToStartTime
toEnd := swap.ToEndTime
toUseAsset := toStart == common.TimeLockNow && toEnd == common.TimeLockForever
var fromNeedValue *common.TimeLock
var toNeedValue *common.TimeLock
if fromUseAsset == false {
fromNeedValue = common.NewTimeLock(&common.TimeLockItem{
StartTime: common.MaxUint64(fromStart, timestamp),
EndTime: fromEnd,
Value: fromTotal,
})
}
if toUseAsset == false {
toNeedValue = common.NewTimeLock(&common.TimeLockItem{
StartTime: common.MaxUint64(toStart, timestamp),
EndTime: toEnd,
Value: toTotal,
})
}
if toUseAsset == true {
if st.state.GetBalance(swap.ToAssetID, st.msg.From()).Cmp(toTotal) < 0 {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "not enough from asset"))
return fmt.Errorf("not enough from asset")
}
} else {
isValid := true
if err := toNeedValue.IsValid(); err != nil {
isValid = false
}
available := st.state.GetTimeLockBalance(swap.ToAssetID, st.msg.From())
if isValid && available.Cmp(toNeedValue) < 0 {
if param.Func == common.TakeSwapFunc {
// this was the legacy swap do not do
// time lock and just return an error
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "not enough time lock balance"))
return fmt.Errorf("not enough time lock balance")
}
if st.state.GetBalance(swap.ToAssetID, st.msg.From()).Cmp(toTotal) < 0 {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "not enough time lock balance"))
return fmt.Errorf("not enough time lock or asset balance")
}
// subtract the asset from the balance
st.state.SubBalance(st.msg.From(), swap.ToAssetID, toTotal)
totalValue := common.NewTimeLock(&common.TimeLockItem{
StartTime: timestamp,
EndTime: common.TimeLockForever,
Value: toTotal,
})
st.state.AddTimeLockBalance(st.msg.From(), swap.ToAssetID, totalValue, height, timestamp)
}
}
swapDeleted := "false"
if swap.SwapSize.Cmp(takeSwapParam.Size) == 0 {
if err := st.state.RemoveSwap(swap.ID); err != nil {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "System Error"))
return err
}
swapDeleted = "true"
} else {
swap.SwapSize = swap.SwapSize.Sub(swap.SwapSize, takeSwapParam.Size)
if err := st.state.UpdateSwap(swap); err != nil {
st.addLog(common.TakeSwapFunc, takeSwapParam, common.NewKeyValue("Error", "System Error"))
return err
}