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
use darling::{
    util::{Flag, SpannedValue},
    FromAttributes, FromDeriveInput, FromField, FromVariant,
};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{DeriveInput, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, Pat, Path};
use tiny_keccak::{Hasher as _, Keccak};

const SELECTOR_LENGTH: usize = 4;

#[derive(FromAttributes)]
#[darling(attributes(evm_method))]
struct EvmMethod {
    signature: SpannedValue<String>,
    convert: Flag,
}

#[derive(Debug, Clone)]
struct Signature {
    selector: [u8; SELECTOR_LENGTH],
    name: Ident,
    convert: bool,
    args: Vec<String>,
}

fn evm_crate_path() -> Path {
    let is_internal = std::env::var("CARGO_PKG_NAME")
        .map(|pkg_name| pkg_name == "oasis-runtime-sdk-evm")
        .unwrap_or_default();
    if is_internal {
        // Doctests are their own crates, but they share the name of the primary crate.
        // Thus, the primary crate needs to refer to itself. Either that or depend on unstable
        // rustdoc env vars.
        syn::parse_quote!(crate::oasis_runtime_sdk_evm)
    } else {
        syn::parse_quote!(::oasis_runtime_sdk_evm)
    }
}

fn parse_signature(name: Ident, signature: &str) -> Signature {
    let mut hash = [0u8; 32];
    let mut keccak = Keccak::v256();
    keccak.update(signature.as_bytes());
    keccak.finalize(&mut hash);
    let mut selector = [0u8; SELECTOR_LENGTH];
    selector.copy_from_slice(&hash[..SELECTOR_LENGTH]);

    let mut args = Vec::new();
    if let Some((_, after_paren)) = signature.split_once('(') {
        if let Some((arg_list, _)) = after_paren.split_once(')') {
            args = arg_list
                .split(',')
                .map(str::to_string)
                .filter(|s| !s.is_empty())
                .collect();
        }
    }

    Signature {
        selector,
        name,
        convert: false,
        args,
    }
}

fn get_method(f: &ImplItemFn) -> Option<(Signature, EvmMethod, TokenStream)> {
    let attr = match EvmMethod::from_attributes(&f.attrs) {
        Ok(a) => a,
        Err(e) => {
            e.span().unwrap().error(format!("{}", e)).emit();
            return None;
        }
    };

    let mut signature = parse_signature(f.sig.ident.clone(), attr.signature.as_str());
    signature.convert = attr.convert.is_present();
    for inp in f.sig.inputs.iter() {
        match inp {
            FnArg::Receiver(recv) => {
                recv.self_token
                    .span
                    .unwrap()
                    .error("Dispatchable methods can't have a receiver")
                    .emit();
                return None;
            }
            FnArg::Typed(typed) => match *typed.pat {
                Pat::Ident(_) => continue,
                _ => {
                    typed
                        .colon_token
                        .span
                        .unwrap()
                        .error("Unsupported function input type")
                        .emit();
                    return None;
                }
            },
        }
    }
    if signature.convert && signature.args.len() != f.sig.inputs.len() - 1 {
        signature
            .name
            .span()
            .unwrap()
            .error("Number of function arguments doesn't match EVM signature")
            .emit();
        return None;
    }

    let byte_tokens = signature.selector.iter().map(|&b| quote!(#b));
    let byte_list = quote!(#(#byte_tokens ,)*);
    Some((signature, attr, byte_list))
}

fn generate_method_call(attr: &EvmMethod, sig: &Signature) -> Option<TokenStream> {
    let mut decoder_list: Vec<TokenStream> = Vec::new();
    let mut call_args: Vec<Ident> = Vec::new();
    let mut arg_decls: Vec<TokenStream> = Vec::new();
    for (i, evm_ty) in sig.args.iter().enumerate() {
        let arg_name = format_ident!("arg_{}", i);
        call_args.push(arg_name.clone());
        match evm_ty.as_str() {
            "address" => {
                decoder_list.push(quote!(::ethabi::ParamType::Address));
                arg_decls.push(quote! {
                    let #arg_name = decoded_args[#i].clone().into_address().unwrap();
                });
            }
            "uint256" => {
                decoder_list.push(quote!(::ethabi::ParamType::Uint(256)));
                let temp_name = format_ident!("{}_uint", arg_name);
                arg_decls.push(quote! {
                    let #temp_name = decoded_args[#i].clone().into_uint().unwrap();
                    if #temp_name.bits() > (u128::BITS as usize) {
                        return Some(Err(::evm::executor::stack::PrecompileFailure::Error {
                            exit_status: ::evm::ExitError::Other("integer overflow".into()),
                        }));
                    }
                    let #arg_name = #temp_name.as_u128();
                });
            }
            ty => {
                attr.signature
                    .span()
                    .unwrap()
                    .error(format!("Unknown argument type '{}'", ty))
                    .emit();
            }
        }
    }
    let method_name = sig.name.clone();
    Some(quote! { {
        let decoded_args = match ::ethabi::decode(&[#(#decoder_list),*], &handle.input()[#SELECTOR_LENGTH..]) {
            Err(e) => return Some(Err(::evm::executor::stack::PrecompileFailure::Error {
                exit_status: ::evm::ExitError::Other("invalid argument".into()),
            })),
            Ok(tokens) => tokens,
        };
        #(#arg_decls)*
        Some(Self::#method_name(handle, #(#call_args),*))
    } })
}

pub fn derive_evm_contract(input: ItemImpl) -> TokenStream {
    let mut methods: Vec<(Signature, EvmMethod, TokenStream)> = Vec::new();
    let mut address_fn: Option<_> = None;

    for item in input.items.iter() {
        if let ImplItem::Fn(f) = item {
            if f.attrs
                .iter()
                .any(|attr| attr.path().is_ident("evm_method"))
            {
                methods.extend(get_method(f).into_iter());
            }
            if f.attrs
                .iter()
                .any(|attr| attr.path().is_ident("evm_contract_address"))
            {
                address_fn = Some(f.sig.ident.clone());
            }
        }
    }
    if address_fn.is_none() {
        input.impl_token
        .span.unwrap()
            .error("Missing implementation for address function (use the `evm_contract_address` attribute)")
            .emit();
        return TokenStream::new();
    }

    let method_arms: Vec<TokenStream> = methods
        .into_iter()
        .map(|(sig, method, keccak)| {
            if sig.convert {
                let decode_body = generate_method_call(&method, &sig);
                quote! {
                    &[#keccak] => { #decode_body }
                }
            } else {
                let method_name = sig.name.clone();
                quote! {
                    &[#keccak] => Some(Self::#method_name(handle, #SELECTOR_LENGTH)),
                }
            }
        })
        .collect();

    let impl_generics = &input.generics;
    let self_ty = input.self_ty.clone();
    let evm_crate = evm_crate_path();
    quote! {
        #input

        #[automatically_derived]
        impl #impl_generics #evm_crate::precompile::contract::StaticContract for #self_ty {
            fn address() -> ::primitive_types::H160 {
                Self::#address_fn()
            }

            fn dispatch_call(
                handle: &mut impl ::evm::executor::stack::PrecompileHandle,
            ) -> Option<Result<::evm::executor::stack::PrecompileOutput, ::evm::executor::stack::PrecompileFailure>> {
                if handle.context().address != handle.code_address() {
                    return Some(Err(::evm::executor::stack::PrecompileFailure::Error {
                        exit_status: ::evm::ExitError::Other("invalid call".into()),
                    }));
                }
                let selector = match handle.input().get(..#SELECTOR_LENGTH) {
                    Some(slice) => slice,
                    None => return Some(Err(::evm::executor::stack::PrecompileFailure::Revert {
                        exit_status: ::evm::ExitRevert::Reverted,
                        output: vec![],
                    })),
                };
                match selector {
                    #(#method_arms)*
                    _ => Some(Err(::evm::executor::stack::PrecompileFailure::Revert {
                        exit_status: ::evm::ExitRevert::Reverted,
                        output: vec![],
                    })),
                }
            }
        }

        #[automatically_derived]
        impl #impl_generics ::evm::executor::stack::PrecompileSet for #self_ty {
            fn execute(&self, handle: &mut impl ::evm::executor::stack::PrecompileHandle) -> Option<Result<::evm::executor::stack::PrecompileOutput, ::evm::executor::stack::PrecompileFailure>> {
                match self.is_precompile(handle.code_address(), handle.remaining_gas()) {
                    ::evm::executor::stack::IsPrecompileResult::Answer {
                        is_precompile: true,
                        extra_cost,
                    } => {
                        if let Err(e) = handle.record_cost(extra_cost) {
                            return Some(Err(e.into()));
                        }
                    }
                    ::evm::executor::stack::IsPrecompileResult::OutOfGas => {
                        return Some(Err(::evm::ExitError::OutOfGas.into()));
                    }
                    _ => {
                        return None;
                    }
                }

                <Self as #evm_crate::precompile::contract::StaticContract>::dispatch_call(handle)
            }

            fn is_precompile(
                &self,
                address: ::primitive_types::H160,
                _remaining_gas: u64,
            ) -> ::evm::executor::stack::IsPrecompileResult {
                ::evm::executor::stack::IsPrecompileResult::Answer {
                    is_precompile: Self::address() == address,
                    extra_cost: 0,
                }
            }
        }
    }
}

#[derive(FromDeriveInput)]
#[darling(supports(struct_named), attributes(evm_event))]
struct EvmEvent {
    ident: Ident,
    data: darling::ast::Data<(), EvmEventArg>,
    name: String,
}

#[derive(FromField)]
#[darling(attributes(evm_event))]
struct EvmEventArg {
    ident: Option<Ident>,
    indexed: darling::util::Flag,
    arg_type: String,
}

pub fn derive_evm_event(input: DeriveInput) -> TokenStream {
    let event = match EvmEvent::from_derive_input(&input) {
        Ok(event) => event,
        Err(e) => return e.write_errors(),
    };

    let fields = event.data.as_ref().take_struct().unwrap().fields;

    let signature = {
        let mut bytes = [0u8; 32];
        let mut keccak = Keccak::v256();
        keccak.update(event.name.as_bytes());
        keccak.update(b"(");
        for (i, field) in fields.iter().enumerate() {
            if i > 0 {
                keccak.update(b",");
            }
            keccak.update(field.arg_type.as_bytes());
        }
        keccak.update(b")");
        keccak.finalize(&mut bytes);
        bytes
    };
    let signature_tokens = signature.into_iter().map(|b| quote!(#b));

    let evm_crate = evm_crate_path();

    let topics: Vec<TokenStream> = fields.iter().filter_map(|f| {
        if f.indexed.is_present() {
            let name = f.ident.as_ref().unwrap();
            Some(quote! { ::primitive_types::H256::from_slice(::ethabi::encode(&[self.#name.clone()]).as_slice()) })
        } else {
            None
        }
    }).collect();

    let data: Vec<TokenStream> = fields
        .iter()
        .filter_map(|f| {
            if !f.indexed.is_present() {
                let name = f.ident.as_ref().unwrap();
                Some(quote! { self.#name.clone() })
            } else {
                None
            }
        })
        .collect();
    let data_tokens = if data.is_empty() {
        quote! { vec![] }
    } else {
        quote! {
            ::ethabi::encode(&[
                #(#data ,)*
            ])
        }
    };

    let event_ty = &event.ident;

    quote! {
        #[automatically_derived]
        impl #evm_crate::precompile::contract::EvmEvent for #event_ty {
            fn emit<C: #evm_crate::precompile::contract::StaticContract>(&self, handle: &mut impl ::evm::executor::stack::PrecompileHandle) -> Result<(), ::evm::ExitError> {
                let address = C::address();
                let topics = vec![
                    ::primitive_types::H256::from_slice(&[#(#signature_tokens ,)*]),
                    #(#topics ,)*
                ];
                let data = #data_tokens;
                handle.log(address, topics, data)
            }
        }
    }
}

#[derive(FromDeriveInput)]
#[darling(supports(enum_unit, enum_tuple), attributes(evm_error))]
struct EvmError {
    ident: Ident,
    data: darling::ast::Data<EvmErrorArg, ()>,
}

#[derive(FromVariant)]
#[darling(attributes(evm_error))]
struct EvmErrorArg {
    ident: Ident,
    signature: SpannedValue<String>,
}

pub fn derive_evm_error(input: DeriveInput) -> TokenStream {
    let error = match EvmError::from_derive_input(&input) {
        Ok(error) => error,
        Err(e) => return e.write_errors(),
    };

    let mut variant_encoders: Vec<TokenStream> = Vec::new();
    for variant in error.data.as_ref().take_enum().unwrap().iter() {
        let ident = &variant.ident;
        let signature = parse_signature(variant.ident.clone(), &variant.signature);
        let hash_bytes = signature.selector.map(|b| quote!(#b));
        let mut abi_tokens: Vec<TokenStream> = Vec::new();
        let mut match_fields: Vec<Ident> = Vec::new();
        for (i, evm_ty) in signature.args.iter().enumerate() {
            let field_ident = format_ident!("field_{}", i);
            match_fields.push(field_ident.clone());
            match evm_ty.as_str() {
                "address" => {
                    // The tuple field for this should be a primitive_types::H160.
                    abi_tokens.push(quote! {
                        ::ethabi::Token::Address(*#field_ident)
                    });
                }
                "uint256" => {
                    // The tuple field for this should be a u128.
                    abi_tokens.push(quote! {
                        ::ethabi::Token::Uint((*#field_ident).into())
                    });
                }
                "string" => {
                    // The tuple field for this should be anything that has a to_string() method.
                    abi_tokens.push(quote! {
                        ::ethabi::Token::String(#field_ident.to_string())
                    });
                }
                ty => {
                    variant
                        .signature
                        .span()
                        .unwrap()
                        .error(format!("Unknown type '{}'", ty))
                        .emit();
                    return TokenStream::new();
                }
            }
        }
        let (match_expr, encode_expr) = if match_fields.is_empty() {
            (quote! { Self::#ident }, TokenStream::new())
        } else {
            (
                quote! { Self::#ident(#(#match_fields,)*) },
                quote! { output.extend(::ethabi::encode(&[#(#abi_tokens,)*]).as_slice()); },
            )
        };
        variant_encoders.push(quote! {
            #match_expr => {
                let mut output = Vec::new();
                output.extend(&[#(#hash_bytes,)*]);
                #encode_expr
                ::evm::executor::stack::PrecompileFailure::Revert {
                    exit_status: ::evm::ExitRevert::Reverted,
                    output,
                }
            }
        });
    }

    let evm_crate = evm_crate_path();
    let error_ty = &error.ident;

    quote! {
        #[automatically_derived]
        impl #evm_crate::precompile::contract::EvmError for #error_ty {
            fn encode(&self) -> ::evm::executor::stack::PrecompileFailure {
                match self {
                    #(#variant_encoders)*
                }
            }
        }
    }
}