-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
154 lines (136 loc) · 4.69 KB
/
lib.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
// Modified based on https://github.com/kvinwang/phatjs-playground/blob/master/lib.rs
#![cfg_attr(not(feature = "std"), no_std, no_main)]
extern crate alloc;
pub use jtee_engine::*;
#[ink::contract]
mod jtee_engine {
use alloc::{format, string::String, vec, vec::Vec};
use phat_js as js;
use pink_extension::chain_extension::{signing, SigType};
use scale::{Decode, Encode};
#[derive(Debug, Encode, Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum JsEngine {
SidevmQuickJS,
SidevmQuickJSWithPolyfill,
JsDelegate,
JsDelegate2,
CustomDriver(String),
CustomCodeHash(Hash),
}
impl JsEngine {
fn into_delegate_code_hash(self) -> Result<Hash, String> {
match self {
JsEngine::SidevmQuickJS => get_driver("JsRuntime"),
JsEngine::SidevmQuickJSWithPolyfill => get_driver("JsRuntime"),
JsEngine::JsDelegate => get_driver("JsDelegate"),
JsEngine::JsDelegate2 => get_driver("JsDelegate2"),
JsEngine::CustomDriver(name) => get_driver(&name),
JsEngine::CustomCodeHash(code) => Ok(code),
}
}
fn is_sidevm(&self) -> bool {
matches!(
self,
JsEngine::SidevmQuickJS | JsEngine::SidevmQuickJSWithPolyfill
)
}
fn with_polyfill(&self) -> bool {
matches!(self, JsEngine::SidevmQuickJSWithPolyfill)
}
}
#[ink(storage)]
pub struct JteeEngine {
pub owner: AccountId,
pub key: [u8; 32],
pub account: [u8; 20],
}
impl JteeEngine {
#[ink(constructor)]
pub fn default() -> Self {
let key = pink_web3::keys::pink::KeyPair::derive_keypair(b"engine").private_key();
let ecdsa_pubkey: [u8; 33] = signing::get_public_key(&key, SigType::Ecdsa)
.try_into()
.expect("Public key should be of length 33");
let mut ecdsa_address = [0u8; 20];
ink_env::ecdsa_to_eth_address(&ecdsa_pubkey, &mut ecdsa_address)
.expect("Get address of ecdsa failed");
Self {
owner: Self::env().caller(),
key,
account: ecdsa_address,
}
}
#[ink(message)]
/// Executes the provided JavaScript code and returns the execution result.
///
/// # Arguments
///
/// * `engine` - The js engine to use.
/// * `js_code` - The Javascript code to run
/// * `args` - The arguments to pass to the Javascript code
///
/// @ui js_code widget codemirror
/// @ui js_code options.lang javascript
pub fn run_js(
&self,
engine: JsEngine,
js_code: String,
args: Vec<String>,
) -> Result<js::JsValue, String> {
self.ensure_owner()?;
if engine.is_sidevm() {
if engine.with_polyfill() {
Ok(js::eval_async_js(&js_code, &args))
} else {
Ok(pink::ext().js_eval(
vec![js::JsCode::Source(self.seal()), js::JsCode::Source(js_code)],
args,
))
}
} else {
js::eval_with(engine.into_delegate_code_hash()?, &js_code, &args).map(Into::into)
}
}
#[ink(message)]
/// Ping for log output
pub fn ping(&self) -> Result<(), String> {
Ok(())
}
pub fn seal(&self) -> String {
String::from(format!(
r#"const jtee = {{
"owner": "{}",
"key": "0x{}",
"account": "0x{}",
}};"#,
hex::encode(self.owner),
hex::encode(self.key),
hex::encode(&self.account),
))
}
fn ensure_owner(&self) -> Result<(), String> {
if self.env().caller() == self.owner {
Ok(())
} else {
Err(String::from("BadOrigin"))
}
}
}
pub fn get_driver(name: &str) -> Result<Hash, String> {
use phat_js::ConvertTo;
let system = pink::system::SystemRef::instance();
let delegate = system.get_driver(name.into()).ok_or("No JS driver found")?;
Ok(delegate.convert_to())
}
}
#[cfg(test)]
mod tests {
use super::JteeEngine;
#[test]
fn test_key_derivation() {
pink_extension_runtime::mock_ext::mock_all_ext();
let jtee = JteeEngine::default();
println!("seal: {:?}", jtee.seal())
}
}