-
Notifications
You must be signed in to change notification settings - Fork 477
Expand file tree
/
Copy pathpallet_revive.rs
More file actions
1667 lines (1473 loc) · 56.1 KB
/
pallet_revive.rs
File metadata and controls
1667 lines (1473 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Use Ink (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "xcm")]
use ink_primitives::Weight;
use ink_primitives::{
Address,
CodeHashErr,
H256,
U256,
abi::{
AbiEncodeWith,
Ink,
Sol,
},
sol::SolResultEncode,
};
use ink_storage_traits::{
Storable,
decode_all,
};
use pallet_revive_uapi::{
CallFlags,
HostFn,
HostFnImpl as ext,
ReturnErrorCode,
ReturnFlags,
StorageFlags,
};
#[cfg(feature = "xcm")]
use xcm::VersionedXcm;
use crate::{
DecodeDispatch,
DispatchError,
EnvBackend,
Environment,
Result,
TypedEnvBackend,
call::{
Call,
CallParams,
ConstructorReturnType,
CreateParams,
DelegateCall,
FromAddr,
LimitParamsV2,
utils::{
DecodeMessageResult,
EncodeArgsWith,
},
},
engine::on_chain::{
EncodeScope,
EnvInstance,
ScopedBuffer,
},
event::{
Event,
TopicEncoder,
TopicsBuilderBackend,
},
hash::{
Blake2x128,
Blake2x256,
CryptoHash,
HashOutput,
Keccak256,
Sha2x256,
},
types::FromLittleEndian,
};
/// The code hash of an existing account without code.
/// This is the `keccak256` hash of empty data.
/// ```no_compile
/// const EMPTY_CODE_HASH: H256 =
/// H256(sp_core::hex2array!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
/// ````
const EMPTY_CODE_HASH: H256 = H256([
197, 210, 70, 1, 134, 247, 35, 60, 146, 126, 125, 178, 220, 199, 3, 192, 229, 0, 182,
83, 202, 130, 39, 59, 123, 250, 216, 4, 93, 133, 164, 112,
]);
const H256_ZERO: H256 = H256::zero();
impl CryptoHash for Blake2x128 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 16];
static_assertions::assert_type_eq_all!(
<Blake2x128 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = array_mut_ref!(output, 0, 16);
let mut buffer = [0u8; 32];
let mut output_buffer = [0u8; 32];
let sel = const { solidity_selector("hashBlake128(bytes)") };
buffer[..4].copy_from_slice(&sel[..4]);
// we pass `offset = 32`, as the `bytes` payload starts there (right after the
// offset word), we pass `offset_pos = 0`, as the callee takes only one argument.
let n = solidity_encode_bytes(input, 32, 0, &mut buffer[4..]);
const ADDR: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000900");
let call_result = ext::delegate_call(
CallFlags::empty(),
&ADDR,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&buffer[..4 + n],
Some(&mut &mut output_buffer[..]),
);
call_result.expect("call host function failed");
output[..].copy_from_slice(&output_buffer[16..]);
}
fn hash_with_buffer(
_input: &[u8],
_buffer: &mut [u8],
_output: &mut <Self as HashOutput>::Type,
) {
panic!(
"Hashing Blake2x128 can be done without a buffer, by calling a host function"
);
}
}
/// Returns the Solidity selector for `fn_sig`.
///
/// Note that this is a const function, it is evaluated at compile time.
///
/// # Usage
///
/// ```
/// let sel = solidity_selector("ownCodeHash()");
/// assert_eq!(sel, [219, 107, 220, 138]);
/// ```
pub const fn solidity_selector(fn_sig: &str) -> [u8; 4] {
let output: [u8; 32] = const_crypto::sha3::Keccak256::new()
.update(fn_sig.as_bytes())
.finalize();
[output[0], output[1], output[2], output[3]]
}
/// Encodes a `u32` to big-endian `[u8; 32]` with padded zeros.
fn encode_u32(value: u32, out: &mut [u8]) {
debug_assert_eq!(out.len(), 32);
out[28..].copy_from_slice(&value.to_be_bytes()); // last 4 bytes
}
/// Encodes a `bool` to big-endian `[u8; 32]` with padded zeros.
fn encode_bool(value: bool, out: &mut [u8]) {
debug_assert_eq!(out.len(), 32);
if value {
out[31] = 1;
}
}
const STORAGE_PRECOMPILE_ADDR: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000901");
#[cfg(feature = "xcm")]
const XCM_PRECOMPILE_ADDR: [u8; 20] =
hex_literal::hex!("00000000000000000000000000000000000A0000");
/// Four bytes are required to encode a Solidity selector;
const SOL_ENCODED_SELECTOR_LEN: usize = 4;
/// Number of bytes required to encode the `uint32 flags` parameter
/// that the `Storage` pre-compile functions take.
const SOL_ENCODED_FLAGS_LEN: usize = 32;
/// Number of bytes required to encode the `bool isFixedKey` parameter
/// that the `Storage` pre-compile functions take.
const SOL_ENCODED_IS_FIXED_KEY_LEN: usize = 32;
/// Number of bytes required to store the offset word when encoding
/// to the Solidity type `bytes`.
const SOL_BYTES_OFFSET_WORD_LEN: usize = 32;
/// When encoding a Rust `[u8]` to Solidity `bytes`, a small amount
/// of overhead space is required (for the 32 bytes offset + 32 bytes
/// length word).
const SOL_BYTES_ENCODING_OVERHEAD: usize = 64;
/// Encodes the `bytes` argument for the Solidity ABI.
/// The result is written to `out`.
///
/// Returns the number of bytes written.
///
/// # Arguments
///
/// - `input`: the bytes to encode.
/// - `offset`: the position in `out` where the data segment of `input` starts. The data
/// segment is composed of [length word (32 bytes)] [input (padded to 32)]`.
/// - `offset_pos`: the position in `out` where to write the `offset` word to.
/// - `out`: the output buffer.
///
/// # Developer Note
///
/// The returned layout will be
///
/// `... [offset (32 bytes)] ... [len (32 bytes)] [data (padded to 32)] ...`
///
/// The `out` byte array needs to be able to hold
/// (in the worst case) 95 bytes more than `input.len()`.
///
/// This is because we write the following to `out`:
/// * The offset word → always 32 bytes.
/// * The length word → always 32 bytes.
/// * The input itself → exactly `input.len()` bytes.
/// * We pad the input to a multiple of 32 → between 0 and 31 extra bytes.
fn solidity_encode_bytes(
input: &[u8],
offset: u32,
offset_pos: usize,
out: &mut [u8],
) -> usize {
let input_len = input.len();
let padded_len = solidity_padded_len(input_len);
// out_len = 32 + padded_len
// = 32 + ceil(input_len / 32) * 32
assert!(out.len() >= padded_len + SOL_BYTES_ENCODING_OVERHEAD);
// Encode offset as a 32-byte big-endian word
out[offset_pos + 28..offset_pos + 32].copy_from_slice(&offset.to_be_bytes()[..4]);
out[offset_pos..offset_pos + 28].copy_from_slice(&[0u8; 28]); // make sure the first bytes are zeroed
// Encode length as a 32-byte big-endian word
let mut len_word = [0u8; 32];
// We are at most on a 64-bit architecture, hence we can safely assume `len < 2^64`.
let len_bytes = (input_len as u64).to_be_bytes();
len_word[24..32].copy_from_slice(&len_bytes);
// we take `offset: u32` as a parameter of `solidity_encode_bytes`,
// as we need to extract the big endian bytes above.
let offset = offset as usize;
// The offset is a 32 byte word
out[offset..offset + 32].copy_from_slice(&len_word);
// Number of bytes required to encode the length of the `bytes` array
// (i.e. the "length word").
const BYTES_LEN_WORD: usize = 32;
// Write the `input` at `offset_pos`, after the 32 byte `len` word
out[offset + BYTES_LEN_WORD..offset + BYTES_LEN_WORD + input_len]
.copy_from_slice(input);
64 + padded_len
}
/// Returns the Solidity word padded length for the given input length (i.e. next multiple
/// of 32 for the given number).
///
/// # Developer Note
// The implementation does not use `.div_ceil()`, as that function is more complex
// and would use up more stack space.
#[allow(clippy::manual_div_ceil)]
#[inline(always)]
const fn solidity_padded_len(len: usize) -> usize {
((len + 31) / 32) * 32
}
impl CryptoHash for Blake2x256 {
fn hash(_input: &[u8], _output: &mut <Self as HashOutput>::Type) {
panic!("Hashing Blake2x256 requires calling a pre-compile and a buffer");
}
fn hash_with_buffer(
input: &[u8],
buffer: &mut [u8],
output: &mut <Self as HashOutput>::Type,
) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Blake2x256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = array_mut_ref!(output, 0, 32);
let sel = const { solidity_selector("hashBlake256(bytes)") };
buffer[..4].copy_from_slice(&sel[..4]);
// we pass `offset = 32`, as the `bytes` payload starts there (right after the
// offset word)
let n = solidity_encode_bytes(input, 32, 0, &mut buffer[4..]);
const ADDR: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000900");
let call_result = ext::delegate_call(
CallFlags::empty(),
&ADDR,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&buffer[..4 + n],
Some(&mut &mut output[..]),
);
call_result.expect("call host function failed");
}
}
impl CryptoHash for Sha2x256 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Sha2x256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = array_mut_ref!(output, 0, 32);
const ADDR: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000002");
// todo return value?
let _ = ext::call(
CallFlags::empty(),
&ADDR,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
input,
Some(&mut &mut output[..]),
);
}
fn hash_with_buffer(
_input: &[u8],
_buffer: &mut [u8],
_output: &mut <Self as HashOutput>::Type,
) {
panic!(
"Hashing Sha2x256 can be done without a buffer, by calling a host function"
);
}
}
impl CryptoHash for Keccak256 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Keccak256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = array_mut_ref!(output, 0, 32);
ext::hash_keccak_256(input, output);
}
fn hash_with_buffer(
_input: &[u8],
_buffer: &mut [u8],
_output: &mut <Self as HashOutput>::Type,
) {
panic!(
"Hashing Keccak256 can be done without a buffer, by calling a host function"
);
}
}
pub struct TopicsBuilder<'a> {
scoped_buffer: ScopedBuffer<'a>,
}
impl<'a> From<ScopedBuffer<'a>> for TopicsBuilder<'a> {
fn from(scoped_buffer: ScopedBuffer<'a>) -> Self {
Self { scoped_buffer }
}
}
impl<'a, Abi> TopicsBuilderBackend<Abi> for TopicsBuilder<'a>
where
Abi: TopicEncoder,
{
type Output = (ScopedBuffer<'a>, &'a mut [u8]);
fn push_topic<T>(&mut self, topic_value: &T)
where
T: AbiEncodeWith<Abi>,
{
let output = if <Abi as TopicEncoder>::REQUIRES_BUFFER {
let mut output = [0u8; 32];
let split = self.scoped_buffer.split();
let buffer = split.take_rest();
<Abi as TopicEncoder>::encode_topic_with_hash_buffer(
topic_value,
&mut output,
buffer,
);
output
} else {
<Abi as TopicEncoder>::encode_topic(topic_value)
};
self.scoped_buffer.append_bytes(output.as_slice());
}
fn output(mut self) -> Self::Output {
let encoded_topics = self.scoped_buffer.take_appended();
(self.scoped_buffer, encoded_topics)
}
}
impl TopicEncoder for Ink {
const REQUIRES_BUFFER: bool = true;
fn encode_topic<T>(_value: &T) -> [u8; 32]
where
T: AbiEncodeWith<Self>,
{
panic!("Blake2x256 hashing requires calling a pre-compile and a buffer");
}
fn encode_topic_with_hash_buffer<T>(
value: &T,
output: &mut [u8; 32],
buffer: &mut [u8],
) where
T: AbiEncodeWith<Self>,
{
let mut scoped_buffer = ScopedBuffer::from(buffer);
let encoded = scoped_buffer.take_encoded_with(|buff| value.encode_to_slice(buff));
let len_encoded = encoded.len();
let solidity_encoding_buffer = scoped_buffer.take(
SOL_ENCODED_SELECTOR_LEN
+ SOL_BYTES_ENCODING_OVERHEAD
+ solidity_padded_len(len_encoded),
);
if len_encoded <= 32 {
output[..len_encoded].copy_from_slice(encoded);
} else {
<Blake2x256 as CryptoHash>::hash_with_buffer(
encoded,
&mut solidity_encoding_buffer[..],
output,
);
}
}
}
impl TopicEncoder for Sol {
const REQUIRES_BUFFER: bool = false;
fn encode_topic<T>(value: &T) -> [u8; 32]
where
T: AbiEncodeWith<Self>,
{
value.encode_topic(<Keccak256 as CryptoHash>::hash)
}
fn encode_topic_with_hash_buffer<T>(
_value: &T,
_output: &mut [u8; 32],
_buffer: &mut [u8],
) where
T: AbiEncodeWith<Self>,
{
panic!(
"Keccak-256 hashing can be done without a buffer, by calling a host function"
);
}
}
impl EnvInstance {
#[inline(always)]
/// Returns a new scoped buffer for the entire scope of the static 16 kB buffer.
fn scoped_buffer(&mut self) -> ScopedBuffer<'_> {
ScopedBuffer::from(&mut self.buffer[..])
}
/// Returns the contract property value from its little-endian representation.
///
/// # Note
///
/// This skips the potentially costly decoding step that is often equivalent to a
/// `memcpy`.
#[inline(always)]
fn get_property_little_endian<T>(&mut self, ext_fn: fn(output: &mut [u8; 32])) -> T
where
T: FromLittleEndian,
{
let mut scope = self.scoped_buffer();
let u256: &mut [u8; 32] = scope
.take(32)
.try_into()
.expect("failed to take 32 bytes from buffer");
ext_fn(u256);
let mut result = <T as FromLittleEndian>::Bytes::default();
let len = result.as_ref().len();
result.as_mut()[..].copy_from_slice(&u256[..len]);
<T as FromLittleEndian>::from_le_bytes(result)
}
}
fn call_bool_precompile(selector: [u8; 4], output: &mut [u8]) -> bool {
debug_assert_eq!(output.len(), 32);
const ADDR: [u8; 20] = hex_literal::hex!("0000000000000000000000000000000000000900");
ext::call(
CallFlags::empty(),
&ADDR,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
&selector[..],
Some(&mut &mut output[..]),
)
.expect("call host function failed");
if output[31] == 1 {
debug_assert_eq!(&output[..31], [0u8; 31]);
return true;
}
debug_assert_eq!(&output[..32], [0u8; 32]);
false
}
/// Calls a function on the `pallet-revive` `Storage` pre-compile "contract".
///
/// # Developer Note
///
/// This function assumes that the called pre-compiles all have this function
/// signature for the arguments:
///
/// ```no_compile
/// function containsStorage(uint32 flags, bool isFixedKey, bytes memory key)
/// ```
///
/// The function makes heavy use of operating on byte slices and the positions
/// in the slice are calculated based on the size of these three arguments.
///
/// The return type does not matter.
fn call_storage_precompile(
input_buf: &mut &mut [u8],
selector: [u8; 4],
key: &[u8],
output: &mut [u8],
) -> core::result::Result<(), ReturnErrorCode> {
input_buf.fill(0);
debug_assert_eq!(
SOL_ENCODED_SELECTOR_LEN
+ SOL_ENCODED_FLAGS_LEN
+ SOL_ENCODED_IS_FIXED_KEY_LEN
+ SOL_BYTES_ENCODING_OVERHEAD
+ solidity_padded_len(key.len()),
input_buf.len(),
"input buffer has an unexpected size",
);
input_buf[..4].copy_from_slice(&selector[..]);
encode_u32(STORAGE_FLAGS.bits(), &mut input_buf[4..36]); // todo @cmichi optimize
encode_bool(false, &mut input_buf[36..68]); // todo @cmichi optimize
let encoded_bytes_len = solidity_encode_bytes(
key,
// The offset is 96 here because all `Storage` pre-compile functions
// take the input arguments `(uint32 flags, bool isFixedKey, bytes memory key)`.
//
// The offset is where the data payload of the third argument, `bytes`, starts:
// 32 bytes for `flags` + 32 bytes for `isFixedKey` + 32 bytes for the `offset`
// word that comes first when encoding `bytes`.
// 96 then points to the `len|data` segment of `bytes`
(SOL_ENCODED_FLAGS_LEN + SOL_ENCODED_IS_FIXED_KEY_LEN + SOL_BYTES_OFFSET_WORD_LEN)
as u32,
// encode the `bytes` starting at the appropriate position in the slice
64,
&mut input_buf[SOL_ENCODED_SELECTOR_LEN..],
);
// todo @cmichi check if we might better return `None` in this situation. perhaps a
// zero sized key is legal?
debug_assert!(
encoded_bytes_len >= SOL_BYTES_ENCODING_OVERHEAD + 32,
"the `bytes` encoding length was < 96, meaning we didn't encode a 32 byte `key`. \
calling this function without `key` does not make sense and is unexpected."
);
// `output` needs to hold at least 32 bytes, for the len field of `bytes`.
// if no `bytes` are returned from the delegate call we will at the minimum
// have the `len` field.
assert!(output.len() >= 32);
ext::delegate_call(
CallFlags::empty(),
&STORAGE_PRECOMPILE_ADDR,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&input_buf[..SOL_ENCODED_SELECTOR_LEN
+ SOL_ENCODED_FLAGS_LEN
+ SOL_ENCODED_IS_FIXED_KEY_LEN
+ encoded_bytes_len],
Some(&mut &mut output[..]),
)
}
/// Simple decoder for a Solidity `bytes` type.
///
/// # Important
///
/// This function assumes that it is decoding a single
/// bytes return type!
///
/// - Fine: `function foo() returns (bytes memory);`
/// - Not Fine: `function foo() returns (bool, bytes memory);`
///
/// # Return Value
///
/// Returns the number of bytes written to `out`.
fn decode_bytes(input: &[u8], out: &mut [u8]) -> usize {
let mut buf = [0u8; 4];
buf[..].copy_from_slice(&input[28..32]);
debug_assert_eq!(
{
// offset
u32::from_be_bytes(buf) as usize
},
64
);
let mut buf = [0u8; 4];
buf[..].copy_from_slice(&input[60..64]);
let bytes_len = u32::from_be_bytes(buf) as usize;
// we start decoding at the start of the payload.
// the payload starts at the `len` word here:
// `bytes = offset (32 bytes) | len (32 bytes) | data`
out[..bytes_len].copy_from_slice(&input[64..64 + bytes_len]);
bytes_len
}
const STORAGE_FLAGS: StorageFlags = StorageFlags::empty();
const TRANSIENT_STORAGE_FLAGS: StorageFlags = StorageFlags::TRANSIENT;
impl EnvBackend for EnvInstance {
fn set_contract_storage<K, V>(&mut self, key: &K, value: &V) -> Option<u32>
where
K: scale::Encode,
V: Storable,
{
let mut buffer = self.scoped_buffer();
let key = buffer.take_encoded(key);
let value = buffer.take_storable_encoded(value);
ext::set_storage(STORAGE_FLAGS, key, value)
}
fn get_contract_storage<K, R>(&mut self, key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable,
{
let mut buffer = self.scoped_buffer();
let key = buffer.take_encoded(key);
let output = &mut buffer.take_rest();
match ext::get_storage(STORAGE_FLAGS, key, output) {
Ok(_) => (),
Err(ReturnErrorCode::KeyNotFound) => return Ok(None),
Err(_) => panic!("encountered unexpected error"),
}
let decoded = decode_all(&mut &output[..])?;
Ok(Some(decoded))
}
fn remaining_buffer(&mut self) -> usize {
self.scoped_buffer().remaining_buffer()
}
/// Calls the following function on the `pallet-revive` `Storage` pre-compile:
///
/// ```no_compile
/// function takeStorage(uint32 flags, bool isFixedKey, bytes memory key)
/// external returns (bytes memory)
/// ```
fn take_contract_storage<K, R>(&mut self, key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable,
{
let mut buffer = self.scoped_buffer();
let key = buffer.take_encoded(key);
let padded_len = solidity_padded_len(key.len());
let buf: &mut [u8] = buffer.take(
SOL_ENCODED_SELECTOR_LEN
+ SOL_ENCODED_FLAGS_LEN
+ SOL_ENCODED_IS_FIXED_KEY_LEN
+ SOL_BYTES_ENCODING_OVERHEAD
+ padded_len,
);
let output = &mut buffer.take_rest();
let sel = const { solidity_selector("takeStorage(uint32,bool,bytes)") };
call_storage_precompile(&mut &mut buf[..], sel, key, output)
.expect("failed calling Storage pre-compile (take)");
debug_assert!(
!output.is_empty(),
"output must always contain at least the len and offset of `bytes`"
);
// extract the `len` from the returned Solidity `bytes`
let mut buf = [0u8; 4];
buf[..].copy_from_slice(&output[60..64]);
let bytes_len = u32::from_be_bytes(buf) as usize;
if bytes_len == 0 {
return Ok(None);
}
if output.len() < SOL_BYTES_ENCODING_OVERHEAD + bytes_len {
return Err(crate::Error::BufferTooSmall);
}
// We start decoding at the start of the payload.
// The payload starts at the `len` word here:
// `bytes = offset (32 bytes) | len (32 bytes) | data`
let decoded = decode_all(
&mut &output
[SOL_BYTES_ENCODING_OVERHEAD..bytes_len + SOL_BYTES_ENCODING_OVERHEAD],
)?;
Ok(Some(decoded))
}
/// Calls the following function on the `pallet-revive` `Storage` pre-compile:
///
/// ```no_compile
/// function containsStorage(uint32 flags, bool isFixedKey, bytes memory key)
/// external returns (bool containedKey, uint valueLen)
/// ```
fn contains_contract_storage<K>(&mut self, key: &K) -> Option<u32>
where
K: scale::Encode,
{
let mut buffer = self.scoped_buffer();
let key = buffer.take_encoded(key);
let padded_len = solidity_padded_len(key.len());
let buf: &mut [u8] = buffer.take(
SOL_ENCODED_SELECTOR_LEN
+ SOL_ENCODED_FLAGS_LEN
+ SOL_ENCODED_IS_FIXED_KEY_LEN
+ SOL_BYTES_ENCODING_OVERHEAD
+ padded_len,
);
let output = buffer.take(64);
let sel = const { solidity_selector("containsStorage(uint32,bool,bytes)") };
call_storage_precompile(&mut &mut buf[..], sel, key, &mut output[..])
.expect("failed calling Storage pre-compile (contains)");
// Check the returned `containedKey` boolean value
if output[31] == 0 {
debug_assert!(
output.iter().all(|x| *x == 0),
"both `containedKey` and `valueLen` need to be zero"
);
return None;
}
let mut value_len_buf = [0u8; 4];
value_len_buf[..4].copy_from_slice(&output[60..64]);
Some(u32::from_be_bytes(value_len_buf))
}
/// Calls the following function on the `pallet-revive` `Storage` pre-compile:
///
/// ```no_compile
/// function clearStorage(uint32 flags, bool isFixedKey, bytes memory key)
/// external returns (bool containedKey, uint valueLen);
/// ```
fn clear_contract_storage<K>(&mut self, key: &K) -> Option<u32>
where
K: scale::Encode,
{
let mut buffer = self.scoped_buffer();
let key = buffer.take_encoded(key);
let padded_len = solidity_padded_len(key.len());
let buf: &mut [u8] = buffer.take(
SOL_ENCODED_SELECTOR_LEN
+ SOL_ENCODED_FLAGS_LEN
+ SOL_ENCODED_IS_FIXED_KEY_LEN
+ SOL_BYTES_ENCODING_OVERHEAD
+ padded_len,
);
let output = buffer.take(64);
let sel = const { solidity_selector("clearStorage(uint32,bool,bytes)") };
call_storage_precompile(&mut &mut buf[..], sel, key, &mut output[..])
.expect("failed calling Storage pre-compile (clear)");
// Check the returned `containedKey` boolean value
if output[31] == 0 {
debug_assert!(
output.iter().all(|x| *x == 0),
"both `containedKey` and `valueLen` need to be zero"
);
return None;
}
let mut value_len_buf = [0u8; 4];
value_len_buf[..4].copy_from_slice(&output[60..64]);
Some(u32::from_be_bytes(value_len_buf))
}
fn decode_input<T>(&mut self) -> core::result::Result<T, DispatchError>
where
T: DecodeDispatch,
{
let full_scope = &mut self.scoped_buffer().take_rest();
ext::call_data_copy(full_scope, 0);
DecodeDispatch::decode_dispatch(&mut &full_scope[..])
}
fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
where
R: scale::Encode,
{
let mut scope = EncodeScope::from(&mut self.buffer[..]);
return_value.encode_to(&mut scope);
let len = scope.len();
if len == 0 {
ext::return_value(flags, &[]);
} else {
ext::return_value(flags, &self.buffer[..][..len]);
}
}
fn return_value_solidity<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
where
R: for<'a> SolResultEncode<'a>,
{
let encoded = return_value.encode();
ext::return_value(flags, &encoded[..]);
}
fn hash_bytes<H>(&mut self, input: &[u8], output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
{
<H as CryptoHash>::hash(input, output)
}
fn hash_encoded<H, T>(&mut self, input: &T, output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
T: scale::Encode,
{
let mut scope = self.scoped_buffer();
let enc_input = scope.take_encoded(input);
<H as CryptoHash>::hash(enc_input, output)
}
fn bn128_add(&mut self, x1: U256, y1: U256, x2: U256, y2: U256) -> (U256, U256) {
const BN128_ADD: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000006");
let mut input = [0u8; 128];
input[..32].copy_from_slice(&x1.to_big_endian());
input[32..64].copy_from_slice(&y1.to_big_endian());
input[64..96].copy_from_slice(&x2.to_big_endian());
input[96..128].copy_from_slice(&y2.to_big_endian());
let mut output = [0u8; 64];
let _ = ext::call(
CallFlags::empty(),
&BN128_ADD,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
&input[..],
Some(&mut &mut output[..]),
);
let x3 = U256::from_big_endian(&output[..32]);
let y3 = U256::from_big_endian(&output[32..64]);
(x3, y3)
}
fn bn128_mul(&mut self, x1: U256, y1: U256, scalar: U256) -> (U256, U256) {
const BN128_ADD: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000007");
let mut input = [0u8; 128];
input[..32].copy_from_slice(&x1.to_big_endian());
input[32..64].copy_from_slice(&y1.to_big_endian());
input[64..96].copy_from_slice(&scalar.to_big_endian());
let mut output = [0u8; 64];
let _ = ext::call(
CallFlags::empty(),
&BN128_ADD,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
&input[..],
Some(&mut &mut output[..]),
);
let x2 = U256::from_big_endian(&output[..32]);
let y2 = U256::from_big_endian(&output[32..64]);
(x2, y2)
}
fn bn128_pairing(&mut self, input: &[u8]) -> bool {
const BN128_ADD: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000008");
let mut output = [0u8; 32];
let _ = ext::call(
CallFlags::empty(),
&BN128_ADD,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
&input[..],
Some(&mut &mut output[..]),
);
if output[31] == 1 {
debug_assert_eq!(&output[..31], [0u8; 31]);
return true;
}
debug_assert_eq!(&output[..32], [0u8; 32]);
false
}
fn ecdsa_recover(
&mut self,
signature: &[u8; 65],
message_hash: &[u8; 32],
output: &mut [u8; 33],
) -> Result<()> {
// todo change fn args to just take the slice callee_input slice directly
let mut callee_input = [0u8; 65 + 32];
callee_input[..65].copy_from_slice(&signature[..65]);
callee_input[65..65 + 32].copy_from_slice(&message_hash[..32]);
const ECRECOVER: [u8; 20] =
hex_literal::hex!("0000000000000000000000000000000000000001");
// todo return value?
let _ = ext::call(
CallFlags::empty(),
&ECRECOVER,
u64::MAX, // `ref_time` to devote for execution. `u64::MAX` = all
u64::MAX, // `proof_size` to devote for execution. `u64::MAX` = all
&[u8::MAX; 32], // No deposit limit.
&U256::zero().to_little_endian(), // Value transferred to the contract.
&callee_input[..],
Some(&mut &mut output[..]),
);
Ok(())
}
#[cfg(feature = "unstable-hostfn")]
fn ecdsa_to_eth_address(
&mut self,
pubkey: &[u8; 33],
output: &mut [u8; 20],
) -> Result<()> {
ext::ecdsa_to_eth_address(pubkey, output).map_err(Into::into)
}
#[cfg(feature = "unstable-hostfn")]
fn sr25519_verify(
&mut self,
signature: &[u8; 64],
message: &[u8],
pub_key: &[u8; 32],
) -> Result<()> {
ext::sr25519_verify(signature, message, pub_key).map_err(Into::into)
}
#[cfg(feature = "unstable-hostfn")]
fn set_code_hash(&mut self, code_hash: &H256) -> Result<()> {
ext::set_code_hash(code_hash.as_fixed_bytes());
Ok(()) // todo
}
}
// TODO remove anything with hash
impl TypedEnvBackend for EnvInstance {