This repository was archived by the owner on Nov 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpolyjuice.h
1400 lines (1265 loc) · 46.1 KB
/
polyjuice.h
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
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ckb_syscalls.h"
#include <ethash/keccak.hpp>
#include <evmc/evmc.h>
#include <evmc/evmc.hpp>
#include <evmone/evmone.h>
#include "uint256.h"
/* https://stackoverflow.com/a/1545079 */
#pragma push_macro("errno")
#undef errno
#include "godwoken.h"
#include "gw_eth_addr_reg.h"
#include "gw_syscalls.h"
#include "sudt_utils.h"
#pragma pop_macro("errno")
#include "common.h"
#include "polyjuice_errors.h"
#include "polyjuice_utils.h"
#ifdef GW_GENERATOR
#include "generator/secp256k1_helper.h"
#else
#include "validator/secp256k1_helper.h"
#endif
#include "contracts.h"
#define is_create(kind) ((kind) == EVMC_CREATE || (kind) == EVMC_CREATE2)
#define is_special_call(kind) \
((kind) == EVMC_CALLCODE || (kind) == EVMC_DELEGATECALL)
/* Max data buffer size: 24KB */
#define MAX_DATA_SIZE 24576
/* Max evm_memory size 512KB */
#define MAX_EVM_MEMORY_SIZE 524288
#define POLYJUICE_SYSTEM_PREFIX 0xFF
#define POLYJUICE_CONTRACT_CODE 0x01
#define POLYJUICE_DESTRUCTED 0x02
void polyjuice_build_system_key(uint32_t id, uint8_t polyjuice_field_type,
uint8_t key[GW_KEY_BYTES]) {
memset(key, 0, GW_KEY_BYTES);
memcpy(key, (uint8_t*)(&id), sizeof(uint32_t));
key[4] = POLYJUICE_SYSTEM_PREFIX;
key[5] = polyjuice_field_type;
}
void polyjuice_build_contract_code_key(uint32_t id, uint8_t key[GW_KEY_BYTES]) {
polyjuice_build_system_key(id, POLYJUICE_CONTRACT_CODE, key);
}
void polyjuice_build_destructed_key(uint32_t id, uint8_t key[GW_KEY_BYTES]) {
polyjuice_build_system_key(id, POLYJUICE_DESTRUCTED, key);
}
/* assume `account_id` already exists */
int gw_increase_nonce(gw_context_t *ctx, uint32_t account_id, uint32_t *new_nonce) {
uint32_t old_nonce;
int ret = ctx->sys_get_account_nonce(ctx, account_id, &old_nonce);
if (ret != 0) {
return ret;
}
uint32_t next_nonce = old_nonce + 1;
uint8_t nonce_key[GW_KEY_BYTES];
uint8_t nonce_value[GW_VALUE_BYTES];
memset(nonce_value, 0, GW_VALUE_BYTES);
gw_build_account_field_key(account_id, GW_ACCOUNT_NONCE, nonce_key);
memcpy(nonce_value, (uint8_t *)(&next_nonce), 4);
ret = ctx->_internal_store_raw(ctx, nonce_key, nonce_value);
if (ret != 0) {
return ret;
}
if (new_nonce != NULL) {
*new_nonce = next_nonce;
}
return 0;
}
int handle_message(gw_context_t* ctx,
uint32_t parent_from_id,
uint32_t parent_to_id,
evmc_address *parent_destination,
const evmc_message* msg, struct evmc_result* res);
typedef int (*stream_data_loader_fn)(gw_context_t* ctx, long data_id,
uint32_t* len, uint32_t offset,
uint8_t* data);
struct evmc_host_context {
gw_context_t* gw_ctx;
const uint8_t* code_data;
const size_t code_size;
uint32_t from_id;
uint32_t to_id;
evmc_address sender;
evmc_address destination;
int error_code;
};
int load_account_script(gw_context_t* gw_ctx, uint32_t account_id,
uint8_t* buffer, uint32_t buffer_size,
mol_seg_t* script_seg) {
debug_print_int("load_account_script, account_id:", account_id);
int ret;
uint64_t len = buffer_size;
ret = gw_ctx->sys_get_account_script(gw_ctx, account_id, &len, 0, buffer);
if (ret != 0) {
ckb_debug("load account script failed");
return ret;
}
script_seg->ptr = buffer;
script_seg->size = len;
if (MolReader_Script_verify(script_seg, false) != MOL_OK) {
ckb_debug("load account script: invalid script");
return FATAL_POLYJUICE;
}
return 0;
}
// TODO: change gas_limit, gas_price, value to u256
/**
Message = [
header : [u8; 8] 0xff, 0xff, 0xff, "POLY", call_kind
gas_limit : u64 (little endian)
gas_price : u128 (little endian)
value : u128 (little endian)
input_size : u32 (little endian)
input_data : [u8; input_size]
]
*/
int parse_args(struct evmc_message* msg, uint128_t* gas_price,
gw_context_t* ctx) {
gw_transaction_context_t *tx_ctx = &ctx->transaction_context;
debug_print_int("args_len", tx_ctx->args_len);
if (tx_ctx->args_len < (8 + 8 + 16 + 16 + 4)) {
ckb_debug("invalid polyjuice arguments data");
return -1;
}
/* == Args decoder */
size_t offset = 0;
uint8_t* args = tx_ctx->args;
/**
* args[0..8] magic header + call kind
* Only access native eth_address after Polyjuice v1.0.0
*/
static const uint8_t eth_polyjuice_args_header[7]
= {0xff, 0xff, 0xff, 'P', 'O', 'L', 'Y'};
if (memcmp(eth_polyjuice_args_header, args, 7) != 0) {
debug_print_data("invalid polyjuice args header", args, 7);
return -1;
}
debug_print_int("[call_kind]", args[7]);
if (args[7] != EVMC_CALL && args[7] != EVMC_CREATE) {
ckb_debug("invalid call kind");
return -1;
}
evmc_call_kind kind = (evmc_call_kind)args[7];
offset += 8;
/* args[8..16] gas limit */
int64_t gas_limit;
memcpy(&gas_limit, args + offset, sizeof(int64_t));
offset += 8;
debug_print_int("[gas_limit]", gas_limit);
/* args[16..32] gas price */
memcpy(gas_price, args + offset, sizeof(uint128_t));
offset += 16;
debug_print_int("[gas_price]", (int64_t)(*gas_price));
/* args[32..48] transfer value */
evmc_uint256be value{0};
for (size_t i = 0; i < 16; i++) {
value.bytes[31 - i] = args[offset + i];
}
offset += 16;
/* args[48..52] */
uint32_t input_size = *((uint32_t*)(args + offset));
offset += 4;
debug_print_int("[input_size]", input_size);
if (input_size > tx_ctx->args_len) {
/* If input size large enough may overflow `input_size + offset` */
ckb_debug("input_size too large");
return -1;
}
if (tx_ctx->args_len != (input_size + offset)) {
ckb_debug("invalid polyjuice transaction");
return -1;
}
/* args[52..52+input_size] */
uint8_t* input_data = args + offset;
msg->kind = kind;
msg->flags = 0;
msg->depth = 0;
msg->value = value;
msg->input_data = input_data;
msg->input_size = input_size;
msg->gas = gas_limit;
msg->sender = evmc_address{0};
msg->destination = evmc_address{0};
msg->create2_salt = evmc_bytes32{};
return 0;
}
void release_result(const struct evmc_result* result) {
if (result->output_data != NULL) {
free((void*)result->output_data);
}
return;
}
int load_account_code(gw_context_t* gw_ctx, uint32_t account_id,
uint64_t* code_size, uint64_t offset, uint8_t* code) {
int ret;
uint8_t buffer[GW_MAX_SCRIPT_SIZE];
mol_seg_t script_seg;
ret = load_account_script(gw_ctx, account_id, buffer, GW_MAX_SCRIPT_SIZE, &script_seg);
if (ret == GW_ERROR_ACCOUNT_NOT_EXISTS) {
// This is an EoA or other kind of account, and not yet created
debug_print_int("account not found", account_id);
*code_size = 0;
return 0;
}
if (ret != 0) {
return ret;
}
mol_seg_t code_hash_seg = MolReader_Script_get_code_hash(&script_seg);
mol_seg_t hash_type_seg = MolReader_Script_get_hash_type(&script_seg);
mol_seg_t args_seg = MolReader_Script_get_args(&script_seg);
mol_seg_t raw_args_seg = MolReader_Bytes_raw_bytes(&args_seg);
if (raw_args_seg.size != CONTRACT_ACCOUNT_SCRIPT_ARGS_LEN) {
debug_print_int("[load_account_code] invalid account script", account_id);
debug_print_int("[load_account_code] raw_args_seg.size", raw_args_seg.size);
// This is an EoA or other kind of account
*code_size = 0;
return 0;
}
if (memcmp(code_hash_seg.ptr, g_script_code_hash, 32) != 0
|| *hash_type_seg.ptr != g_script_hash_type
/* compare rollup_script_hash */
|| memcmp(raw_args_seg.ptr, g_rollup_script_hash, 32) != 0
/* compare creator account id */
|| memcmp(&g_creator_account_id, raw_args_seg.ptr + 32, sizeof(uint32_t)) != 0
) {
debug_print_int("[load_account_code] creator account id not match for account", account_id);
// This is an EoA or other kind of account
*code_size = 0;
return 0;
}
debug_print_int("[load_account_code] account_id", account_id);
uint8_t key[32];
uint8_t data_hash[32];
polyjuice_build_contract_code_key(account_id, key);
ret = gw_ctx->sys_load(gw_ctx, account_id, key, GW_KEY_BYTES, data_hash);
if (ret != 0) {
debug_print_int("[load_account_code] sys_load failed", ret);
return ret;
}
bool is_data_hash_zero = true;
for (size_t i = 0; i < 32; i++) {
if (data_hash[i] != 0) {
is_data_hash_zero = false;
break;
}
}
if (is_data_hash_zero) {
ckb_debug("[load_account_code] data hash all zero");
*code_size = 0;
return 0;
}
debug_print_int("[load_account_code] code_size before loading", *code_size);
ret = gw_ctx->sys_load_data(gw_ctx, data_hash, code_size, offset, code);
debug_print_int("[load_account_code] code_size after loading", *code_size);
if (ret != 0) {
ckb_debug("[load_account_code] sys_load_data failed");
return ret;
}
if (*code_size > MAX_DATA_SIZE) {
debug_print_int("[load_account_code] code_size can't be larger than",
MAX_DATA_SIZE);
return GW_FATAL_BUFFER_OVERFLOW;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//// Callbacks - EVMC Host Interfaces
////////////////////////////////////////////////////////////////////////////////
struct evmc_tx_context get_tx_context(struct evmc_host_context* context) {
struct evmc_tx_context ctx{0};
memcpy(ctx.tx_origin.bytes, g_tx_origin.bytes, 20);
/* gas price = 1 */
ctx.tx_gas_price.bytes[31] = 0x01;
ctx.block_number = context->gw_ctx->block_info.number;
/*
block_timestamp => second
block_info.timestamp => millisecond
*/
ctx.block_timestamp = context->gw_ctx->block_info.timestamp / 1000;
/* Ethereum block gas limit */
ctx.block_gas_limit = 12500000;
/* 2500000000000000 */
ctx.block_difficulty = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0xe1, 0xbc, 0x9b, 0xf0, 0x40, 0x00,
};
uint8_t *chain_id_ptr = (uint8_t *)(&g_chain_id);
ctx.chain_id.bytes[31] = chain_id_ptr[0];
ctx.chain_id.bytes[30] = chain_id_ptr[1];
ctx.chain_id.bytes[29] = chain_id_ptr[2];
ctx.chain_id.bytes[28] = chain_id_ptr[3];
ctx.chain_id.bytes[27] = chain_id_ptr[4];
ctx.chain_id.bytes[26] = chain_id_ptr[5];
ctx.chain_id.bytes[25] = chain_id_ptr[6];
ctx.chain_id.bytes[24] = chain_id_ptr[7];
/* block_coinbase */
gw_reg_addr_t *block_producer = &context->gw_ctx->block_info.block_producer;
if (block_producer->reg_id != GW_DEFAULT_ETH_REGISTRY_ACCOUNT_ID
|| block_producer->addr_len != ETH_ADDRESS_LEN) {
ckb_debug("[get_tx_context] Error: block_producer is not an Ethereum EOA.");
ckb_debug("[get_tx_context] failed to load block_coinbase address");
context->error_code = GW_FATAL_INVALID_CONTEXT;
} else {
debug_print_data("load block_coinbase eth_address:",
block_producer->addr, ETH_ADDRESS_LEN);
memcpy(ctx.block_coinbase.bytes, block_producer->addr, ETH_ADDRESS_LEN);
}
return ctx;
}
bool account_exists(struct evmc_host_context* context,
const evmc_address* address) {
debug_print_data("BEGIN account_exists", address->bytes, 20);
uint8_t script_hash[32] = {0};
bool exists = true;
int ret = load_script_hash_by_eth_address(context->gw_ctx, address->bytes,
script_hash);
if (ret != 0) {
exists = false;
debug_print_int("[account_exists] load_script_hash_by_eth_address failed",
ret);
}
debug_print_int("END account_exists", (int)exists);
return exists;
}
evmc_bytes32 get_storage(struct evmc_host_context* context,
const evmc_address* address, const evmc_bytes32* key) {
ckb_debug("BEGIN get_storage");
evmc_bytes32 value{0};
int ret = context->gw_ctx->sys_load(context->gw_ctx, context->to_id,
key->bytes, GW_KEY_BYTES,
(uint8_t *)value.bytes);
if (ret != 0) {
debug_print_int("get_storage, sys_load failed", ret);
if (is_fatal_error(ret)) {
context->error_code = ret;
}
}
ckb_debug("END get_storage");
return value;
}
enum evmc_storage_status set_storage(struct evmc_host_context* context,
const evmc_address* address,
const evmc_bytes32* key,
const evmc_bytes32* value) {
ckb_debug("BEGIN set_storage");
evmc_storage_status status = EVMC_STORAGE_ADDED;
int ret = context->gw_ctx->sys_store(context->gw_ctx, context->to_id,
key->bytes, GW_KEY_BYTES, value->bytes);
if (ret != 0) {
debug_print_int("sys_store failed", ret);
if (is_fatal_error(ret)) {
context->error_code = ret;
}
status = EVMC_STORAGE_UNCHANGED;
}
/* TODO: more rich evmc_storage_status */
ckb_debug("END set_storage");
return status;
}
size_t get_code_size(struct evmc_host_context* context,
const evmc_address* address) {
ckb_debug("BEGIN get_code_size");
uint32_t account_id = 0;
int ret = load_account_id_by_eth_address(context->gw_ctx,
address->bytes, &account_id);
if (ret != 0) {
ckb_debug("get contract account id failed");
return 0;
}
uint8_t code[MAX_DATA_SIZE];
uint64_t code_size = MAX_DATA_SIZE;
ret = load_account_code(context->gw_ctx, account_id, &code_size, 0, code);
if (ret != 0) {
debug_print_int("[get_code_size] load_account_code failed", ret);
context->error_code = ret;
return 0;
}
ckb_debug("END get_code_size");
return code_size;
}
evmc_bytes32 get_code_hash(struct evmc_host_context* context,
const evmc_address* address) {
ckb_debug("BEGIN get_code_hash");
evmc_bytes32 hash{0};
uint32_t account_id = 0;
int ret = load_account_id_by_eth_address(context->gw_ctx,
address->bytes, &account_id);
if (ret != 0) {
ckb_debug("get contract account id failed");
context->error_code = ret;
return hash;
}
uint8_t code[MAX_DATA_SIZE];
uint64_t code_size = MAX_DATA_SIZE;
ret = load_account_code(context->gw_ctx, account_id, &code_size, 0, code);
if (ret != 0) {
debug_print_int("[get_code_hash] load_account_code failed", ret);
context->error_code = ret;
return hash;
}
if (code_size > 0) {
union ethash_hash256 hash_result = ethash::keccak256(code, code_size);
memcpy(hash.bytes, hash_result.bytes, 32);
}
ckb_debug("END get_code_hash");
return hash;
}
/**
* @brief Copy code callback function.
*
* This callback function is used by an EVM to request a copy of the code of the
* given account to the memory buffer provided by the EVM. The Client MUST copy
* the requested code, starting with the given offset, to the provided memory
* buffer up to the size of the buffer or the size of the code, whichever is
* smaller.
*
* @param context The pointer to the Host execution context.
* @param address The address of the account.
* @param code_offset The offset of the code to copy.
* @param buffer_data The pointer to the memory buffer allocated by the EVM to
* store a copy of the requested code.
* @param buffer_size The size of the memory buffer.
* @return size_t The number of bytes copied to the buffer by the Client.
*/
size_t copy_code(struct evmc_host_context* context, const evmc_address* address,
size_t code_offset, uint8_t* buffer_data, size_t buffer_size) {
ckb_debug("BEGIN copy_code");
debug_print_int("[copy_code] code_offset", code_offset);
debug_print_int("[copy_code] buffer_size", buffer_size);
uint32_t account_id = 0;
int ret = load_account_id_by_eth_address(context->gw_ctx,
address->bytes, &account_id);
if (ret != 0) {
ckb_debug("get contract account id failed");
context->error_code = ret;
return 0;
}
uint64_t code_size = buffer_size;
ret = load_account_code(context->gw_ctx, account_id, &code_size,
code_offset, buffer_data);
if (ret != 0) {
debug_print_int("[copy_code] load_account_code failed", ret);
context->error_code = ret;
return 0;
}
ckb_debug("END copy_code");
return code_size >= buffer_size ? buffer_size : code_size;
}
evmc_uint256be get_balance(struct evmc_host_context* context,
const evmc_address* address) {
ckb_debug("BEGIN get_balance");
evmc_uint256be balance{};
gw_reg_addr_t addr = new_reg_addr(address->bytes);
uint256_t value = {0};
int ret = sudt_get_balance(context->gw_ctx,
g_sudt_id, /* g_sudt_id account must exists */
addr, &value);
if (ret != 0) {
ckb_debug("sudt_get_balance failed");
context->error_code = FATAL_POLYJUICE;
return balance;
}
uint8_t* value_ptr = (uint8_t*)(&value);
for (int i = 0; i < 32; i++) {
balance.bytes[31 - i] = *(value_ptr + i);
}
debug_print_data("address", address->bytes, 20);
debug_print_data("balance", (uint8_t*)&value, 32);
ckb_debug("END get_balance");
return balance;
}
void selfdestruct(struct evmc_host_context* context,
const evmc_address* address,
const evmc_address* beneficiary) {
gw_reg_addr_t from_addr = new_reg_addr(address->bytes);
uint256_t balance;
int ret = sudt_get_balance(context->gw_ctx,
g_sudt_id, /* g_sudt_id account must exists */
from_addr, &balance);
if (ret != 0) {
ckb_debug("get balance failed");
context->error_code = ret;
return;
}
uint256_t zero = {0};
if (uint256_cmp(balance, zero) == LARGER) {
gw_reg_addr_t to_addr = new_reg_addr(beneficiary->bytes);
ret = sudt_transfer(context->gw_ctx, g_sudt_id,
from_addr,
to_addr,
balance);
if (ret != 0) {
ckb_debug("transfer beneficiary failed");
context->error_code = ret;
return;
}
}
uint8_t raw_key[GW_KEY_BYTES];
uint8_t value[GW_VALUE_BYTES];
polyjuice_build_destructed_key(context->to_id, raw_key);
memset(value, 1, GW_VALUE_BYTES);
ret = context->gw_ctx->_internal_store_raw(context->gw_ctx, raw_key, value);
if (ret != 0) {
ckb_debug("update selfdestruct special key failed");
context->error_code = ret;
}
ckb_debug("END selfdestruct");
return;
}
struct evmc_result call(struct evmc_host_context* context,
const struct evmc_message* msg) {
ckb_debug("BEGIN call");
debug_print_int("msg.gas", msg->gas);
debug_print_int("msg.depth", msg->depth);
debug_print_int("msg.kind", msg->kind);
debug_print_data("call.sender", msg->sender.bytes, 20);
debug_print_data("call.destination", msg->destination.bytes, 20);
int ret;
struct evmc_result res;
memset(&res, 0, sizeof(res));
res.release = release_result;
gw_context_t* gw_ctx = context->gw_ctx;
precompiled_contract_gas_fn contract_gas;
precompiled_contract_fn contract;
if (match_precompiled_address(&msg->destination, &contract_gas, &contract)) {
uint64_t gas_cost = 0;
ret = contract_gas(msg->input_data, msg->input_size, &gas_cost);
if (is_fatal_error(ret)) {
context->error_code = ret;
}
if (ret != 0) {
ckb_debug("call pre-compiled contract gas failed");
res.status_code = EVMC_INTERNAL_ERROR;
return res;
}
if ((uint64_t)msg->gas < gas_cost) {
ckb_debug("call pre-compiled contract out of gas");
res.status_code = EVMC_OUT_OF_GAS;
return res;
}
res.gas_left = msg->gas - (int64_t)gas_cost;
ret = contract(gw_ctx,
context->code_data, context->code_size,
msg->flags == EVMC_STATIC,
msg->input_data, msg->input_size,
(uint8_t**)&res.output_data, &res.output_size);
if (is_fatal_error(ret)) {
context->error_code = ret;
}
if (ret != 0) {
debug_print_int("call pre-compiled contract failed", ret);
res.status_code = EVMC_INTERNAL_ERROR;
return res;
}
res.status_code = EVMC_SUCCESS;
} else {
ret = handle_message(gw_ctx, context->from_id, context->to_id, &context->destination, msg, &res);
if (is_fatal_error(ret)) {
/* stop as soon as possible */
context->error_code = ret;
}
if (ret != 0) {
debug_print_int("inner call failed (transfer/contract call contract)", ret);
if (is_evmc_error(ret)) {
res.status_code = (evmc_status_code)ret;
} else {
res.status_code = EVMC_INTERNAL_ERROR;
}
}
}
debug_print_int("call.res.status_code", res.status_code);
ckb_debug("END call");
return res;
}
evmc_bytes32 get_block_hash(struct evmc_host_context* context, int64_t number) {
ckb_debug("BEGIN get_block_hash");
evmc_bytes32 block_hash{};
int ret = context->gw_ctx->sys_get_block_hash(context->gw_ctx, number,
(uint8_t*)block_hash.bytes);
if (ret != 0) {
ckb_debug("sys_get_block_hash failed");
context->error_code = ret;
return block_hash;
}
ckb_debug("END get_block_hash");
return block_hash;
}
void emit_log(struct evmc_host_context* context, const evmc_address* address,
const uint8_t* data, size_t data_size,
const evmc_bytes32 topics[], size_t topics_count) {
ckb_debug("BEGIN emit_log");
/*
output[ 0..20] = callee_contract.address
output[20..24] = data_size_u32
output[24..24+data_size] = data
ouptut[24+data_size..28+data_size] = topics_count_u32
ouptut[28+data_size..] = topics
*/
size_t output_size = 20 + (4 + data_size) + (4 + topics_count * 32);
uint8_t* output = (uint8_t*)malloc(output_size);
if (output == NULL) {
context->error_code = -1;
return;
}
uint32_t data_size_u32 = (uint32_t)(data_size);
uint32_t topics_count_u32 = (uint32_t)(topics_count);
uint8_t* output_current = output;
memcpy(output_current, address->bytes, 20);
output_current += 20;
memcpy(output_current, (uint8_t*)(&data_size_u32), 4);
output_current += 4;
if (data_size > 0) {
memcpy(output_current, data, data_size);
output_current += data_size;
}
memcpy(output_current, (uint8_t*)(&topics_count_u32), 4);
output_current += 4;
for (size_t i = 0; i < topics_count; i++) {
debug_print_data("log.topic", topics[i].bytes, 32);
memcpy(output_current, topics[i].bytes, 32);
output_current += 32;
}
int ret = context->gw_ctx->sys_log(context->gw_ctx, context->to_id,
GW_LOG_POLYJUICE_USER, (uint32_t)output_size, output);
if (ret != 0) {
ckb_debug("sys_log failed");
context->error_code = ret;
}
free(output);
ckb_debug("END emit_log");
return;
}
/**
* @return 0 if the `to_id` account is not destructed
*/
int check_destructed(gw_context_t* ctx, uint32_t to_id) {
int ret;
uint8_t destructed_raw_key[GW_KEY_BYTES];
uint8_t destructed_raw_value[GW_VALUE_BYTES] = {0};
polyjuice_build_destructed_key(to_id, destructed_raw_key);
ret = ctx->_internal_load_raw(ctx, destructed_raw_key, destructed_raw_value);
if (ret != 0) {
debug_print_int("load destructed key failed", ret);
return ret;
}
bool destructed = true;
for (int i = 0; i < GW_VALUE_BYTES; i++) {
if (destructed_raw_value[i] == 0) {
destructed = false;
break;
}
}
if (destructed) {
ckb_debug("call a contract that was already destructed");
return FATAL_POLYJUICE;
}
return 0;
}
/**
* load the following global values:
* - g_chain_id
* - g_creator_account_id
* - g_script_hash_type
* - g_rollup_script_hash
* - g_sudt_id
*/
int load_globals(gw_context_t* ctx, uint32_t to_id) {
uint8_t buffer[GW_MAX_SCRIPT_SIZE];
mol_seg_t script_seg;
int ret = load_account_script(ctx, to_id, buffer, GW_MAX_SCRIPT_SIZE, &script_seg);
if (ret != 0) {
return ret;
}
mol_seg_t code_hash_seg = MolReader_Script_get_code_hash(&script_seg);
mol_seg_t hash_type_seg = MolReader_Script_get_hash_type(&script_seg);
mol_seg_t args_seg = MolReader_Script_get_args(&script_seg);
mol_seg_t raw_args_seg = MolReader_Bytes_raw_bytes(&args_seg);
memcpy(g_script_code_hash, code_hash_seg.ptr, 32);
g_script_hash_type = *hash_type_seg.ptr;
uint8_t creator_script_buffer[GW_MAX_SCRIPT_SIZE];
mol_seg_t creator_script_seg;
mol_seg_t creator_raw_args_seg;
if (raw_args_seg.size == CREATOR_SCRIPT_ARGS_LEN) {
/* polyjuice creator account */
g_creator_account_id = to_id;
creator_raw_args_seg = raw_args_seg;
} else if (raw_args_seg.size == CONTRACT_ACCOUNT_SCRIPT_ARGS_LEN) {
/* read creator account id and do some checking */
memcpy(&g_creator_account_id, raw_args_seg.ptr + 32, sizeof(uint32_t));
int ret = load_account_script(ctx,
g_creator_account_id,
creator_script_buffer,
GW_MAX_SCRIPT_SIZE,
&creator_script_seg);
if (ret != 0) {
return ret;
}
mol_seg_t creator_code_hash_seg = MolReader_Script_get_code_hash(&creator_script_seg);
mol_seg_t creator_hash_type_seg = MolReader_Script_get_hash_type(&creator_script_seg);
mol_seg_t creator_args_seg = MolReader_Script_get_args(&creator_script_seg);
creator_raw_args_seg = MolReader_Bytes_raw_bytes(&creator_args_seg);
if (memcmp(creator_code_hash_seg.ptr, code_hash_seg.ptr, 32) != 0
|| *creator_hash_type_seg.ptr != *hash_type_seg.ptr
/* compare rollup_script_hash */
|| memcmp(creator_raw_args_seg.ptr, raw_args_seg.ptr, 32) != 0
|| creator_raw_args_seg.size != CREATOR_SCRIPT_ARGS_LEN) {
debug_print_int("invalid creator account id in normal contract account script args",
g_creator_account_id);
return FATAL_POLYJUICE;
}
} else {
debug_print_data("invalid to account script args", raw_args_seg.ptr, raw_args_seg.size);
return FATAL_POLYJUICE;
}
/** read g_chain_id from Godwoken RollupConfig */
mol_seg_t rollup_config_seg;
rollup_config_seg.ptr = ctx->rollup_config;
rollup_config_seg.size = ctx->rollup_config_size;
mol_seg_t id_u64_seg = MolReader_RollupConfig_get_chain_id(&rollup_config_seg);
memcpy(&g_chain_id, id_u64_seg.ptr, id_u64_seg.size);
debug_print_int("chain_id", g_chain_id);
debug_print_int("creator_account_id", g_creator_account_id);
/** read rollup_script_hash and g_sudt_id from creator account */
memcpy(g_rollup_script_hash, creator_raw_args_seg.ptr, 32);
memcpy(&g_sudt_id, creator_raw_args_seg.ptr + 32, sizeof(uint32_t));
debug_print_data("g_rollup_script_hash", g_rollup_script_hash, 32);
debug_print_int("g_sudt_id", g_sudt_id);
return 0;
}
int create_new_account(gw_context_t* ctx,
const evmc_message* msg,
uint32_t from_id,
uint32_t* to_id,
uint8_t* code_data,
size_t code_size) {
if (code_size == 0) {
ckb_debug("[create_new_account] can't create new account by empty code data");
return FATAL_POLYJUICE;
}
int ret = 0;
uint8_t script_args[CONTRACT_ACCOUNT_SCRIPT_ARGS_LEN];
uint8_t data[128] = {0};
uint32_t data_len = 0;
if (msg->kind == EVMC_CREATE) {
/* normal contract account script.args[36..36+20] content before hash
Include:
- [20 bytes] sender address
- [4 bytes] sender nonce (NOTE: only use first 4 bytes (u32))
Above data will be RLP encoded.
*/
ckb_debug("[create_new_account] msg->kind == EVMC_CREATE");
uint32_t nonce;
/* from_id must already exists */
ret = ctx->sys_get_account_nonce(ctx, from_id, &nonce);
if (ret != 0) {
return ret;
}
debug_print_data("sender", msg->sender.bytes, 20);
debug_print_int("from_id", from_id);
debug_print_int("nonce", nonce);
rlp_encode_sender_and_nonce(&msg->sender, nonce, data, &data_len);
} else if (msg->kind == EVMC_CREATE2) {
/* CREATE2 contract account script.args[36..36+20] content before hash
Include:
- [ 1 byte ] 0xff (refer to ethereum)
- [20 bytes] sender address
- [32 bytes] create2_salt
- [32 bytes] keccak256(init_code)
*/
ckb_debug("[create_new_account] msg->kind == EVMC_CREATE2");
union ethash_hash256 hash_result = ethash::keccak256(code_data, code_size);
data[0] = 0xff;
memcpy(data + 1, msg->sender.bytes, 20);
memcpy(data + 1 + 20, msg->create2_salt.bytes, 32);
memcpy(data + 1 + 20 + 32, hash_result.bytes, 32);
data_len = 1 + 20 + 32 + 32;
} else {
ckb_debug("[create_new_account] unreachable");
return FATAL_POLYJUICE;
}
/* contract account script.args
Include:
- [32 bytes] rollup type hash
- [ 4 bytes] little endian creator_account_id, it's Polyjuice Root Account
- [20 bytes] keccak256(data)[12..]
*/
memcpy(script_args, g_rollup_script_hash, 32);
memcpy(script_args + 32, (uint8_t*)(&g_creator_account_id), 4);
union ethash_hash256 data_hash_result = ethash::keccak256(data, data_len);
uint8_t *eth_addr = data_hash_result.bytes + 12;
memcpy(script_args + 32 + 4, eth_addr, ETH_ADDRESS_LEN);
mol_seg_t new_script_seg;
uint32_t new_account_id;
ret = build_script(g_script_code_hash, g_script_hash_type, script_args,
CONTRACT_ACCOUNT_SCRIPT_ARGS_LEN, &new_script_seg);
if (ret != 0) {
return ret;
}
uint8_t script_hash[32];
blake2b_hash(script_hash, new_script_seg.ptr, new_script_seg.size);
ret = ctx->sys_create(ctx, new_script_seg.ptr, new_script_seg.size, &new_account_id);
if (ret != 0) {
debug_print_int("sys_create error", ret);
// create account failed assume account already created by meta_contract
ret = ctx->sys_get_account_id_by_script_hash(ctx, script_hash, &new_account_id);
if (ret != 0) {
return ret;
}
}
free(new_script_seg.ptr);
*to_id = new_account_id;
memcpy((uint8_t *)msg->destination.bytes, eth_addr, 20);
debug_print_int(">> new to id", *to_id);
// register a created contract account into `ETH Address Registry`
ret = gw_update_eth_address_register(ctx, eth_addr, script_hash);
if (ret != 0) {
ckb_debug("[create_new_account] failed to register a contract account");
return ret;
}
return 0;
}
int handle_transfer(gw_context_t* ctx,
const evmc_message* msg,
bool to_address_is_eoa) {
uint256_t value;
uint8_t* value_ptr = (uint8_t*)&value;
for (int i = 0; i < 32; i++) {
value_ptr[i] = msg->value.bytes[31 - i];
}
debug_print_data("[handle_transfer] sender", msg->sender.bytes, 20);
debug_print_data("[handle_transfer] destination", msg->destination.bytes, 20);
debug_print_data("[handle_transfer] msg->value", (uint8_t*)&value, 32);
if (msg->kind == EVMC_CALL
&& memcmp(msg->sender.bytes, g_tx_origin.bytes, 20) == 0
&& to_address_is_eoa) {
ckb_debug("warning: transfer value from eoa to eoa");
return FATAL_POLYJUICE;
}
gw_reg_addr_t from_addr = new_reg_addr(msg->sender.bytes);
gw_reg_addr_t to_addr = new_reg_addr(msg->destination.bytes);
uint256_t zero = {0};
if (uint256_cmp(value, zero) == EQUAL) {
return 0;
}
int ret = sudt_transfer(ctx, g_sudt_id, from_addr, to_addr, value);
if (ret != 0) {
ckb_debug("[handle_transfer] sudt_transfer failed");
return ret;
}
return 0;
}
int execute_in_evmone(gw_context_t* ctx,
evmc_message* msg,
uint32_t _parent_from_id,
uint32_t from_id,
uint32_t to_id,
const uint8_t* code_data,
const size_t code_size,
struct evmc_result* res) {
int ret = 0;
evmc_address sender = msg->sender;
evmc_address destination = msg->destination;
struct evmc_host_context context {ctx, code_data, code_size, from_id, to_id, sender, destination, 0};
struct evmc_vm* vm = evmc_create_evmone();
struct evmc_host_interface interface = {account_exists, get_storage, set_storage, get_balance,
get_code_size, get_code_hash, copy_code, selfdestruct,
call, get_tx_context, get_block_hash, emit_log};
/* Execute the code in EVM */
debug_print_int("[execute_in_evmone] code size", code_size);
debug_print_int("[execute_in_evmone] input_size", msg->input_size);
*res = vm->execute(vm, &interface, &context, EVMC_MAX_REVISION, msg, code_data, code_size);
if (res->status_code != EVMC_SUCCESS && res->status_code != EVMC_REVERT) {
res->output_data = NULL;
res->output_size = 0;
}
if (context.error_code != 0) {
debug_print_int("[execute_in_evmone] context.error_code", context.error_code);
ret = context.error_code;
goto evmc_vm_cleanup;
}
if (res->gas_left < 0) {
ckb_debug("[execute_in_evmone] gas not enough");
ret = EVMC_OUT_OF_GAS;
goto evmc_vm_cleanup;
}
evmc_vm_cleanup:
evmc_destroy(vm); // destroy the VM instance
return ret;
}
int store_contract_code(gw_context_t* ctx,
uint32_t to_id,
struct evmc_result* res) {
int ret;
uint8_t key[32];
uint8_t data_hash[32];
blake2b_hash(data_hash, (uint8_t*)res->output_data, res->output_size);
polyjuice_build_contract_code_key(to_id, key);
ckb_debug("BEGIN store data key");
debug_print_data("code_data_hash", data_hash, 32);
/* to_id must exists here */
ret = ctx->sys_store(ctx, to_id, key, GW_KEY_BYTES, data_hash);
if (ret != 0) {
return ret;
}
ckb_debug("BEGIN store data");
debug_print_int("contract_code_len", res->output_size);
ret = ctx->sys_store_data(ctx, res->output_size, (uint8_t*)res->output_data);