-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtransaction_context.cpp
896 lines (758 loc) · 42.5 KB
/
transaction_context.cpp
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
#include <eosio/chain/apply_context.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/authorization_manager.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/transaction_object.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/deep_mind.hpp>
#include <bit>
namespace eosio::chain {
transaction_checktime_timer::transaction_checktime_timer(platform_timer& timer)
: _timer(timer) {
}
void transaction_checktime_timer::start(fc::time_point tp) {
_timer.start(tp);
}
void transaction_checktime_timer::stop() {
_timer.stop();
}
void transaction_checktime_timer::set_expiration_callback(void(*func)(void*), void* user) {
_timer.set_expiration_callback(func, user);
}
transaction_checktime_timer::~transaction_checktime_timer() {
stop();
_timer.set_expiration_callback(nullptr, nullptr);
}
transaction_context::transaction_context( controller& c,
const packed_transaction& t,
const transaction_id_type& trx_id,
transaction_checktime_timer&& tmr,
action_digests_t::store_which_t store_which,
fc::time_point s,
transaction_metadata::trx_type type)
:control(c)
,packed_trx(t)
,id(trx_id)
,undo_session()
,trace(std::make_shared<transaction_trace>())
,start(s)
,executed_action_receipts(store_which)
,transaction_timer(std::move(tmr))
,trx_type(type)
,pseudo_start(s)
{
initialize();
}
void transaction_context::reset() {
undo();
*trace = transaction_trace{}; // reset trace
initialize();
resume_billing_timer(start);
auto sw = executed_action_receipts.store_which();
executed_action_receipts = action_digests_t{sw};
bill_to_accounts.clear();
validate_ram_usage.clear();
}
void transaction_context::initialize() {
if (!control.skip_db_sessions() && !is_read_only()) {
undo_session.emplace(control.mutable_db().start_undo_session(true));
}
trace->id = id;
trace->block_num = control.head().block_num() + 1;
trace->block_time = control.pending_block_time();
trace->producer_block_id = control.pending_producer_block_id();
trace->net_usage = init_net_usage;
if(auto dm_logger = control.get_deep_mind_logger(is_transient())) {
dm_logger->on_start_transaction();
}
}
transaction_context::~transaction_context()
{
if(auto dm_logger = control.get_deep_mind_logger(is_transient()))
{
dm_logger->on_end_transaction();
}
}
bool transaction_context::has_undo() const {
return !control.skip_db_sessions()
&& !is_read_only()
&& control.get_deep_mind_logger(is_transient()) == nullptr;
}
void transaction_context::disallow_transaction_extensions( const char* error_msg )const {
if( control.is_speculative_block() ) {
EOS_THROW( subjective_block_production_exception, error_msg );
} else {
EOS_THROW( disallowed_transaction_extensions_bad_block_exception, error_msg );
}
}
void transaction_context::init(uint64_t initial_net_usage)
{
EOS_ASSERT( !is_initialized, transaction_exception, "cannot initialize twice" );
init_net_usage = initial_net_usage;
// set maximum to a semi-valid deadline to allow for pause math and conversion to dates for logging
const fc::time_point far_future_time = start + fc::days(7*52);
if( block_deadline == fc::time_point::maximum() ) block_deadline = far_future_time;
const auto& cfg = control.get_global_properties().configuration;
auto& rl = control.get_mutable_resource_limits_manager();
net_limit = rl.get_block_net_limit();
objective_duration_limit = fc::microseconds( rl.get_block_cpu_limit() );
_deadline = start + objective_duration_limit;
// Possibly lower net_limit to the maximum net usage a transaction is allowed to be billed
if( cfg.max_transaction_net_usage <= net_limit && !is_read_only() ) {
net_limit = cfg.max_transaction_net_usage;
net_limit_due_to_block = false;
}
// Possibly lower objective_duration_limit to the maximum cpu usage a transaction is allowed to be billed
if( cfg.max_transaction_cpu_usage <= objective_duration_limit.count() && !is_read_only() ) {
objective_duration_limit = fc::microseconds(cfg.max_transaction_cpu_usage);
billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;
tx_cpu_usage_reason = tx_cpu_usage_exceeded_reason::on_chain_consensus_max_transaction_cpu_usage;
_deadline = start + objective_duration_limit;
}
const transaction& trx = packed_trx.get_transaction();
// Possibly lower net_limit to optional limit set in the transaction header
uint64_t trx_specified_net_usage_limit = static_cast<uint64_t>(trx.max_net_usage_words.value) * 8;
if( trx_specified_net_usage_limit > 0 && trx_specified_net_usage_limit <= net_limit ) {
net_limit = trx_specified_net_usage_limit;
net_limit_due_to_block = false;
}
// Possibly lower objective_duration_limit to optional limit set in transaction header
if( trx.max_cpu_usage_ms > 0 ) {
auto trx_specified_cpu_usage_limit = fc::milliseconds(trx.max_cpu_usage_ms);
if( trx_specified_cpu_usage_limit <= objective_duration_limit ) {
objective_duration_limit = trx_specified_cpu_usage_limit;
billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;
tx_cpu_usage_reason = tx_cpu_usage_exceeded_reason::user_specified_trx_max_cpu_usage_ms;
_deadline = start + objective_duration_limit;
}
}
initial_objective_duration_limit = objective_duration_limit;
int64_t account_net_limit = 0;
int64_t account_cpu_limit = 0;
if ( !is_read_only() ) {
if( explicit_billed_cpu_time )
validate_cpu_usage_to_bill( billed_cpu_time_us, std::numeric_limits<int64_t>::max(), false, subjective_cpu_bill_us); // Fail early if the amount to be billed is too high
// Record accounts to be billed for network and CPU usage
if( control.is_builtin_activated(builtin_protocol_feature_t::only_bill_first_authorizer) ) {
bill_to_accounts.insert( trx.first_authorizer() );
} else {
for( const auto& act : trx.actions ) {
for( const auto& auth : act.authorization ) {
bill_to_accounts.insert( auth.actor );
}
}
}
validate_ram_usage.reserve( bill_to_accounts.size() );
// Update usage values of accounts to reflect new time
rl.update_account_usage( bill_to_accounts, block_timestamp_type(control.pending_block_time()).slot );
// Calculate the highest network usage and CPU time that all of the billed accounts can afford to be billed
bool greylisted_net = false, greylisted_cpu = false;
std::tie( account_net_limit, account_cpu_limit, greylisted_net, greylisted_cpu) = max_bandwidth_billed_accounts_can_pay();
net_limit_due_to_greylist |= greylisted_net;
cpu_limit_due_to_greylist |= greylisted_cpu;
}
eager_net_limit = net_limit;
if ( !is_read_only() ) {
// Possibly lower eager_net_limit to what the billed accounts can pay plus some (objective) leeway
auto new_eager_net_limit = std::min( eager_net_limit, static_cast<uint64_t>(account_net_limit + cfg.net_usage_leeway) );
if( new_eager_net_limit < eager_net_limit ) {
eager_net_limit = new_eager_net_limit;
net_limit_due_to_block = false;
}
// Possibly limit deadline if the duration accounts can be billed for (+ a subjective leeway) does not exceed current delta
if( (fc::microseconds(account_cpu_limit) + leeway) <= (_deadline - start) ) {
_deadline = start + fc::microseconds(account_cpu_limit) + leeway;
billing_timer_exception_code = leeway_deadline_exception::code_value;
}
}
// Possibly limit deadline to subjective max_transaction_time
if( max_transaction_time_subjective != fc::microseconds::maximum() && (start + max_transaction_time_subjective) <= _deadline ) {
_deadline = start + max_transaction_time_subjective;
tx_cpu_usage_reason = billed_cpu_time_us > 0 ?
tx_cpu_usage_exceeded_reason::speculative_executed_adjusted_max_transaction_time : tx_cpu_usage_exceeded_reason::node_configured_max_transaction_time;
billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;
}
// Possibly limit deadline to caller provided wall clock block deadline
if( block_deadline < _deadline ) {
_deadline = block_deadline;
billing_timer_exception_code = deadline_exception::code_value;
}
if ( !is_read_only() ) {
if( !explicit_billed_cpu_time ) {
int64_t validate_account_cpu_limit = account_cpu_limit - subjective_cpu_bill_us + leeway.count(); // Add leeway to allow powerup
// Possibly limit deadline to account subjective cpu left
if( subjective_cpu_bill_us > 0 && (start + fc::microseconds(validate_account_cpu_limit) < _deadline) ) {
_deadline = start + fc::microseconds(validate_account_cpu_limit);
billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;
tx_cpu_usage_reason = tx_cpu_usage_exceeded_reason::account_cpu_limit;
}
// Fail early if amount of the previous speculative execution is within 10% of remaining account cpu available
if( validate_account_cpu_limit > 0 )
validate_account_cpu_limit -= EOS_PERCENT( validate_account_cpu_limit, 10 * config::percent_1 );
if( validate_account_cpu_limit < 0 ) validate_account_cpu_limit = 0;
validate_account_cpu_usage_estimate( billed_cpu_time_us, validate_account_cpu_limit, subjective_cpu_bill_us );
}
}
// Explicit billed_cpu_time_us should be used, block_deadline will be maximum unless in test code
if( explicit_billed_cpu_time ) {
_deadline = block_deadline;
deadline_exception_code = deadline_exception::code_value;
} else {
deadline_exception_code = billing_timer_exception_code;
}
eager_net_limit = (eager_net_limit/8)*8; // Round down to nearest multiple of word size (8 bytes) so check_net_usage can be efficient
if( initial_net_usage > 0 )
add_net_usage( initial_net_usage ); // Fail early if current net usage is already greater than the calculated limit
if(control.skip_trx_checks()) {
_deadline = block_deadline;
}
if(_deadline < far_future_time)
transaction_timer.start( _deadline );
else
transaction_timer.start( fc::time_point::maximum() ); //avoids overhead in starting the timer at all
checktime(); // Fail early if deadline has already been exceeded
is_initialized = true;
}
void transaction_context::init_for_implicit_trx()
{
const transaction& trx = packed_trx.get_transaction();
if( trx.transaction_extensions.size() > 0 ) {
disallow_transaction_extensions( "no transaction extensions supported yet for implicit transactions" );
}
published = control.pending_block_time();
init(0);
}
void transaction_context::init_for_input_trx( uint64_t packed_trx_unprunable_size,
uint64_t packed_trx_prunable_size )
{
const transaction& trx = packed_trx.get_transaction();
// delayed transactions are not allowed after protocol feature
// DISABLE_DEFERRED_TRXS_STAGE_1 is activated;
// read-only and dry-run transactions are not allowed to be delayed at any time
if( control.is_builtin_activated(builtin_protocol_feature_t::disable_deferred_trxs_stage_1) || is_transient() ) {
EOS_ASSERT( trx.delay_sec.value == 0, transaction_exception, "transaction cannot be delayed" );
}
if( trx.transaction_extensions.size() > 0 ) {
disallow_transaction_extensions( "no transaction extensions supported yet for input transactions" );
}
const auto& cfg = control.get_global_properties().configuration;
uint64_t discounted_size_for_pruned_data = packed_trx_prunable_size;
if( cfg.context_free_discount_net_usage_den > 0
&& cfg.context_free_discount_net_usage_num < cfg.context_free_discount_net_usage_den )
{
discounted_size_for_pruned_data *= cfg.context_free_discount_net_usage_num;
discounted_size_for_pruned_data = ( discounted_size_for_pruned_data + cfg.context_free_discount_net_usage_den - 1)
/ cfg.context_free_discount_net_usage_den; // rounds up
}
uint64_t initial_net_usage = static_cast<uint64_t>(cfg.base_per_transaction_net_usage)
+ packed_trx_unprunable_size + discounted_size_for_pruned_data;
if( trx.delay_sec.value > 0 ) {
// If delayed, also charge ahead of time for the additional net usage needed to retire the delayed transaction
// whether that be by successfully executing, soft failure, hard failure, or expiration.
initial_net_usage += static_cast<uint64_t>(cfg.base_per_transaction_net_usage)
+ static_cast<uint64_t>(config::transaction_id_net_usage);
}
published = control.pending_block_time();
is_input = true;
if (!control.skip_trx_checks()) {
if ( !is_read_only() ) {
control.validate_expiration(trx);
control.validate_tapos(trx);
}
validate_referenced_accounts( trx, enforce_whiteblacklist && control.is_speculative_block() );
}
init( initial_net_usage );
if ( !is_read_only() ) {
record_transaction( id, trx.expiration );
}
}
void transaction_context::init_for_deferred_trx( fc::time_point p )
{
const transaction& trx = packed_trx.get_transaction();
if( (trx.expiration.sec_since_epoch() != 0) && (trx.transaction_extensions.size() > 0) ) {
disallow_transaction_extensions( "no transaction extensions supported yet for deferred transactions" );
}
// If (trx.expiration.sec_since_epoch() == 0) then it was created after NO_DUPLICATE_DEFERRED_ID activation,
// and so validation of its extensions was done either in:
// * apply_context::schedule_deferred_transaction for contract-generated transactions;
// * or transaction_context::init_for_input_trx for delayed input transactions.
published = p;
trace->scheduled = true;
apply_context_free = false;
init( 0 );
}
void transaction_context::exec() {
EOS_ASSERT( is_initialized, transaction_exception, "must first initialize" );
for (int i = 0; i < 2; ++i) { // interrupt_oc_exception can only happen once
try {
const transaction& trx = packed_trx.get_transaction();
if( apply_context_free ) {
for( const auto& act : trx.context_free_actions ) {
schedule_action( act, act.account, true, 0, 0 );
}
}
if( delay == fc::microseconds() ) {
for( const auto& act : trx.actions ) {
schedule_action( act, act.account, false, 0, 0 );
}
}
auto& action_traces = trace->action_traces;
uint32_t num_original_actions_to_execute = action_traces.size();
for( uint32_t i = 1; i <= num_original_actions_to_execute; ++i ) {
execute_action( i, 0 );
}
if( delay != fc::microseconds() ) {
schedule_transaction();
}
break;
} catch ( const fc::exception& e ) {
if (i == 0 && e.code() == interrupt_oc_exception::code_value) {
reset();
continue;
}
throw;
}
}
}
void transaction_context::finalize() {
EOS_ASSERT( is_initialized, transaction_exception, "must first initialize" );
// read-only transactions only need net_usage and elapsed in the trace
if ( is_read_only() ) {
trace->net_usage = ((trace->net_usage + 7)/8)*8; // Round up to nearest multiple of word size (8 bytes)
trace->elapsed = fc::time_point::now() - start;
return;
}
if( is_input ) {
const transaction& trx = packed_trx.get_transaction();
auto& am = control.get_mutable_authorization_manager();
for( const auto& act : trx.actions ) {
for( const auto& auth : act.authorization ) {
am.update_permission_usage( am.get_permission(auth) );
}
}
}
auto& rl = control.get_mutable_resource_limits_manager();
for( auto a : validate_ram_usage ) {
rl.verify_account_ram_usage( a );
}
// Calculate the new highest network usage and CPU time that all of the billed accounts can afford to be billed
int64_t account_net_limit = 0;
int64_t account_cpu_limit = 0;
bool greylisted_net = false, greylisted_cpu = false;
std::tie( account_net_limit, account_cpu_limit, greylisted_net, greylisted_cpu) = max_bandwidth_billed_accounts_can_pay();
net_limit_due_to_greylist |= greylisted_net;
cpu_limit_due_to_greylist |= greylisted_cpu;
// Possibly lower net_limit to what the billed accounts can pay
if( static_cast<uint64_t>(account_net_limit) <= net_limit ) {
// NOTE: net_limit may possibly not be objective anymore due to net greylisting, but it should still be no greater than the truly objective net_limit
net_limit = static_cast<uint64_t>(account_net_limit);
net_limit_due_to_block = false;
}
// Possibly lower objective_duration_limit to what the billed accounts can pay
if( account_cpu_limit <= objective_duration_limit.count() ) {
// NOTE: objective_duration_limit may possibly not be objective anymore due to cpu greylisting, but it should still be no greater than the truly objective objective_duration_limit
objective_duration_limit = fc::microseconds(account_cpu_limit);
billing_timer_exception_code = tx_cpu_usage_exceeded::code_value;
tx_cpu_usage_reason = tx_cpu_usage_exceeded_reason::account_cpu_limit;
}
trace->net_usage = ((trace->net_usage + 7)/8)*8; // Round up to nearest multiple of word size (8 bytes)
eager_net_limit = net_limit;
check_net_usage();
auto now = fc::time_point::now();
trace->elapsed = now - start;
update_billed_cpu_time( now );
validate_cpu_usage_to_bill( billed_cpu_time_us, account_cpu_limit, true, subjective_cpu_bill_us );
rl.add_transaction_usage( bill_to_accounts, static_cast<uint64_t>(billed_cpu_time_us), trace->net_usage,
block_timestamp_type(control.pending_block_time()).slot, is_transient() ); // Should never fail
}
void transaction_context::squash() {
if (undo_session) undo_session->squash();
control.apply_trx_block_context(trx_blk_context);
transaction_timer.stop();
}
void transaction_context::undo() {
if (undo_session) undo_session->undo();
transaction_timer.stop();
}
void transaction_context::check_net_usage()const {
if (!control.skip_trx_checks()) {
if( BOOST_UNLIKELY(trace->net_usage > eager_net_limit) ) {
if ( net_limit_due_to_block ) {
EOS_THROW( block_net_usage_exceeded,
"not enough space left in block: ${net_usage} > ${net_limit}",
("net_usage", trace->net_usage)("net_limit", eager_net_limit) );
} else if (net_limit_due_to_greylist) {
EOS_THROW( greylist_net_usage_exceeded,
"greylisted transaction net usage is too high: ${net_usage} > ${net_limit}",
("net_usage", trace->net_usage)("net_limit", eager_net_limit) );
} else {
EOS_THROW( tx_net_usage_exceeded,
"transaction net usage is too high: ${net_usage} > ${net_limit}",
("net_usage", trace->net_usage)("net_limit", eager_net_limit) );
}
}
}
}
std::string transaction_context::get_tx_cpu_usage_exceeded_reason_msg(fc::microseconds& limit) const {
switch( tx_cpu_usage_reason ) {
case tx_cpu_usage_exceeded_reason::account_cpu_limit:
limit = objective_duration_limit;
return " reached account cpu limit ${limit}us";
case tx_cpu_usage_exceeded_reason::on_chain_consensus_max_transaction_cpu_usage:
limit = objective_duration_limit;
return " reached on chain max_transaction_cpu_usage ${limit}us";
case tx_cpu_usage_exceeded_reason::user_specified_trx_max_cpu_usage_ms:
limit = objective_duration_limit;
return " reached trx specified max_cpu_usage_ms ${limit}us";
case tx_cpu_usage_exceeded_reason::node_configured_max_transaction_time:
limit = max_transaction_time_subjective;
return " reached node configured max-transaction-time ${limit}us";
case tx_cpu_usage_exceeded_reason::speculative_executed_adjusted_max_transaction_time:
limit = max_transaction_time_subjective;
return " reached speculative executed adjusted trx max time ${limit}us";
}
return "unknown tx_cpu_usage_exceeded";
}
void transaction_context::checktime()const {
platform_timer::state_t expired = transaction_timer.timer_state();
if(BOOST_LIKELY(expired == platform_timer::state_t::running))
return;
auto now = fc::time_point::now();
if (expired == platform_timer::state_t::interrupted) {
EOS_THROW( interrupt_exception, "interrupt signaled, ran ${bt}us, start ${s}",
("bt", now - pseudo_start)("s", start) );
} else if( explicit_billed_cpu_time || deadline_exception_code == deadline_exception::code_value ) {
EOS_THROW( deadline_exception, "deadline exceeded ${billing_timer}us",
("billing_timer", now - pseudo_start)("now", now)("deadline", _deadline)("start", start) );
} else if( deadline_exception_code == block_cpu_usage_exceeded::code_value ) {
EOS_THROW( block_cpu_usage_exceeded,
"not enough time left in block to complete executing transaction ${billing_timer}us",
("now", now)("deadline", _deadline)("start", start)("billing_timer", now - pseudo_start) );
} else if( deadline_exception_code == tx_cpu_usage_exceeded::code_value ) {
std::string assert_msg = "transaction ${id} was executing for too long ${billing_timer}us";
if (subjective_cpu_bill_us > 0) {
assert_msg += " with a subjective cpu of (${subjective} us)";
}
fc::microseconds limit;
assert_msg += get_tx_cpu_usage_exceeded_reason_msg(limit);
if (cpu_limit_due_to_greylist) {
assert_msg = "greylisted " + assert_msg;
EOS_THROW( greylist_cpu_usage_exceeded, assert_msg, ("id", packed_trx.id())
("billing_timer", now - pseudo_start)("subjective", subjective_cpu_bill_us)("limit", limit) );
} else {
EOS_THROW( tx_cpu_usage_exceeded, assert_msg, ("id", packed_trx.id())
("billing_timer", now - pseudo_start)("subjective", subjective_cpu_bill_us)("limit", limit) );
}
} else if( deadline_exception_code == leeway_deadline_exception::code_value ) {
EOS_THROW( leeway_deadline_exception,
"the transaction was unable to complete by deadline, "
"but it is possible it could have succeeded if it were allowed to run to completion ${billing_timer}",
("now", now)("deadline", _deadline)("start", start)("billing_timer", now - pseudo_start) );
}
EOS_ASSERT( false, transaction_exception, "unexpected deadline exception code ${code}", ("code", deadline_exception_code) );
}
void transaction_context::pause_billing_timer() {
paused_time = fc::time_point::now();
billed_time = paused_time - pseudo_start;
pseudo_start = fc::time_point();
transaction_timer.stop();
}
void transaction_context::resume_billing_timer(fc::time_point resume_from) {
if (resume_from != fc::time_point()) {
paused_time = resume_from;
}
auto now = fc::time_point::now();
auto paused = now - paused_time;
pseudo_start = now - billed_time;
_deadline += paused;
// do not allow to go past block wall clock deadline
if( block_deadline < _deadline ) {
deadline_exception_code = deadline_exception::code_value;
_deadline = block_deadline;
}
transaction_timer.start(_deadline);
}
void transaction_context::validate_cpu_usage_to_bill( int64_t billed_us, int64_t account_cpu_limit, bool check_minimum, int64_t subjective_billed_us )const {
if (!control.skip_trx_checks()) {
if( check_minimum ) {
const auto& cfg = control.get_global_properties().configuration;
EOS_ASSERT( billed_us >= cfg.min_transaction_cpu_usage, transaction_exception,
"cannot bill CPU time less than the minimum of ${min_billable} us",
("min_billable", cfg.min_transaction_cpu_usage)("billed_cpu_time_us", billed_us)
);
}
validate_account_cpu_usage( billed_us, account_cpu_limit, subjective_billed_us );
}
}
void transaction_context::validate_account_cpu_usage( int64_t billed_us, int64_t account_cpu_limit, int64_t subjective_billed_us )const {
if( (billed_us > 0) && !control.skip_trx_checks() ) {
const bool cpu_limited_by_account = (account_cpu_limit <= objective_duration_limit.count());
if( !cpu_limited_by_account && (billing_timer_exception_code == block_cpu_usage_exceeded::code_value) ) {
EOS_ASSERT( billed_us <= objective_duration_limit.count(),
block_cpu_usage_exceeded,
"billed CPU time (${billed} us) is greater than the billable CPU time left in the block (${billable} us)",
("billed", billed_us)( "billable", objective_duration_limit.count() )
);
} else {
auto graylisted = cpu_limit_due_to_greylist && cpu_limited_by_account;
// exceeds trx.max_cpu_usage_ms or cfg.max_transaction_cpu_usage if objective_duration_limit is greater
auto account_limit = graylisted ? account_cpu_limit : (cpu_limited_by_account ? account_cpu_limit : objective_duration_limit.count());
if( billed_us > account_limit ) {
fc::microseconds tx_limit;
std::string assert_msg;
assert_msg.reserve(1024);
assert_msg += "billed CPU time (${billed} us) is greater than the maximum";
assert_msg += graylisted ? " greylisted" : "";
assert_msg += " billable CPU time for the transaction (${billable} us)";
assert_msg += subjective_billed_us > 0 ? " with a subjective cpu of (${subjective} us)" : "";
assert_msg += get_tx_cpu_usage_exceeded_reason_msg( tx_limit );
if( graylisted ) {
FC_THROW_EXCEPTION( greylist_cpu_usage_exceeded, std::move(assert_msg),
("billed", billed_us)("billable", account_limit)("subjective", subjective_billed_us)("limit", tx_limit) );
} else {
FC_THROW_EXCEPTION( tx_cpu_usage_exceeded, std::move(assert_msg),
("billed", billed_us)("billable", account_limit)("subjective", subjective_billed_us)("limit", tx_limit) );
}
}
}
}
}
void transaction_context::validate_account_cpu_usage_estimate( int64_t prev_billed_us, int64_t account_cpu_limit, int64_t subjective_billed_us )const {
// prev_billed_us can be 0, but so can account_cpu_limit
if( (prev_billed_us >= 0) && !control.skip_trx_checks() ) {
const bool cpu_limited_by_account = (account_cpu_limit <= objective_duration_limit.count());
if( !cpu_limited_by_account && (billing_timer_exception_code == block_cpu_usage_exceeded::code_value) ) {
EOS_ASSERT( prev_billed_us < objective_duration_limit.count(),
block_cpu_usage_exceeded,
"estimated CPU time (${billed} us) is not less than the billable CPU time left in the block (${billable} us)",
("billed", prev_billed_us)( "billable", objective_duration_limit.count() )
);
} else {
auto graylisted = cpu_limit_due_to_greylist && cpu_limited_by_account;
// exceeds trx.max_cpu_usage_ms or cfg.max_transaction_cpu_usage if objective_duration_limit is greater
auto account_limit = graylisted ? account_cpu_limit : (cpu_limited_by_account ? account_cpu_limit : objective_duration_limit.count());
if( prev_billed_us >= account_limit ) {
std::string assert_msg;
assert_msg.reserve(1024);
assert_msg += "estimated CPU time (${billed} us) is not less than the maximum";
assert_msg += graylisted ? " greylisted" : "";
assert_msg += " billable CPU time for the transaction (${billable} us)";
assert_msg += subjective_billed_us > 0 ? " with a subjective cpu of (${subjective} us)" : "";
assert_msg += " reached account cpu limit ${limit}us";
if( graylisted ) {
FC_THROW_EXCEPTION( greylist_cpu_usage_exceeded, std::move(assert_msg),
("billed", prev_billed_us)("billable", account_limit)("subjective", subjective_billed_us)("limit", account_limit) );
} else {
FC_THROW_EXCEPTION( tx_cpu_usage_exceeded, std::move(assert_msg),
("billed", prev_billed_us)("billable", account_limit)("subjective", subjective_billed_us)("limit", account_limit) );
}
}
}
}
}
void transaction_context::add_ram_usage( account_name account, int64_t ram_delta ) {
auto& rl = control.get_mutable_resource_limits_manager();
rl.add_pending_ram_usage( account, ram_delta, is_transient() );
if( ram_delta > 0 ) {
validate_ram_usage.insert( account );
}
}
uint32_t transaction_context::update_billed_cpu_time( fc::time_point now ) {
if( explicit_billed_cpu_time ) return static_cast<uint32_t>(billed_cpu_time_us);
const auto& cfg = control.get_global_properties().configuration;
billed_cpu_time_us = std::max( (now - pseudo_start).count(), static_cast<int64_t>(cfg.min_transaction_cpu_usage) );
return static_cast<uint32_t>(billed_cpu_time_us);
}
std::tuple<int64_t, int64_t, bool, bool> transaction_context::max_bandwidth_billed_accounts_can_pay( bool force_elastic_limits ) const{
// Assumes rl.update_account_usage( bill_to_accounts, block_timestamp_type(control.pending_block_time()).slot ) was already called prior
// Calculate the new highest network usage and CPU time that all of the billed accounts can afford to be billed
auto& rl = control.get_mutable_resource_limits_manager();
const static int64_t large_number_no_overflow = std::numeric_limits<int64_t>::max()/2;
int64_t account_net_limit = large_number_no_overflow;
int64_t account_cpu_limit = large_number_no_overflow;
bool greylisted_net = false;
bool greylisted_cpu = false;
uint32_t specified_greylist_limit = control.get_greylist_limit();
for( const auto& a : bill_to_accounts ) {
uint32_t greylist_limit = config::maximum_elastic_resource_multiplier;
if( !force_elastic_limits && control.is_speculative_block() ) {
if( control.is_resource_greylisted(a) ) {
greylist_limit = 1;
} else {
greylist_limit = specified_greylist_limit;
}
}
auto [net_limit, net_was_greylisted] = rl.get_account_net_limit(a, greylist_limit);
if( net_limit >= 0 ) {
account_net_limit = std::min( account_net_limit, net_limit );
greylisted_net |= net_was_greylisted;
}
auto [cpu_limit, cpu_was_greylisted] = rl.get_account_cpu_limit(a, greylist_limit);
if( cpu_limit >= 0 ) {
account_cpu_limit = std::min( account_cpu_limit, cpu_limit );
greylisted_cpu |= cpu_was_greylisted;
}
}
EOS_ASSERT( (!force_elastic_limits && control.is_speculative_block()) || (!greylisted_cpu && !greylisted_net),
transaction_exception, "greylisted when not producing block" );
return std::make_tuple(account_net_limit, account_cpu_limit, greylisted_net, greylisted_cpu);
}
action_trace& transaction_context::get_action_trace( uint32_t action_ordinal ) {
EOS_ASSERT( 0 < action_ordinal && action_ordinal <= trace->action_traces.size() ,
transaction_exception,
"action_ordinal ${ordinal} is outside allowed range [1,${max}]",
("ordinal", action_ordinal)("max", trace->action_traces.size())
);
return trace->action_traces[action_ordinal-1];
}
const action_trace& transaction_context::get_action_trace( uint32_t action_ordinal )const {
EOS_ASSERT( 0 < action_ordinal && action_ordinal <= trace->action_traces.size() ,
transaction_exception,
"action_ordinal ${ordinal} is outside allowed range [1,${max}]",
("ordinal", action_ordinal)("max", trace->action_traces.size())
);
return trace->action_traces[action_ordinal-1];
}
uint32_t transaction_context::schedule_action( const action& act, account_name receiver, bool context_free,
uint32_t creator_action_ordinal,
uint32_t closest_unnotified_ancestor_action_ordinal )
{
uint32_t new_action_ordinal = trace->action_traces.size() + 1;
trace->action_traces.emplace_back( *trace, act, receiver, context_free,
new_action_ordinal, creator_action_ordinal,
closest_unnotified_ancestor_action_ordinal );
return new_action_ordinal;
}
uint32_t transaction_context::schedule_action( action&& act, account_name receiver, bool context_free,
uint32_t creator_action_ordinal,
uint32_t closest_unnotified_ancestor_action_ordinal )
{
uint32_t new_action_ordinal = trace->action_traces.size() + 1;
trace->action_traces.emplace_back( *trace, std::move(act), receiver, context_free,
new_action_ordinal, creator_action_ordinal,
closest_unnotified_ancestor_action_ordinal );
return new_action_ordinal;
}
uint32_t transaction_context::schedule_action( uint32_t action_ordinal, account_name receiver, bool context_free,
uint32_t creator_action_ordinal,
uint32_t closest_unnotified_ancestor_action_ordinal )
{
uint32_t new_action_ordinal = trace->action_traces.size() + 1;
trace->action_traces.reserve( std::bit_ceil(new_action_ordinal) ); // bit_ceil to avoid vector copy on every reserve call.
const action& provided_action = get_action_trace( action_ordinal ).act;
// The reserve above is required so that the emplace_back below does not invalidate the provided_action reference,
// which references an action within the `trace->action_traces` vector we are appending to.
trace->action_traces.emplace_back( *trace, provided_action, receiver, context_free,
new_action_ordinal, creator_action_ordinal,
closest_unnotified_ancestor_action_ordinal );
return new_action_ordinal;
}
void transaction_context::execute_action( uint32_t action_ordinal, uint32_t recurse_depth ) {
apply_context acontext( control, *this, action_ordinal, recurse_depth );
if (recurse_depth == 0) {
if (auto dm_logger = control.get_deep_mind_logger(is_transient())) {
dm_logger->on_input_action();
}
}
acontext.exec();
}
void transaction_context::schedule_transaction() {
// Charge ahead of time for the additional net usage needed to retire the delayed transaction
// whether that be by successfully executing, soft failure, hard failure, or expiration.
const transaction& trx = packed_trx.get_transaction();
if( trx.delay_sec.value == 0 ) { // Do not double bill. Only charge if we have not already charged for the delay.
const auto& cfg = control.get_global_properties().configuration;
add_net_usage( static_cast<uint64_t>(cfg.base_per_transaction_net_usage)
+ static_cast<uint64_t>(config::transaction_id_net_usage) ); // Will exit early if net usage cannot be payed.
}
auto first_auth = trx.first_authorizer();
uint32_t trx_size = 0;
const auto& cgto = control.mutable_db().create<generated_transaction_object>( [&]( auto& gto ) {
gto.trx_id = id;
gto.payer = first_auth;
gto.sender = account_name(); /// delayed transactions have no sender
gto.sender_id = transaction_id_to_sender_id( gto.trx_id );
gto.published = control.pending_block_time();
gto.delay_until = gto.published + delay;
gto.expiration = gto.delay_until + fc::seconds(control.get_global_properties().configuration.deferred_trx_expiration_window);
trx_size = gto.set( trx );
if (auto dm_logger = control.get_deep_mind_logger(is_transient())) {
std::string event_id = RAM_EVENT_ID("${id}", ("id", gto.id));
dm_logger->on_create_deferred(deep_mind_handler::operation_qualifier::push, gto, packed_trx);
dm_logger->on_ram_trace(std::move(event_id), "deferred_trx", "push", "deferred_trx_pushed");
}
});
int64_t ram_delta = (config::billable_size_v<generated_transaction_object> + trx_size);
add_ram_usage( cgto.payer, ram_delta );
trace->account_ram_delta = account_delta( cgto.payer, ram_delta );
}
void transaction_context::record_transaction( const transaction_id_type& id, fc::time_point_sec expire ) {
try {
control.mutable_db().create<transaction_object>([&](transaction_object& transaction) {
transaction.trx_id = id;
transaction.expiration = expire;
});
} catch( const boost::interprocess::bad_alloc& ) {
throw;
} catch ( ... ) {
EOS_ASSERT( false, tx_duplicate,
"duplicate transaction ${id}", ("id", id ) );
}
} /// record_transaction
void transaction_context::validate_referenced_accounts( const transaction& trx, bool enforce_actor_whitelist_blacklist )const {
const auto& db = control.db();
const auto& auth_manager = control.get_authorization_manager();
if( !trx.context_free_actions.empty() && !control.skip_trx_checks() ) {
for( const auto& a : trx.context_free_actions ) {
auto* code = db.find<account_object, by_name>( a.account );
EOS_ASSERT( code != nullptr, transaction_exception,
"action's code account '${account}' does not exist", ("account", a.account) );
EOS_ASSERT( a.authorization.size() == 0, transaction_exception,
"context-free actions cannot have authorizations" );
}
}
flat_set<account_name> actors;
bool one_auth = false;
for( const auto& a : trx.actions ) {
auto* code = db.find<account_object, by_name>(a.account);
EOS_ASSERT( code != nullptr, transaction_exception,
"action's code account '${account}' does not exist", ("account", a.account) );
if ( is_read_only() ) {
EOS_ASSERT( a.authorization.size() == 0, transaction_exception,
"read-only action '${name}' cannot have authorizations", ("name", a.name) );
}
for( const auto& auth : a.authorization ) {
one_auth = true;
auto* actor = db.find<account_object, by_name>(auth.actor);
EOS_ASSERT( actor != nullptr, transaction_exception,
"action's authorizing actor '${account}' does not exist", ("account", auth.actor) );
EOS_ASSERT( auth_manager.find_permission(auth) != nullptr, transaction_exception,
"action's authorizations include a non-existent permission: ${permission}",
("permission", auth) );
if( enforce_actor_whitelist_blacklist )
actors.insert( auth.actor );
}
}
EOS_ASSERT( one_auth || is_read_only(), tx_no_auths, "transaction must have at least one authorization" );
if( enforce_actor_whitelist_blacklist ) {
control.check_actor_list( actors );
}
}
int64_t transaction_context::set_proposed_producers(vector<producer_authority> producers) {
if (producers.empty())
return -1; // SAVANNA depends on DISALLOW_EMPTY_PRODUCER_SCHEDULE
EOS_ASSERT(producers.size() <= config::max_proposers, wasm_execution_error,
"Producer schedule exceeds the maximum proposer count for this chain");
trx_blk_context.proposed_schedule_block_num = control.head().block_num() + 1;
// proposed_schedule.version is set in assemble_block
trx_blk_context.proposed_schedule.producers = std::move(producers);
return std::numeric_limits<uint32_t>::max();
}
void transaction_context::set_proposed_finalizers(finalizer_policy&& fin_pol) {
trx_blk_context.proposed_fin_pol_block_num = control.head().block_num() + 1;
trx_blk_context.proposed_fin_pol = std::move(fin_pol);
}
} /// eosio::chain