-
Notifications
You must be signed in to change notification settings - Fork 15
/
apply_context.go
1464 lines (1195 loc) · 47.2 KB
/
apply_context.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 chain
import (
"fmt"
"github.com/eosspark/eos-go/chain/types"
. "github.com/eosspark/eos-go/chain/types/generated_containers"
"github.com/eosspark/eos-go/common"
"github.com/eosspark/eos-go/common/eos_math"
"github.com/eosspark/eos-go/crypto"
"github.com/eosspark/eos-go/crypto/rlp"
"github.com/eosspark/eos-go/database"
"github.com/eosspark/eos-go/entity"
. "github.com/eosspark/eos-go/exception"
. "github.com/eosspark/eos-go/exception/try"
"github.com/eosspark/eos-go/log"
"os"
"reflect"
"unsafe"
)
type ApplyContext struct {
Control *Controller
DB *database.LDataBase
TrxContext *TransactionContext
Act *types.Action
Receiver common.AccountName
UsedAuthorizations []bool
RecurseDepth uint32
Privileged bool
ContextFree bool
UsedContestFreeApi bool
Trace types.ActionTrace
idx64 *Idx64
idx128 *Idx128
idx256 *Idx256
idxDouble *IdxDouble
idxLongDouble *IdxLongDouble
//GenericIndex
KeyvalCache *iteratorCache
Notified []common.AccountName
InlineActions []types.Action
CfaInlineActions []types.Action
PendingConsoleOutput string
AccountRamDeltas AccountDeltaSet
ilog log.Logger
// PseudoStart common.TimePoint
// BilledTime common.TimePoint
}
func NewApplyContext(control *Controller, trxContext *TransactionContext, act *types.Action, recurseDepth uint32) *ApplyContext {
applyContext := &ApplyContext{
Control: control,
DB: (control.DB).(*database.LDataBase),
TrxContext: trxContext,
Act: act,
Receiver: act.Account,
UsedAuthorizations: make([]bool, len(act.Authorization)), //to false
RecurseDepth: recurseDepth,
Privileged: false,
ContextFree: false,
UsedContestFreeApi: false,
//KeyvalCache: NewIteratorCache(),
}
applyContext.KeyvalCache = NewIteratorCache()
applyContext.Notified = []common.AccountName{}
applyContext.InlineActions = []types.Action{}
applyContext.CfaInlineActions = []types.Action{}
applyContext.idx64 = NewIdx64(applyContext)
applyContext.idx128 = NewIdx128(applyContext)
applyContext.idx256 = NewIdx256(applyContext)
applyContext.idxDouble = NewIdxDouble(applyContext)
applyContext.idxLongDouble = NewIdxLongDouble(applyContext)
applyContext.AccountRamDeltas = *NewAccountDeltaSet()
applyContext.ilog = log.New("Apply_Context")
logHandler := log.StreamHandler(os.Stdout, log.TerminalFormat(true))
//applyContext.ilog.SetHandler(log.LvlFilterHandler(log.LvlDebug, logHandler))
applyContext.ilog.SetHandler(log.LvlFilterHandler(log.LvlInfo, logHandler))
// applyContext.ilog.SetHandler(log.DiscardHandler())
return applyContext
}
type pairTableIterator struct {
tableIDObject *entity.TableIdObject
iterator int
}
type iteratorCache struct {
tableCache map[common.IdType]*pairTableIterator
endIteratorToTable []*entity.TableIdObject
iteratorToObject []interface{}
objectToIterator map[interface{}]int
}
func NewIteratorCache() *iteratorCache {
i := iteratorCache{
tableCache: make(map[common.IdType]*pairTableIterator),
// endIteratorToTable: make([]*entity.TableIdObject, 8),
// iteratorToObject: make([]interface{}, 32),
endIteratorToTable: []*entity.TableIdObject{},
iteratorToObject: []interface{}{},
objectToIterator: make(map[interface{}]int),
}
return &i
}
func (i *iteratorCache) endIteratorToIndex(ei int) int { return (-ei - 2) }
func (i *iteratorCache) IndexToEndIterator(index int) int { return -(index + 2) }
func (i *iteratorCache) cacheTable(tobj *entity.TableIdObject) int {
if itr, ok := i.tableCache[tobj.ID]; ok {
itr.tableIDObject = tobj
return itr.iterator
}
if len(i.endIteratorToTable) >= 8 {
return 0 // an invalid iterator
}
ei := i.IndexToEndIterator(len(i.endIteratorToTable))
i.endIteratorToTable = append(i.endIteratorToTable, tobj)
pair := &pairTableIterator{
tableIDObject: tobj,
iterator: ei,
}
i.tableCache[tobj.ID] = pair
return ei
}
func (i *iteratorCache) getTable(id common.IdType) *entity.TableIdObject {
if itr, ok := i.tableCache[id]; ok {
return itr.tableIDObject
}
EosAssert(false, &TableNotInCache{}, "an invariant was broken, table should be in cache")
return &entity.TableIdObject{}
}
func (i *iteratorCache) getEndIteratorByTableID(id common.IdType) int {
if itr, ok := i.tableCache[id]; ok {
return itr.iterator
}
EosAssert(false, &TableNotInCache{}, "an invariant was broken, table should be in cache")
return -1
}
func (i *iteratorCache) findTablebyEndIterator(ei int) *entity.TableIdObject {
EosAssert(ei < -1, &InvalidTableIterator{}, "not an end iterator")
index := i.endIteratorToIndex(ei)
if index >= len(i.endIteratorToTable) {
return nil
}
return i.endIteratorToTable[index]
}
func (i *iteratorCache) get(iterator int) interface{} {
EosAssert(iterator != -1, &InvalidTableIterator{}, "invalid iterator")
EosAssert(iterator >= 0, &TableOperationNotPermitted{}, "dereference of end iterator")
EosAssert(iterator < len(i.iteratorToObject), &InvalidTableIterator{}, "iterator out of range")
obj := i.iteratorToObject[iterator]
EosAssert(obj != nil, &TableOperationNotPermitted{}, "dereference of deleted object")
return obj
}
func (i *iteratorCache) remove(iterator int) {
EosAssert(iterator != -1, &InvalidTableIterator{}, "invalid iterator")
EosAssert(iterator >= 0, &TableOperationNotPermitted{}, "dereference of end iterator")
EosAssert(iterator < len(i.iteratorToObject), &InvalidTableIterator{}, "iterator out of range")
obj := i.iteratorToObject[iterator]
if obj == nil {
return
}
i.iteratorToObject[iterator] = nil
// bytes, _ := rlp.EncodeToBytes(obj)
// key := *crypto.NewSha256Byte(bytes)
delete(i.objectToIterator, obj)
}
func (i *iteratorCache) add(obj interface{}) int {
bytes, _ := rlp.EncodeToBytes(obj)
key := *crypto.NewSha256Byte(bytes)
// if itr, ok := i.objectToIterator[key]; ok {
// return itr
// }
for object, itr := range i.objectToIterator {
bytesObject, _ := rlp.EncodeToBytes(object)
keyObject := *crypto.NewSha256Byte(bytesObject)
if keyObject == key {
return itr
}
}
if len(i.iteratorToObject) >= 32 {
return -1
}
i.iteratorToObject = append(i.iteratorToObject, obj)
i.objectToIterator[obj] = len(i.iteratorToObject) - 1
return len(i.iteratorToObject) - 1
}
func (a *ApplyContext) printDebug(receiver common.AccountName, at *types.ActionTrace) {
if len(at.Console) != 0 {
prefix := fmt.Sprintf("\n[(%s,%s)->%s]", common.S(uint64(at.Act.Account)), common.S(uint64(at.Act.Name)), common.S(uint64(receiver)))
fmt.Println(prefix, ": CONSOLE OUTPUT BEGIN =====================")
fmt.Println(at.Console)
fmt.Println(prefix, ": CONSOLE OUTPUT END =====================")
}
}
func (a *ApplyContext) execOne(trace *types.ActionTrace) {
start := common.Now() //common.TimePoint.now()
r := types.ActionReceipt{}
r.Receiver = a.Receiver
r.ActDigest = *crypto.Hash256(a.Act)
trace.TrxId = a.TrxContext.ID
trace.BlockNum = a.Control.PendingBlockState().BlockNum
trace.BlockTime = types.NewBlockTimeStamp(a.Control.PendingBlockTime())
trace.ProducerBlockId = a.Control.PendingProducerBlockId()
trace.Act = *a.Act
trace.ContextFree = a.ContextFree
//cfg := a.Control.GetGlobalProperties().Configuration
Try(func() {
Try(func() {
account := a.Control.GetAccount(a.Receiver)
a.Privileged = account.Privileged
native := a.Control.FindApplyHandler(a.Receiver, a.Act.Account, a.Act.Name)
//a.ilog.Info("receiver:%v account:%v action:%v", a.Receiver, a.Act.Account, a.Act.Name)
if native != nil {
if a.TrxContext.CanSubjectivelyFail && a.Control.IsProducingBlock() {
a.Control.CheckContractList(a.Receiver)
a.Control.CheckActionList(a.Act.Account, a.Act.Name)
}
native(a)
}
if len(account.Code) > 0 &&
!(a.Act.Account == common.DefaultConfig.SystemAccountName && a.Act.Name == common.ActionName(common.N("setcode")) &&
a.Receiver == common.DefaultConfig.SystemAccountName) {
if a.TrxContext.CanSubjectivelyFail && a.Control.IsProducingBlock() {
a.Control.CheckContractList(a.Receiver)
a.Control.CheckActionList(a.Act.Account, a.Act.Name)
}
//try
a.Control.GetWasmInterface().Apply(&account.CodeVersion, account.Code, a)
//}catch(const wasm_exit&){}
}
}).FcCaptureAndRethrow("pending console output: %s", a.PendingConsoleOutput).End()
}).Catch(func(e Exception) {
trace.Receipt = r
trace.Except = e
a.FinalizeTrace(trace, &start)
Throw(e)
}).End()
r.GlobalSequence = a.nextGlobalSequence()
r.RecvSequence = a.nextRecvSequence(a.Receiver)
accountSequence := entity.AccountSequenceObject{Name: a.Act.Account}
a.DB.Find("byName", accountSequence, &accountSequence)
r.CodeSequence = common.Vuint32(accountSequence.CodeSequence)
r.AbiSequence = common.Vuint32(accountSequence.AbiSequence)
r.AuthSequence = *NewAccountNameUint64Map()
for _, auth := range a.Act.Authorization {
r.AuthSequence.Put(auth.Actor, a.nextAuthSequence(auth.Actor))
}
trace.Receipt = r
a.TrxContext.Executed = append(a.TrxContext.Executed, r)
a.FinalizeTrace(trace, &start)
if a.Control.ContractsConsole() {
a.printDebug(a.Receiver, trace)
}
}
func (a *ApplyContext) FinalizeTrace(trace *types.ActionTrace, start *common.TimePoint) {
trace.AccountRamDeltas = a.AccountRamDeltas
//a.AccountRamDeltas.clear()
trace.Console = a.PendingConsoleOutput
a.resetConsole()
trace.Elapsed = common.Now().Sub(*start)
}
func (a *ApplyContext) Exec(trace *types.ActionTrace) {
a.Notified = append(a.Notified, a.Receiver)
a.execOne(trace)
for k, r := range a.Notified {
if k == 0 { //skip self
continue
}
a.Receiver = r
t := types.ActionTrace{}
trace.InlineTraces = append(trace.InlineTraces, t)
a.execOne(&trace.InlineTraces[len(trace.InlineTraces)-1])
}
if len(a.CfaInlineActions) > 0 || len(a.InlineActions) > 0 {
EosAssert(a.RecurseDepth < uint32(a.Control.GetGlobalProperties().Configuration.MaxInlineActionDepth),
&TransactionException{},
"inline action recursion depth reached")
}
for _, inlineAction := range a.CfaInlineActions {
trace.InlineTraces = append(trace.InlineTraces, types.ActionTrace{})
a.TrxContext.DispatchAction(&trace.InlineTraces[len(trace.InlineTraces)-1], &inlineAction, inlineAction.Account, true, a.RecurseDepth+1)
}
for _, inlineAction := range a.InlineActions {
trace.InlineTraces = append(trace.InlineTraces, types.ActionTrace{})
a.TrxContext.DispatchAction(&trace.InlineTraces[len(trace.InlineTraces)-1], &inlineAction, inlineAction.Account, false, a.RecurseDepth+1)
}
}
//context action api
func (a *ApplyContext) GetActionData() []byte { return a.Act.Data }
func (a *ApplyContext) GetReceiver() common.AccountName { return a.Receiver }
func (a *ApplyContext) GetCode() common.AccountName { return a.Act.Account }
func (a *ApplyContext) GetAct() common.ActionName { return a.Act.Name }
//func (a *ApplyContext) RequireAuthorizations(account common.AccountName) {}
func (a *ApplyContext) IsAccount(n int64) bool {
account := entity.AccountObject{Name: common.AccountName(n)}
return a.DB.Find("byName", account, &account) == nil
}
//context authorization api
func (a *ApplyContext) RequireAuthorization(account int64) {
//return
for k, v := range a.Act.Authorization {
if v.Actor == common.AccountName(account) {
a.UsedAuthorizations[k] = true
return
}
}
EosAssert(false, &MissingAuthException{}, "missing authority of %s", common.S(uint64(account)))
}
func (a *ApplyContext) HasAuthorization(account int64) bool {
for _, v := range a.Act.Authorization {
if v.Actor == common.AccountName(account) {
return true
}
}
return false
}
func (a *ApplyContext) RequireAuthorization2(account int64, permission int64) {
for k, v := range a.Act.Authorization {
if v.Actor == common.AccountName(account) && v.Permission == common.PermissionName(permission) {
a.UsedAuthorizations[k] = true
return
}
}
EosAssert(false, &MissingAuthException{}, "missing authority of %s/%s", common.S(uint64(account)), common.S(uint64(permission)))
}
func (a *ApplyContext) HasRecipient(code int64) bool {
for _, a := range a.Notified {
if a == common.AccountName(code) {
return true
}
}
return false
}
func (a *ApplyContext) RequireRecipient(recipient int64) {
if !a.HasRecipient(recipient) {
a.Notified = append(a.Notified, common.AccountName(recipient))
}
a.ilog.Debug("Notified:%v", a.Notified)
}
//context transaction api
func (a *ApplyContext) InlineActionTooBig(dataLen int) bool {
if uint32(dataLen) > a.Control.GetGlobalProperties().Configuration.MaxInlineActionSize {
return true
}
return false
}
//func (a *ApplyContext) ExecuteInline(action []byte) {
func (a *ApplyContext) ExecuteInline(act *types.Action) {
// act := types.Action{}
// rlp.DecodeBytes(action, &act)
a.ilog.Debug("action:%v", act)
code := entity.AccountObject{Name: act.Account}
err := a.DB.Find("byName", code, &code)
EosAssert(err == nil, &ActionValidateException{},
"inline action's code account %s does not exist", common.S(uint64(act.Account)))
for _, auth := range act.Authorization {
actor := entity.AccountObject{Name: auth.Actor}
err := a.DB.Find("byName", actor, &actor)
EosAssert(err == nil, &ActionValidateException{}, "inline action's authorizing actor %s does not exist", common.S(uint64(auth.Actor)))
EosAssert(a.Control.GetAuthorizationManager().FindPermission(&auth) != nil, &ActionValidateException{},
"inline action's authorizations include a non-existent permission:%s",
auth) //todo permissionLevel print
}
if !a.Control.SkipAuthCheck() && !a.Privileged && act.Account != a.Receiver {
checkTime := a.TrxContext.CheckTime
providedKeys := NewPublicKeySet()
providedPermissions := NewPermissionLevelSet()
providedPermissions.Add(common.PermissionLevel{a.Receiver, common.DefaultConfig.EosioCodeName})
a.Control.GetAuthorizationManager().CheckAuthorization([]*types.Action{act},
providedKeys,
providedPermissions,
common.Microseconds(a.Control.PendingBlockTime()-a.TrxContext.Published),
&checkTime,
false)
}
a.InlineActions = append(a.InlineActions, *act)
}
//func (a *ApplyContext) ExecuteContextFreeInline(action []byte) {
func (a *ApplyContext) ExecuteContextFreeInline(act *types.Action) {
// act := types.Action{}
// rlp.DecodeBytes(action, &act)
code := entity.AccountObject{Name: act.Account}
err := a.DB.Find("byName", code, &code)
EosAssert(err == nil, &ActionValidateException{},
"inline action's code account %s does not exist", common.S(uint64(act.Account)))
EosAssert(len(act.Authorization) == 0, &ActionValidateException{},
"context-free actions cannot have authorizations")
a.CfaInlineActions = append(a.CfaInlineActions, *act)
}
func (a *ApplyContext) ScheduleDeferredTransaction(sendId *eos_math.Uint128, payer common.AccountName, trx *types.Transaction, replaceExisting bool) {
EosAssert(len(trx.ContextFreeActions) == 0, &CfaInsideGeneratedTx{}, "context free actions are not currently allowed in generated transactions")
trx.Expiration = common.NewTimePointSecTp(common.MaxTimePoint()) //control.pending_block_time() + fc::microseconds(999'999)
headBlockId := a.Control.HeadBlockId()
trx.SetReferenceBlock(&headBlockId)
a.Control.ValidateReferencedAccounts(trx)
cfg := a.Control.GetGlobalProperties().Configuration
a.TrxContext.AddNetUsage(uint64(cfg.BasePerTransactionNetUsage + common.DefaultConfig.TransactionIdNetUsage))
delay := common.Seconds(int64(trx.DelaySec))
if !a.Control.SkipAuthCheck() && !a.Privileged {
if payer != a.Receiver {
a.RequireAuthorization(int64(payer))
}
checkAuth := false
for _, act := range trx.Actions {
if act.Account != a.Receiver {
checkAuth = true
break
}
}
if checkAuth {
checkTime := a.TrxContext.CheckTime
providedKeys := NewPublicKeySet()
providedPermissions := NewPermissionLevelSet()
providedPermissions.AddItem(common.PermissionLevel{a.Receiver, common.DefaultConfig.EosioCodeName})
a.Control.GetAuthorizationManager().CheckAuthorization(
trx.Actions,
providedKeys,
providedPermissions,
delay,
&checkTime,
false)
}
}
var trxSize uint32 = 0
gto := entity.GeneratedTransactionObject{Sender: a.Receiver, SenderId: *sendId}
err := a.DB.Find("bySenderId", gto, >o)
if err == nil {
EosAssert(replaceExisting, &DeferredTxDuplicate{}, "deferred transaction with the same sender_id and payer already exists")
EosAssert(!a.Control.IsProducingBlock(), &SubjectiveBlockProductionException{}, "Replacing a deferred transaction is temporarily disabled.")
a.DB.Modify(gto, func(obj *entity.GeneratedTransactionObject) {
obj.Sender = a.Receiver
obj.SenderId = *sendId
obj.Payer = payer
obj.Published = a.Control.PendingBlockTime()
obj.DelayUntil = obj.Published + common.TimePoint(delay)
obj.Expiration = obj.DelayUntil + common.TimePoint(common.Seconds(int64(a.Control.GetGlobalProperties().Configuration.DeferredTrxExpirationWindow)))
trxSize = obj.Set(trx)
})
} else {
gto.TrxId = trx.ID()
gto.Sender = a.Receiver
gto.SenderId = *sendId
gto.Payer = payer
gto.Published = a.Control.PendingBlockTime()
gto.DelayUntil = gto.Published + common.TimePoint(delay)
gto.Expiration = gto.DelayUntil + common.TimePoint(common.Seconds(int64(a.Control.GetGlobalProperties().Configuration.DeferredTrxExpirationWindow)))
trxSize = gto.Set(trx)
a.DB.Insert(>o)
}
EosAssert(a.Control.IsRamBillingInNotifyAllowed() || (a.Receiver == payer) || a.Privileged || (a.Receiver == a.Act.Account),
&SubjectiveBlockProductionException{}, "Cannot charge RAM to other accounts during notify.")
a.AddRamUsage(payer, int64(common.BillableSizeV("generated_transaction_object")+uint64(trxSize)))
}
func (a *ApplyContext) CancelDeferredTransaction2(sendId *eos_math.Uint128, sender common.AccountName) bool {
gto := entity.GeneratedTransactionObject{Sender: sender, SenderId: *sendId}
err := a.DB.Find("bySenderId", gto, >o)
if err == nil {
a.AddRamUsage(gto.Payer, -int64(common.BillableSizeV("generated_transaction_object")+uint64(len(gto.PackedTrx))))
a.DB.Remove(>o)
return true
}
return false
}
func (a *ApplyContext) CancelDeferredTransaction(sendId *eos_math.Uint128) bool {
return a.CancelDeferredTransaction2(sendId, a.Receiver)
}
func (a *ApplyContext) FindTable(code uint64, scope uint64, table uint64) *entity.TableIdObject {
tab := entity.TableIdObject{Code: common.AccountName(code),
Scope: common.ScopeName(scope),
Table: common.TableName(table),
}
err := a.DB.Find("byCodeScopeTable", tab, &tab)
if err == nil {
a.ilog.Debug("id:%d code:%v scope:%v table:%v payer:%v count:%d", tab.ID, tab.Code, tab.Scope, tab.Table, tab.Payer, tab.Count)
return &tab
}
//scopeBytes, _ := rlp.EncodeToBytes(tab.Scope)
//a.ilog.Debug(("table:%v"), tab)
return nil
}
func (a *ApplyContext) FindOrCreateTable(code uint64, scope uint64, table uint64, payer uint64) *entity.TableIdObject {
tab := entity.TableIdObject{Code: common.AccountName(code),
Scope: common.ScopeName(scope),
Table: common.TableName(table),
Payer: common.AccountName(payer)}
err := a.DB.Find("byCodeScopeTable", tab, &tab)
if err == nil {
return &tab
}
a.UpdateDbUsage(common.AccountName(payer), int64(common.BillableSizeV("table_id_object")))
a.DB.Insert(&tab)
//scopeBytes, _ := rlp.EncodeToBytes(tab.Scope)
a.ilog.Debug("id:%d code:%v scope:%v table:%v payer:%v count:%d", tab.ID, tab.Code, tab.Scope, tab.Table, tab.Payer, tab.Count)
//a.ilog.Debug(("table:%v"), tab)
return &tab
}
func (a *ApplyContext) RemoveTable(tid entity.TableIdObject) {
a.UpdateDbUsage(tid.Payer, -int64(common.BillableSizeV("table_id_object")))
table := entity.TableIdObject{ID: tid.ID}
a.DB.Remove(&table)
}
//context producer api
func (a *ApplyContext) SetProposedProducers(data []byte) int64 {
producers := []types.ProducerKey{}
rlp.DecodeBytes(data, &producers)
EosAssert(len(producers) <= common.DefaultConfig.MaxProducers,
&WasmExecutionError{},
"Producer schedule exceeds the maximum producer count for this chain")
uniqueProducers := make(map[types.ProducerKey]bool)
for _, p := range producers {
EosAssert(a.IsAccount(int64(p.ProducerName)), &WasmExecutionError{}, "producer schedule includes a nonexisting account")
EosAssert(p.BlockSigningKey.Valid(), &WasmExecutionError{}, "producer schedule includes an invalid key")
if _, ok := uniqueProducers[p]; !ok {
uniqueProducers[p] = true
}
}
EosAssert(len(producers) == len(uniqueProducers), &WasmExecutionError{}, "duplicate producer name in producer schedule")
return a.Control.SetProposedProducers(producers)
}
func (a *ApplyContext) GetActiveProducersInBytes() (data []byte) {
ap := a.Control.ActiveProducers()
accounts := make([]common.AccountName, len(ap.Producers))
for i, producer := range ap.Producers {
accounts[i] = producer.ProducerName
}
//bytes, _ := rlp.EncodeToBytes(&accounts)
//bytes := (*[]byte)(unsafe.Pointer(&accounts))
//return bytes
sv := reflect.ValueOf(accounts)
h := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
h.Cap = sv.Cap() * int(sv.Type().Elem().Size())
h.Len = sv.Len() * int(sv.Type().Elem().Size())
h.Data = sv.Pointer()
return
}
//context console api
func (a *ApplyContext) resetConsole() {
a.PendingConsoleOutput = ""
}
func (a *ApplyContext) ContextAppend(str string) { a.PendingConsoleOutput += str }
//func (a *ApplyContext) GetActiveProducers() []common.AccountName { return }
// func (a *ApplyContext) GetPackedTransaction() []byte {
// bytes, err := rlp.EncodeToBytes(a.TrxContext.Trx)
// if err != nil {
// return []byte{}
// }
// return bytes
// }
//func (a *ApplyContext) GetPackedTransaction() *types.SignedTransaction {
// return a.TrxContext.Trx
//}
func (a *ApplyContext) GetPackedTransaction() *types.Transaction {
return &a.TrxContext.Trx.Transaction
}
func (a *ApplyContext) UpdateDbUsage(payer common.AccountName, delta int64) {
if delta > 0 {
if !(a.Privileged || payer == a.Receiver) {
EosAssert(a.Control.IsRamBillingInNotifyAllowed() || a.Receiver == a.Act.Account,
&SubjectiveBlockProductionException{},
"Cannot charge RAM to other accounts during notify.")
a.RequireAuthorization(int64(payer))
//fmt.Println(payer)
}
}
a.AddRamUsage(payer, delta)
}
// func (a *ApplyContext) GetAction(typ uint32, index int, bufferSize int) (int, []byte) {
// trx := a.TrxContext.Trx
// var a_ptr *types.Action
// if typ == 0 {
// if index >= len(trx.ContextFreeActions) {
// return -1, nil
// }
// a_ptr = trx.ContextFreeActions[index]
// } else if typ == 1 {
// if index >= len(trx.Actions) {
// return -1, nil
// }
// a_ptr = trx.Actions[index]
// }
// EosAssert(a_ptr != nil, &ActionNotFoundException{}, "action is not found")
// s, _ := rlp.EncodeSize(a_ptr)
// if s <= bufferSize {
// bytes, _ := rlp.EncodeToBytes(a_ptr)
// return s, bytes
// }
// return s, nil
// }
func (a *ApplyContext) GetAction(typ uint32, index int) *types.Action {
trx := a.TrxContext.Trx
var a_ptr *types.Action
if typ == 0 {
if index >= len(trx.ContextFreeActions) {
return nil
}
a_ptr = trx.ContextFreeActions[index]
} else if typ == 1 {
if index >= len(trx.Actions) {
return nil
}
a_ptr = trx.Actions[index]
}
EosAssert(a_ptr != nil, &ActionNotFoundException{}, "action is not found")
return a_ptr
}
func (a *ApplyContext) GetContextFreeData(index int, bufferSize int) (int, []byte) {
trx := a.TrxContext.Trx
if index >= len(trx.ContextFreeData) {
return -1, nil
}
s := len(trx.ContextFreeData[index])
if bufferSize == 0 {
return s, nil
}
copySize := common.Min(uint64(bufferSize), uint64(s))
return int(copySize), trx.ContextFreeData[index][0:copySize]
}
//context database api
func (a *ApplyContext) DbStoreI64(scope uint64, table uint64, payer uint64, id uint64, buffer []byte) int {
return a.dbStoreI64(uint64(a.Receiver), scope, table, payer, id, buffer)
}
func (a *ApplyContext) dbStoreI64(code uint64, scope uint64, table uint64, payer uint64, id uint64, buffer []byte) int {
//a.ilog.Debug("code:%v scope:%v table:%v payer:%v id:%d buffer:%v",
// common.AccountName(code), common.ScopeName(scope), common.TableName(table), common.AccountName(payer), id, buffer)
tab := a.FindOrCreateTable(code, scope, table, payer)
tid := tab.ID
EosAssert(payer != 0, &InvalidTablePayer{}, "must specify a valid account to pay for new record")
obj := entity.KeyValueObject{
TId: tid,
PrimaryKey: uint64(id),
Value: buffer,
Payer: common.AccountName(payer),
}
a.DB.Insert(&obj)
a.DB.Modify(tab, func(t *entity.TableIdObject) {
t.Count++
})
// int64_t billable_size = (int64_t)(buffer_size + config::billable_size_v<key_value_object>);
billableSize := int64(len(buffer)) + int64(common.BillableSizeV("key_value_object"))
a.UpdateDbUsage(common.AccountName(payer), billableSize)
a.KeyvalCache.cacheTable(tab)
iteratorOut := a.KeyvalCache.add(&obj)
//a.ilog.Debug("object:%v iteratorOut:%d code:%v scope:%v table:%v payer:%v id:%d",
// obj, iteratorOut, common.AccountName(code), common.ScopeName(scope), common.TableName(table), common.AccountName(payer), id)
a.ilog.Debug("object:%v iteratorOut:%d", obj, iteratorOut)
return iteratorOut
}
func (a *ApplyContext) DbUpdateI64(iterator int, payer uint64, buffer []byte) {
obj := (a.KeyvalCache.get(iterator)).(*entity.KeyValueObject)
objTable := a.KeyvalCache.getTable(obj.TId)
a.ilog.Debug("object:%v iteratorIn:%d payer:%v", *obj, iterator, payer)
a.ilog.Debug("buffer:%v iterator:%d payer:%v", buffer, iterator, payer)
EosAssert(objTable.Code == a.Receiver, &TableAccessViolation{}, "db access violation")
overhead := common.BillableSizeV("key_value_object")
oldSize := int64(len(obj.Value)) + int64(overhead)
newSize := int64(len(buffer)) + int64(overhead)
payerAccount := common.AccountName(payer)
if payerAccount == common.AccountName(0) {
payerAccount = obj.Payer
}
if obj.Payer != payerAccount {
a.UpdateDbUsage(obj.Payer, -(oldSize))
a.UpdateDbUsage(payerAccount, newSize)
} else if oldSize != newSize {
a.UpdateDbUsage(obj.Payer, newSize-oldSize)
}
a.DB.Modify(obj, func(obj *entity.KeyValueObject) {
obj.Value = buffer
obj.Payer = payerAccount
})
}
func (a *ApplyContext) DbRemoveI64(iterator int) {
obj := (a.KeyvalCache.get(iterator)).(*entity.KeyValueObject)
objTable := a.KeyvalCache.getTable(obj.TId)
EosAssert(objTable.Code == a.Receiver, &TableAccessViolation{}, "db access violation")
// // require_write_lock( table_obj.scope );
billableSize := int64(len(obj.Value)) + int64(common.BillableSizeV("key_value_object"))
a.UpdateDbUsage(obj.Payer, -billableSize)
a.DB.Modify(objTable, func(t *entity.TableIdObject) {
t.Count--
})
a.ilog.Debug("object:%#v iteratorIn:%d ", *obj, iterator)
a.DB.Remove(obj)
if objTable.Count == 0 {
a.DB.Remove(objTable)
}
a.KeyvalCache.remove(iterator)
}
func (a *ApplyContext) DbGetI64(iterator int, buffer []byte, bufferSize int) int {
obj := (a.KeyvalCache.get(iterator)).(*entity.KeyValueObject)
s := len(obj.Value)
if bufferSize == 0 {
return s
}
copySize := int(common.Min(uint64(bufferSize), uint64(s)))
copy(buffer[0:copySize], obj.Value[0:copySize])
a.ilog.Debug("object:%v iteratorIn:%d ", *obj, iterator)
return copySize
}
func (a *ApplyContext) DbNextI64(iterator int, primary *uint64) int {
if iterator < -1 { // cannot increment past end iterator of table
return -1
}
obj := (a.KeyvalCache.get(iterator)).(*entity.KeyValueObject)
idx, _ := a.DB.GetIndex("byScopePrimary", obj)
itr := idx.IteratorTo(obj)
ok := itr.Next()
objKeyval := entity.KeyValueObject{}
if ok {
itr.Data(&objKeyval)
}
if idx.CompareEnd(itr) || objKeyval.TId != obj.TId {
return a.KeyvalCache.getEndIteratorByTableID(obj.TId)
}
*primary = objKeyval.PrimaryKey
iteratorOut := a.KeyvalCache.add(&objKeyval)
a.ilog.Debug("object:%v iteratorIn:%d iteratorOut:%d", objKeyval, iterator, iteratorOut)
return iteratorOut
}
func (a *ApplyContext) DbPreviousI64(iterator int, primary *uint64) int {
idx, _ := a.DB.GetIndex("byScopePrimary", entity.KeyValueObject{})
if iterator < -1 { // is end iterator
tab := a.KeyvalCache.findTablebyEndIterator(iterator)
EosAssert(tab != nil, &InvalidTableIterator{}, "not a valid end iterator")
obj := entity.KeyValueObject{TId: tab.ID}
itr, _ := idx.UpperBound(&obj, database.SKIP_ONE)
if idx.CompareIterator(idx.Begin(), idx.End()) || idx.CompareBegin(itr) {
a.ilog.Info("iterator is the begin(nil), iteratorIn:%d iteratorOut:%d", iterator, -1) // Empty table
return -1
}
itr.Prev()
objPrev := entity.KeyValueObject{}
itr.Data(&objPrev)
if objPrev.TId != tab.ID {
a.ilog.Info("previous iterator out of tid, iteratorIn:%d iteratorOut:%d", iterator, -1) // Empty table
return -1
}
*primary = objPrev.PrimaryKey
//return a.KeyvalCache.add(&objPrev)
iteratorOut := a.KeyvalCache.add(&objPrev)
a.ilog.Info("object:%#v iteratorIn:%d iteratorOut:%d", objPrev, iterator, iteratorOut)
return iteratorOut
}
obj := (a.KeyvalCache.get(iterator)).(*entity.KeyValueObject)
itr := idx.IteratorTo(obj)
if idx.CompareBegin(itr) {
return -1 // cannot decrement past beginning iterator of table
}
itr.Prev()
objPrev := entity.KeyValueObject{}
itr.Data(&objPrev)
if objPrev.TId != obj.TId {
return -1 // cannot decrement past beginning iterator of table
}
*primary = objPrev.PrimaryKey
iteratorOut := a.KeyvalCache.add(&objPrev)
a.ilog.Debug("object:%#v iteratorIn:%d iteratorOut:%d", objPrev, iterator, iteratorOut)
return iteratorOut
}
func (a *ApplyContext) DbFindI64(code uint64, scope uint64, table uint64, id uint64) int {
tab := a.FindTable(code, scope, table)
if tab == nil {
a.ilog.Debug("iteratorOut: -1 ")
return -1
}
tableEndItr := a.KeyvalCache.cacheTable(tab)
obj := entity.KeyValueObject{
TId: tab.ID,
PrimaryKey: uint64(id),
}
err := a.DB.Find("byScopePrimary", obj, &obj)
//a.ilog.Debug("object:%#v iteratorOut:%d code:%d scope:%d table:%d id:%d", obj, iteratorOut, code, scope, table, id)
if err != nil {
return tableEndItr
}
iteratorOut := a.KeyvalCache.add(&obj)
//a.ilog.Debug("object:%v iteratorOut:%d code:%v scope:%v table:%v id:%d",
// obj, iteratorOut, common.AccountName(code), common.ScopeName(scope), common.TableName(table), id)
a.ilog.Debug("object:%v iteratorOut:%d ", obj, iteratorOut)
return iteratorOut
}
func (a *ApplyContext) DbLowerboundI64(code uint64, scope uint64, table uint64, id uint64) int {
tab := a.FindTable(code, scope, table)
if tab == nil {
return -1
}
tableEndItr := a.KeyvalCache.cacheTable(tab)
obj := entity.KeyValueObject{TId: tab.ID, PrimaryKey: uint64(id)}
idx, _ := a.DB.GetIndex("byScopePrimary", &obj)
itr, _ := idx.LowerBound(&obj)
if idx.CompareEnd(itr) {
return tableEndItr
}
objLowerbound := entity.KeyValueObject{}
itr.Data(&objLowerbound)
if objLowerbound.TId != tab.ID {
return tableEndItr
}
iteratorOut := a.KeyvalCache.add(&objLowerbound)
a.ilog.Debug("object:%#v iteratorOut:%d code:%v scope:%v table:%v id:%d",
objLowerbound, iteratorOut, common.AccountName(code), common.ScopeName(scope), common.TableName(table), id)
return iteratorOut
}
func (a *ApplyContext) DbUpperboundI64(code uint64, scope uint64, table uint64, id uint64) int {
tab := a.FindTable(code, scope, table)
if tab == nil {
return -1
}
tableEndItr := a.KeyvalCache.cacheTable(tab)