forked from neonevm/neon-evm
-
Notifications
You must be signed in to change notification settings - Fork 6
/
entrypoint.rs
1266 lines (1046 loc) · 50.6 KB
/
entrypoint.rs
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
//! Program entrypoint
#![cfg(not(feature = "no-entrypoint"))]
use std::{
alloc::Layout,
convert::{TryFrom, TryInto},
mem::size_of,
ptr::null_mut,
usize
};
use evm::{
ExitError, ExitFatal, ExitReason, ExitSucceed,
H160, U256,
};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint, entrypoint::{ProgramResult, HEAP_START_ADDRESS},
program_error::{ProgramError}, pubkey::Pubkey,
program::{invoke},
rent::Rent,
sysvar::Sysvar,
keccak::Hasher,
msg,
};
use crate::{
// bump_allocator::BumpAllocator,
config::{ chain_id, token_mint },
account_data::{Account, AccountData, Contract, ACCOUNT_SEED_VERSION, ACCOUNT_MAX_SIZE},
account_storage::{ProgramAccountStorage, /* Sender */ },
solana_backend::{AccountStorage},
transaction::{UnsignedTransaction, verify_tx_signature, check_secp256k1_instruction},
executor_state::{ ExecutorState, ExecutorSubstate, ApplyState },
storage_account::{ StorageAccount },
error::EvmLoaderError,
executor::Machine,
instruction::{EvmInstruction, on_event, on_return},
payment,
token,
token::{create_associated_token_account},
operator::authorized_operator_check,
system::create_pda_account,
utils::is_zero_initialized
};
use crate::solana_program::program_pack::Pack;
type UsedGas = u64;
type EvmResults = (ExitReason, Vec<u8>, Option<ApplyState>);
type CallResult = Result<(Option<EvmResults>,UsedGas), ProgramError>;
const HEAP_LENGTH: usize = 256*1024;
/// Developers can implement their own heap by defining their own
/// `#[global_allocator]`. The following implements a dummy for test purposes
/// but can be flushed out with whatever the developer sees fit.
pub struct BumpAllocator;
impl BumpAllocator {
/// Get occupied memory
#[inline]
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn occupied() -> usize {
const POS_PTR: *mut usize = HEAP_START_ADDRESS as *mut usize;
const TOP_ADDRESS: usize = HEAP_START_ADDRESS + HEAP_LENGTH;
let pos = unsafe{*POS_PTR};
if pos == 0 {0} else {TOP_ADDRESS-pos}
}
}
unsafe impl std::alloc::GlobalAlloc for BumpAllocator {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
const POS_PTR: *mut usize = HEAP_START_ADDRESS as *mut usize;
const TOP_ADDRESS: usize = HEAP_START_ADDRESS + HEAP_LENGTH;
const BOTTOM_ADDRESS: usize = HEAP_START_ADDRESS + size_of::<*mut u8>();
let mut pos = *POS_PTR;
if pos == 0 {
// First time, set starting position
pos = TOP_ADDRESS;
}
pos = pos.saturating_sub(layout.size());
pos &= !(layout.align().saturating_sub(1));
if pos < BOTTOM_ADDRESS {
return null_mut();
}
*POS_PTR = pos;
pos as *mut u8
}
#[inline]
unsafe fn dealloc(&self, _: *mut u8, _layout: Layout) {
// I'm a bump allocator, I don't free
}
}
#[cfg(target_arch = "bpf")]
#[global_allocator]
static mut A: BumpAllocator = BumpAllocator;
// Is't need to save for account:
// 1. ether: [u8;20]
// 2. nonce: u8
// 3. trx_count: u128
// 4. code_size: u32
// 5. storage (all remaining space, if code_size not equal zero)
entrypoint!(process_instruction);
#[allow(clippy::too_many_lines)]
fn process_instruction<'a>(
program_id: &Pubkey,
accounts: &'a [AccountInfo<'a>],
instruction_data: &[u8],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let instruction = EvmInstruction::unpack(instruction_data)?;
debug_print!("Instruction parsed: {:?}", instruction);
#[allow(clippy::match_same_arms)]
let result = match instruction {
EvmInstruction::CreateAccount {lamports: _, space: _, ether, nonce} => {
let rent = Rent::get()?;
let funding_info = next_account_info(account_info_iter)?;
let account_info = next_account_info(account_info_iter)?;
let token_account_info = next_account_info(account_info_iter)?;
authorized_operator_check(funding_info)?;
debug_print!("Ether: {} {}", &(hex::encode(ether)), &hex::encode([nonce]));
if !funding_info.is_signer {
return Err!(ProgramError::InvalidArgument; "!funding_info.is_signer");
}
let mut program_seeds: Vec<&[u8]> = vec![&[ACCOUNT_SEED_VERSION], ether.as_bytes()];
let (expected_address, expected_nonce) = Pubkey::find_program_address(&program_seeds, program_id);
if expected_address != *account_info.key {
return Err!(ProgramError::InvalidArgument; "expected_address<{:?}> != *account_info.key<{:?}>", expected_address, *account_info.key);
};
if expected_nonce != nonce {
return Err!(ProgramError::InvalidArgument; "expected_nonce<{:?}> != nonce<{:?}>", expected_nonce, nonce);
};
let nonce_bytes = &[nonce];
program_seeds.push(nonce_bytes);
let code_account_key = {
let program_code = next_account_info(account_info_iter)?;
if program_code.owner == program_id {
let code_address_seed: &[u8] = &[ &[ACCOUNT_SEED_VERSION], ether.as_bytes() ].concat();
let code_address_seed = bs58::encode(code_address_seed).into_string();
debug_print!("Code account seed: {}", code_address_seed);
let expected_code_address = Pubkey::create_with_seed(funding_info.key, &code_address_seed, program_id)?;
if *program_code.key != expected_code_address {
return Err!(ProgramError::InvalidArgument; "Unexpected code account. Actual<{:?}> != Expected<{:?}>", program_code.key, expected_code_address);
}
if !is_zero_initialized(&program_code.try_borrow_data()?) {
return Err!(ProgramError::InvalidArgument; "Code account is not empty");
}
if !rent.is_exempt(program_code.lamports(), program_code.data_len()) {
return Err!(ProgramError::InvalidArgument; "Code account is not rent exempt. lamports={:?}, data_len={:?}", program_code.lamports(), program_code.data_len());
}
let contract_data = AccountData::Contract( Contract {owner: *account_info.key, code_size: 0_u32} );
contract_data.pack(&mut program_code.data.borrow_mut())?;
*program_code.key
} else {
Pubkey::new_from_array([0_u8; 32])
}
};
create_pda_account(
program_id,
accounts,
account_info,
&program_seeds,
funding_info.key,
ACCOUNT_MAX_SIZE
)?;
debug_print!("create_account done");
invoke(
&create_associated_token_account(funding_info.key, account_info.key, token_account_info.key, &token_mint::id()),
accounts,
)?;
debug_print!("create_associated_token_account done");
AccountData::Account(Account {
ether,
nonce,
trx_count: 0_u64,
code_account: code_account_key,
rw_blocked_acc: None,
eth_token_account: *token_account_info.key,
ro_blocked_cnt: 0_u8,
}).pack(&mut account_info.data.borrow_mut())?;
Ok(())
},
EvmInstruction::ERC20CreateTokenAccount => {
let payer = next_account_info(account_info_iter)?;
let account = next_account_info(account_info_iter)?;
let wallet = next_account_info(account_info_iter)?;
let contract = next_account_info(account_info_iter)?;
let token_mint = next_account_info(account_info_iter)?;
let system_program = next_account_info(account_info_iter)?;
let token_program = next_account_info(account_info_iter)?;
let rent = next_account_info(account_info_iter)?;
authorized_operator_check(payer)?;
if !payer.is_signer {
return Err!(ProgramError::InvalidArgument; "!payer.is_signer");
}
let wallet_data = AccountData::unpack(&wallet.try_borrow_data()?)?;
let wallet_data = wallet_data.get_account()?;
let contract_data = AccountData::unpack(&contract.try_borrow_data()?)?;
let contract_data = contract_data.get_account()?;
if contract_data.code_account == Pubkey::new_from_array([0_u8; 32]) {
return Err!(ProgramError::InvalidArgument; "contract_data.code_account == Pubkey::new_from_array([0_u8; 32])");
}
if *token_mint.owner != spl_token::id() {
return Err!(ProgramError::InvalidArgument; "*token_mint.owner<{:?}> != spl_token::id()", token_mint.owner);
}
spl_token::state::Mint::unpack(&token_mint.try_borrow_data()?)?;
if *system_program.key != solana_program::system_program::id() {
return Err!(ProgramError::InvalidArgument; "*system_program.key<{:?}> != solana_program::system_program::id()", system_program.key);
}
if *token_program.key != spl_token::id() {
return Err!(ProgramError::InvalidArgument; "*token_program.key<{:?}> != spl_token::id()", token_program.key);
}
if *rent.key != solana_program::sysvar::rent::id() {
return Err!(ProgramError::InvalidArgument; "*rent.key<{:?}> != solana_program::sysvar::rent::id()", rent.key);
}
let token_mint_key_bytes = token_mint.key.to_bytes();
let mut seeds: Vec<&[u8]> = vec![
&[ACCOUNT_SEED_VERSION],
b"ERC20Balance",
&token_mint_key_bytes,
contract_data.ether.as_bytes(),
wallet_data.ether.as_bytes()
];
let (expected_address, nonce) = Pubkey::find_program_address(&seeds, program_id);
if *account.key != expected_address {
return Err!(ProgramError::InvalidArgument; "*account.key<{:?}> != expected_address", account.key);
}
let nonce_bytes = &[nonce];
seeds.push(nonce_bytes);
debug_print!("Create program derived account");
create_pda_account(
&spl_token::id(),
accounts,
account,
&seeds,
payer.key,
spl_token::state::Account::LEN
)?;
debug_print!("Initialize token");
let instruction = spl_token::instruction::initialize_account(
&spl_token::id(),
account.key,
token_mint.key,
wallet.key
)?;
invoke(&instruction, accounts)
},
// TODO: EvmInstruction::Call
// https://github.com/neonlabsorg/neon-evm/issues/188
// Does not fit in current vision.
// It is needed to update behavior for all system in whole.
// EvmInstruction::Call {collateral_pool_index, bytes} => {
// let operator_sol_info = next_account_info(account_info_iter)?;
// let collateral_pool_sol_info = next_account_info(account_info_iter)?;
// let system_info = next_account_info(account_info_iter)?;
// let trx_accounts = &accounts[3..];
// let mut account_storage = ProgramAccountStorage::new(program_id, trx_accounts)?;
// if let Sender::Solana(_addr) = account_storage.get_sender() {
// // Success execution
// } else {
// return Err!(ProgramError::InvalidArgument; "This method should used with Solana sender");
// }
// payment::transfer_from_operator_to_collateral_pool(
// program_id,
// collateral_pool_index,
// operator_sol_info,
// collateral_pool_sol_info,
// system_info)?;
// let call_return = do_call(&mut account_storage, trx_accounts, bytes.to_vec(), U256::zero(), u64::MAX)?;
// if let Some(call_results) = call_return {
// applies_and_invokes(
// program_id,
// &mut account_storage,
// trx_accounts,
// None,
// call_results)?;
// }
// Ok(())
// },
EvmInstruction::ExecuteTrxFromAccountDataIterativeV02 {collateral_pool_index, step_count} => {
debug_print!("Execute iterative transaction from account data");
let holder_info = next_account_info(account_info_iter)?;
let storage_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[7..];
let holder_data = holder_info.data.borrow();
let (unsigned_msg, signature) = get_transaction_from_data(&holder_data)?;
let caller = verify_tx_signature(signature, unsigned_msg).map_err(|e| E!(ProgramError::MissingRequiredSignature; "Error={:?}", e))?;
let trx: UnsignedTransaction = rlp::decode(unsigned_msg).map_err(|e| E!(ProgramError::InvalidInstructionData; "DecoderError={:?}", e))?;
do_begin(
collateral_pool_index, step_count, caller, trx,
program_id, trx_accounts, accounts, storage_info,
operator_sol_info, collateral_pool_sol_info,
operator_eth_info, user_eth_info,
system_info,
)?;
Ok(())
},
EvmInstruction::CallFromRawEthereumTX {collateral_pool_index, from_addr, sign: _, unsigned_msg} => {
debug_print!("Execute from raw ethereum transaction");
// Get six accounts needed for payments (note slice accounts[6..] later)
let sysvar_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[6..];
if !operator_sol_info.is_signer {
return Err!(ProgramError::InvalidAccountData);
}
let trx: UnsignedTransaction = rlp::decode(unsigned_msg).map_err(|e| E!(ProgramError::InvalidInstructionData; "DecoderError={:?}", e))?;
let trx_gas_limit = u64::try_from(trx.gas_limit).map_err(|e| E!(ProgramError::InvalidInstructionData; "e={:?}", e))?;
let trx_gas_price = u64::try_from(trx.gas_price).map_err(|e| E!(ProgramError::InvalidInstructionData; "e={:?}", e))?;
// if trx_gas_price < 1_000_000_000_u64 {
// return Err!(ProgramError::InvalidArgument; "trx_gas_price < 1_000_000_000_u64: {} ", trx_gas_price);
// }
StorageAccount::check_for_blocked_accounts(program_id, trx_accounts, true)?;
let mut account_storage = ProgramAccountStorage::new(program_id, trx_accounts)?;
check_secp256k1_instruction(sysvar_info, unsigned_msg.len(), 5_u16)?;
check_ethereum_transaction(&account_storage, &H160::from_slice(from_addr), &trx)?;
payment::transfer_from_operator_to_collateral_pool(
program_id,
collateral_pool_index,
operator_sol_info,
collateral_pool_sol_info,
system_info)?;
let (evm_results, used_gas) = do_call(&mut account_storage, trx.call_data, trx.value, trx_gas_limit)?;
token::user_pays_operator(
trx_gas_price,
used_gas,
user_eth_info,
operator_eth_info,
accounts,
&account_storage
)?;
applies_and_invokes(
program_id,
&mut account_storage,
accounts,
Some(operator_sol_info),
evm_results.unwrap(),
used_gas)?;
Ok(())
},
EvmInstruction::OnReturn {status: _, bytes: _} => {
Ok(())
},
EvmInstruction::OnEvent {address: _, topics: _, data: _} => {
Ok(())
},
EvmInstruction::PartialCallFromRawEthereumTXv02 {collateral_pool_index, step_count, from_addr, sign: _, unsigned_msg} => {
debug_print!("Execute from raw ethereum transaction iterative");
let storage_info = next_account_info(account_info_iter)?;
let sysvar_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[7..];
check_secp256k1_instruction(sysvar_info, unsigned_msg.len(), 13_u16)?;
let caller = H160::from_slice(from_addr);
let trx: UnsignedTransaction = rlp::decode(unsigned_msg)
.map_err(|e| E!(ProgramError::InvalidInstructionData; "DecoderError={:?}", e))?;
do_begin(
collateral_pool_index, step_count, caller, trx,
program_id, trx_accounts, accounts, storage_info,
operator_sol_info, collateral_pool_sol_info,
operator_eth_info, user_eth_info,
system_info,
)?;
Ok(())
},
EvmInstruction::ContinueV02 { collateral_pool_index, step_count } => {
debug_print!("Continue");
let storage_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[6..];
let storage = StorageAccount::restore(storage_info, operator_sol_info).map_err(|err| {
if err == ProgramError::InvalidAccountData {EvmLoaderError::StorageAccountUninitialized.into()}
else {err}
})?;
do_continue_top_level(
storage, step_count, program_id,
accounts, trx_accounts, storage_info,
operator_sol_info, operator_eth_info, user_eth_info,
collateral_pool_index, collateral_pool_sol_info, system_info,
)?;
Ok(())
},
EvmInstruction::CancelWithNonce { nonce } => {
debug_print!("CancelWithNonce");
let storage_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let _operator_eth_info = next_account_info(account_info_iter)?;
let _user_eth_info = next_account_info(account_info_iter)?;
let incinerator_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[6..];
if !operator_sol_info.is_signer {
return Err!(ProgramError::InvalidAccountData);
}
let storage = StorageAccount::restore(storage_info, operator_sol_info).map_err(|err| {
if err == ProgramError::InvalidAccountData {EvmLoaderError::StorageAccountUninitialized.into()}
else {err}
})?;
let custom_error: ProgramError = EvmLoaderError::ExclusiveAccessUnvailable.into();
if let Err(err) = storage.check_accounts(program_id, trx_accounts, false){
if err == custom_error {return Ok(())}
return Err(err)
}
let account_storage = ProgramAccountStorage::new(program_id, trx_accounts)?;
let caller_account_info = account_storage.get_caller_account_info().ok_or_else(||E!(ProgramError::InvalidArgument))?;
let mut caller_account_data = AccountData::unpack(&caller_account_info.try_borrow_data()?)?;
let mut caller_account = caller_account_data.get_mut_account()?;
let (caller, trx_nonce) = storage.caller_and_nonce()?;
if trx_nonce != nonce {
return Err!(ProgramError::InvalidInstructionData; "trx_nonce<{:?}> != nonce<{:?}>", trx_nonce, nonce);
}
if caller_account.ether != caller {
return Err!(ProgramError::InvalidAccountData; "acc.ether<{:?}> != caller<{:?}>", caller_account.ether, caller);
}
caller_account.trx_count += 1;
caller_account_data.pack(&mut caller_account_info.try_borrow_mut_data()?)?;
payment::burn_operators_deposit(
storage_info,
incinerator_info,
)?;
storage.unblock_accounts_and_destroy(program_id, trx_accounts)?;
Ok(())
},
EvmInstruction::PartialCallOrContinueFromRawEthereumTX {collateral_pool_index, step_count, from_addr, sign: _, unsigned_msg} => {
debug_print!("Execute from raw ethereum transaction iterative or continue");
let storage_info = next_account_info(account_info_iter)?;
let sysvar_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[7..];
match StorageAccount::restore(storage_info, operator_sol_info) {
Err(ProgramError::InvalidAccountData) => { // EXCLUDE Err!
check_secp256k1_instruction(sysvar_info, unsigned_msg.len(), 13_u16)?;
let caller = H160::from_slice(from_addr);
let trx: UnsignedTransaction = rlp::decode(unsigned_msg)
.map_err(|e| E!(ProgramError::InvalidInstructionData; "DecoderError={:?}", e))?;
do_begin(
collateral_pool_index, step_count, caller, trx,
program_id, trx_accounts, accounts, storage_info,
operator_sol_info, collateral_pool_sol_info,
operator_eth_info, user_eth_info,
system_info,
)?;
},
Ok(storage) => {
do_continue_top_level(
storage, step_count, program_id,
accounts, trx_accounts, storage_info,
operator_sol_info, operator_eth_info, user_eth_info,
collateral_pool_index, collateral_pool_sol_info, system_info,
)?;
},
Err(err) => return Err(err),
}
Ok(())
},
EvmInstruction::ExecuteTrxFromAccountDataIterativeOrContinue{collateral_pool_index, step_count} => {
debug_print!("Execute iterative transaction from account data or continue");
let holder_info = next_account_info(account_info_iter)?;
let storage_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
let collateral_pool_sol_info = next_account_info(account_info_iter)?;
let operator_eth_info = next_account_info(account_info_iter)?;
let user_eth_info = next_account_info(account_info_iter)?;
let system_info = next_account_info(account_info_iter)?;
authorized_operator_check(operator_sol_info)?;
let trx_accounts = &accounts[7..];
match StorageAccount::restore(storage_info, operator_sol_info) {
Err(ProgramError::InvalidAccountData) => { // EXCLUDE Err!
let holder_data = holder_info.data.borrow();
let (unsigned_msg, signature) = get_transaction_from_data(&holder_data)?;
let caller = verify_tx_signature(signature, unsigned_msg).map_err(|e| E!(ProgramError::MissingRequiredSignature; "Error={:?}", e))?;
let trx: UnsignedTransaction = rlp::decode(unsigned_msg).map_err(|e| E!(ProgramError::InvalidInstructionData; "DecoderError={:?}", e))?;
do_begin(
collateral_pool_index, step_count, caller, trx,
program_id, trx_accounts, accounts, storage_info,
operator_sol_info, collateral_pool_sol_info,
operator_eth_info, user_eth_info,
system_info,
)?;
},
Ok(storage) => {
do_continue_top_level(
storage, step_count, program_id,
accounts, trx_accounts, storage_info,
operator_sol_info, operator_eth_info, user_eth_info,
collateral_pool_index, collateral_pool_sol_info, system_info,
)?;
},
Err(err) => return Err(err),
}
Ok(())
},
EvmInstruction::DeleteAccount { seed } => {
let deleted_acc_info = next_account_info(account_info_iter)?;
let creator_acc_info = next_account_info(account_info_iter)?;
if !creator_acc_info.is_signer {
return Err!(ProgramError::InvalidAccountData; "Creator acc must be signer. Acc {:?}", *creator_acc_info.key);
}
let address = Pubkey::create_with_seed(
creator_acc_info.key,
std::str::from_utf8(seed).map_err(|e| E!(ProgramError::InvalidInstructionData; "Seed decode error={:?}", e))?,
program_id)?;
if *deleted_acc_info.key != address {
return Err!(ProgramError::InvalidAccountData; "Deleted account info doesn't equal to generated. *deleted_acc_info.key<{:?}> != address<{:?}>", *deleted_acc_info.key, address);
}
let data = deleted_acc_info.data.borrow_mut();
let account_data = AccountData::unpack(&data)?;
match account_data {
AccountData::Empty => { },
_ => { return Err!(ProgramError::InvalidAccountData; "Can only delete empty accounts.") },
};
**creator_acc_info.lamports.borrow_mut() = creator_acc_info.lamports().checked_add(deleted_acc_info.lamports()).unwrap();
**deleted_acc_info.lamports.borrow_mut() = 0;
Ok(())
},
EvmInstruction::ResizeStorageAccount {seed} => {
debug_print!("Execute ResizeStorageAccount");
let account_info = next_account_info(account_info_iter)?;
let code_account_info = next_account_info(account_info_iter)?;
let code_account_new_info = next_account_info(account_info_iter)?;
let operator_sol_info = next_account_info(account_info_iter)?;
if !operator_sol_info.is_signer {
return Err!(ProgramError::InvalidAccountData);
}
let mut account_data = AccountData::unpack(&account_info.try_borrow_data()?)?;
let account = account_data.get_mut_account()?;
if account.rw_blocked_acc.is_some() || account.ro_blocked_cnt > 0 {
return Err!(ProgramError::InvalidInstructionData; "Cannot resize account data. Account is blocked {:?}", *account_info.key);
}
if account.code_account != *code_account_info.key {
return Err!(ProgramError::InvalidArgument; "account.code_account<{:?}> != *code_account_info.key<{:?}>", account.code_account, code_account_info.key);
}
if (account.code_account == Pubkey::new_from_array([0; 32])) && (account.trx_count != 0) {
return Err!(ProgramError::InvalidArgument; "Cannot change user account to contract account");
}
let seed = std::str::from_utf8(seed).map_err(|e| E!(ProgramError::InvalidInstructionData; "Seed decode error={:?}", e))?;
let expected_address = Pubkey::create_with_seed(operator_sol_info.key, seed, program_id)?;
if *code_account_new_info.key != expected_address {
return Err!(ProgramError::InvalidArgument; "New code_account must be created by transaction signer");
}
AccountData::unpack(&code_account_new_info.try_borrow_data()?)?.check_empty()?;
let rent = Rent::get()?;
if !rent.is_exempt(code_account_new_info.lamports(), code_account_new_info.data_len()) {
return Err!(ProgramError::InvalidArgument; "New code account is not rent exempt.");
}
account.code_account = *code_account_new_info.key;
account_data.pack(&mut account_info.try_borrow_mut_data()?)?;
if *code_account_info.key == Pubkey::new_from_array([0; 32]) {
let contract_data = AccountData::Contract( Contract {owner: *account_info.key, code_size: 0_u32} );
contract_data.pack(&mut code_account_new_info.try_borrow_mut_data()?)?;
return Ok(());
}
debug_print!("move code and storage from {:?} to {:?}", *code_account_info.key, *code_account_new_info.key);
let mut code_account_data = code_account_info.try_borrow_mut_data()?;
let mut code_account_new_data = code_account_new_info.try_borrow_mut_data()?;
code_account_new_data[..code_account_data.len()].copy_from_slice(&code_account_data);
AccountData::pack(&AccountData::Empty, &mut code_account_data)?;
payment::transfer_from_code_account_to_operator(code_account_info, operator_sol_info, code_account_info.lamports())?;
Ok(())
},
EvmInstruction::WriteHolder { holder_id, offset, bytes} => {
let holder_info = next_account_info(account_info_iter)?;
if holder_info.owner != program_id {
return Err!(ProgramError::InvalidArgument; "holder_account_info.owner<{:?}> != program_id<{:?}>", holder_info.owner, program_id);
}
let operator_info = next_account_info(account_info_iter)?;
if !operator_info.is_signer {
return Err!(ProgramError::InvalidArgument; "operator is not signer <{:?}>", operator_info.key);
}
// proxy_id_bytes = proxy_id.to_bytes((proxy_id.bit_length() + 7) // 8, 'big')
// seed = keccak_256(b'holder' + proxy_id_bytes).hexdigest()[:32]
let bytes_count = std::mem::size_of_val(&holder_id);
let bits_count = bytes_count * 8;
let holder_id_bit_length = bits_count - holder_id.leading_zeros() as usize;
let significant_bytes_count = (holder_id_bit_length + 7) / 8;
let mut hasher = Hasher::default();
hasher.hash(b"holder");
hasher.hash(&holder_id.to_be_bytes()[bytes_count-significant_bytes_count..]);
let output = hasher.result();
let seed = &hex::encode(output)[..32];
let expected_holder_key = Pubkey::create_with_seed(operator_info.key, seed, program_id);
if expected_holder_key.is_err() {
return Err!(ProgramError::InvalidArgument; "invalid seed <{:?}>", seed);
}
if *holder_info.key != expected_holder_key.unwrap() {
return Err!(ProgramError::InvalidArgument; "wrong holder account <{:?}>", holder_info.key);
}
do_write(holder_info, offset, bytes)
},
EvmInstruction::Write |
EvmInstruction::Cancel |
EvmInstruction::Finalise |
EvmInstruction::CreateAccountWithSeed |
EvmInstruction::ExecuteTrxFromAccountDataIterative |
EvmInstruction::PartialCallFromRawEthereumTX |
EvmInstruction::Continue
=> Err!(ProgramError::InvalidInstructionData; "Deprecated instruction"),
};
solana_program::msg!("Total memory occupied: {}", &BumpAllocator::occupied());
result
}
fn get_transaction_from_data(
data: &[u8]
) -> Result<(&[u8], &[u8]), ProgramError>
{
let account_info_data = AccountData::unpack(data)?;
match account_info_data {
AccountData::Empty => (),
_ => return Err!(ProgramError::InvalidAccountData),
};
let (_header, rest) = data.split_at(account_info_data.size());
let (signature, rest) = rest.split_at(65);
let (trx_len, rest) = rest.split_at(8);
let trx_len = trx_len.try_into().ok().map(u64::from_le_bytes).unwrap();
let trx_len = usize::try_from(trx_len).map_err(|e| E!(ProgramError::InvalidInstructionData; "e={:?}", e))?;
let (trx, _rest) = rest.split_at(trx_len as usize);
Ok((trx, signature))
}
fn do_write(account_info: &AccountInfo, offset: u32, bytes: &[u8]) -> ProgramResult {
let mut data = account_info.data.borrow_mut();
let account_data = AccountData::unpack(&data)?;
match account_data {
AccountData::Account(_) | AccountData::Storage(_) | AccountData::ERC20Allowance(_) => {
return Err!(ProgramError::InvalidAccountData);
},
AccountData::Contract(acc) if acc.code_size != 0 => {
return Err!(ProgramError::InvalidAccountData);
},
AccountData::Contract(_) | AccountData::Empty => { },
};
let offset = account_data.size() + offset as usize;
if data.len() < offset + bytes.len() {
return Err!(ProgramError::AccountDataTooSmall; "Account data too small data.len()={:?}, offset={:?}, bytes.len()={:?}", data.len(), offset, bytes.len());
}
data[offset .. offset+bytes.len()].copy_from_slice(bytes);
Ok(())
}
fn do_call(
account_storage: &mut ProgramAccountStorage<'_>,
instruction_data: Vec<u8>,
transfer_value: U256,
gas_limit: u64,
) -> CallResult
{
debug_print!("do_call");
debug_print!(" caller: {}", account_storage.origin());
debug_print!(" contract: {}", account_storage.contract());
let (evm_results,used_gas) = {
let executor_substate = Box::new(ExecutorSubstate::new(gas_limit, account_storage));
let executor_state = ExecutorState::new(executor_substate, account_storage);
let mut executor = Machine::new(executor_state);
debug_print!("Executor initialized");
executor.call_begin(
account_storage.origin(),
account_storage.contract(),
instruction_data,
transfer_value,
gas_limit,
)?;
let (result, exit_reason) = executor.execute();
debug_print!("Call done");
let executor_state = executor.into_state();
let used_gas = executor_state.gasometer().used_gas();
if exit_reason.is_succeed() {
debug_print!("Succeed execution");
let apply = executor_state.deconstruct();
((exit_reason, result, Some(apply)), used_gas)
} else {
((exit_reason, result, None), used_gas)
}
};
Ok((Some(evm_results),used_gas))
}
#[allow(clippy::too_many_arguments)]
fn do_begin<'a>(
collateral_pool_index: u32,
step_count: u64,
caller: H160,
trx: UnsignedTransaction,
program_id: &Pubkey,
trx_accounts: &'a [AccountInfo<'a>],
accounts: &'a [AccountInfo<'a>],
storage_info: &'a AccountInfo<'a>,
operator_sol_info: &'a AccountInfo<'a>,
collateral_pool_sol_info: &'a AccountInfo<'a>,
operator_eth_info: &'a AccountInfo<'a>,
user_eth_info: &'a AccountInfo<'a>,
system_info: &'a AccountInfo<'a>,
) -> ProgramResult
{
if !operator_sol_info.is_signer {
return Err!(ProgramError::InvalidAccountData);
}
let trx_gas_limit = u64::try_from(trx.gas_limit).map_err(|e| E!(ProgramError::InvalidInstructionData; "e={:?}", e))?;
let trx_gas_price = u64::try_from(trx.gas_price).map_err(|e| E!(ProgramError::InvalidInstructionData; "e={:?}", e))?;
token::check_enough_funds(
trx_gas_limit,
trx_gas_price,
user_eth_info,
None)?;
let mut storage = StorageAccount::new(storage_info, operator_sol_info, trx_accounts, caller, trx.nonce, trx_gas_limit, trx_gas_price)?;
StorageAccount::check_for_blocked_accounts(program_id, trx_accounts, false)?;
let account_storage = ProgramAccountStorage::new(program_id, trx_accounts)?;
check_ethereum_transaction(&account_storage, &caller, &trx)?;
payment::transfer_from_operator_to_collateral_pool(
program_id,
collateral_pool_index,
operator_sol_info,
collateral_pool_sol_info,
system_info)?;
payment::transfer_from_operator_to_deposit(
operator_sol_info,
storage_info,
system_info)?;
let (_,used_gas) = if trx.to.is_some() {
do_partial_call(&mut storage, step_count, &account_storage, trx.call_data, trx.value, trx_gas_limit)?
}
else {
do_partial_create(&mut storage, step_count, &account_storage, trx.call_data, trx.value, trx_gas_limit)?
};
token::user_pays_operator_for_iteration(
trx_gas_price, used_gas,
user_eth_info,
operator_eth_info,
accounts,
&account_storage,
&mut storage,
)?;
storage.block_accounts(program_id, trx_accounts)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn do_continue_top_level<'a>(
mut storage: StorageAccount,
step_count: u64,
program_id: &Pubkey,
accounts: &'a [AccountInfo<'a>],
trx_accounts: &'a [AccountInfo<'a>],
storage_info: &'a AccountInfo<'a>,
operator_sol_info: &'a AccountInfo<'a>,
operator_eth_info: &'a AccountInfo<'a>,
user_eth_info: &'a AccountInfo<'a>,
collateral_pool_index: u32,
collateral_pool_sol_info: &'a AccountInfo<'a>,
system_info: &'a AccountInfo<'a>,
) -> ProgramResult
{
if !operator_sol_info.is_signer {
return Err!(ProgramError::InvalidAccountData);
}
let custom_error: ProgramError = EvmLoaderError::ExclusiveAccessUnvailable.into();
if let Err(err) = storage.check_accounts(program_id, trx_accounts, true){
if err == custom_error {
return Ok(())}
return Err(err)
}
let mut account_storage = ProgramAccountStorage::new(program_id, trx_accounts)?;
let (trx_gas_limit, trx_gas_price) = storage.get_gas_params()?;
payment::transfer_from_operator_to_collateral_pool(
program_id,
collateral_pool_index,
operator_sol_info,
collateral_pool_sol_info,
system_info)?;
let (results, used_gas) = {
if let Err(_) = token::check_enough_funds(
trx_gas_limit,
trx_gas_price,
user_eth_info,
Some(&mut storage)) {
let used_gas = storage.get_payments_info()?.0;
(Some((ExitReason::Error(ExitError::OutOfFund), vec![0; 0], None)), used_gas)
} else {
do_continue(&mut storage, step_count, &mut account_storage)?
}
};
token::user_pays_operator_for_iteration(
trx_gas_price, used_gas,
user_eth_info,
operator_eth_info,
accounts,
&account_storage,
&mut storage,
)?;
if let Some(evm_results) = results {
payment::transfer_from_deposit_to_operator(
storage_info,
operator_sol_info)?;
applies_and_invokes(
program_id,
&mut account_storage,
accounts,
Some(operator_sol_info),
evm_results,
used_gas)?;
storage.unblock_accounts_and_destroy(program_id, trx_accounts)?;
}
Ok(())
}
fn do_partial_call<'a>(
storage: &mut StorageAccount,
step_count: u64,
account_storage: &ProgramAccountStorage,
instruction_data: Vec<u8>,
transfer_value: U256,
gas_limit: u64,
) -> CallResult