You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
8.2 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #![allow(dead_code)]
  2. use std::collections::HashMap;
  3. pub mod opcodes;
  4. pub mod u256;
  5. #[derive(Default)]
  6. pub struct Stack {
  7. pub pc: usize,
  8. pub calldata_i: usize,
  9. pub calldata_size: usize,
  10. pub stack: Vec<[u8; 32]>,
  11. pub storage_committed: HashMap<[u8; 32], Vec<u8>>,
  12. pub storage: HashMap<[u8; 32], Vec<u8>>,
  13. pub mem: Vec<u8>,
  14. pub gas: u64,
  15. pub opcodes: HashMap<u8, opcodes::Opcode>,
  16. }
  17. impl Stack {
  18. pub fn new() -> Stack {
  19. let mut s = Stack {
  20. pc: 0,
  21. calldata_i: 0,
  22. calldata_size: 32,
  23. stack: Vec::new(),
  24. storage_committed: HashMap::new(),
  25. storage: HashMap::new(),
  26. mem: Vec::new(),
  27. gas: 10000000000,
  28. opcodes: HashMap::new(),
  29. };
  30. s.opcodes = opcodes::new_opcodes();
  31. s
  32. }
  33. pub fn print_stack(&self) {
  34. println!("stack ({}):", self.stack.len());
  35. for i in (0..self.stack.len()).rev() {
  36. // println!("{:x}", &self.stack[i][28..]);
  37. println!("{:?}", vec_u8_to_hex(self.stack[i].to_vec()));
  38. }
  39. }
  40. pub fn print_memory(&self) {
  41. if !self.mem.is_empty() {
  42. println!("memory ({}):", self.mem.len());
  43. println!("{:?}", vec_u8_to_hex(self.mem.to_vec()));
  44. }
  45. }
  46. pub fn print_storage(&self) {
  47. if !self.storage.is_empty() {
  48. println!("storage ({}):", self.storage.len());
  49. for (key, value) in self.storage.iter() {
  50. println!(
  51. "{:?}: {:?}",
  52. vec_u8_to_hex(key.to_vec()),
  53. vec_u8_to_hex(value.to_vec())
  54. );
  55. }
  56. }
  57. }
  58. pub fn push(&mut self, b: [u8; 32]) {
  59. self.stack.push(b);
  60. }
  61. // push_arbitrary performs a push, but first converting the arbitrary-length
  62. // input into a 32 byte array
  63. pub fn push_arbitrary(&mut self, b: &[u8]) {
  64. // TODO if b.len()>32 return error
  65. let mut d: [u8; 32] = [0; 32];
  66. d[32 - b.len()..].copy_from_slice(b);
  67. self.stack.push(d);
  68. }
  69. // put_arbitrary puts in the last element of the stack the value
  70. pub fn put_arbitrary(&mut self, b: &[u8]) {
  71. // TODO if b.len()>32 return error
  72. let mut d: [u8; 32] = [0; 32];
  73. d[0..b.len()].copy_from_slice(b); // put without left padding
  74. let l = self.stack.len();
  75. self.stack[l - 1] = d;
  76. }
  77. pub fn pop(&mut self) -> Result<[u8; 32], String> {
  78. match self.stack.pop() {
  79. Some(x) => Ok(x),
  80. None => Err("pop err".to_string()), // WIP
  81. }
  82. }
  83. pub fn peek(&mut self) -> Result<[u8; 32], String> {
  84. if self.stack.is_empty() {
  85. return Err("peek err".to_string());
  86. }
  87. Ok(self.stack[self.stack.len() - 1])
  88. }
  89. pub fn substract_gas(&mut self, val: u64) -> Result<(), String> {
  90. if self.gas < val {
  91. return Err("out of gas".to_string());
  92. }
  93. self.gas -= val;
  94. Ok(())
  95. }
  96. pub fn execute(
  97. &mut self,
  98. code: &[u8],
  99. calldata: &[u8],
  100. debug: bool,
  101. ) -> Result<Vec<u8>, String> {
  102. self.pc = 0;
  103. self.calldata_i = 0;
  104. let l = code.len();
  105. while self.pc < l {
  106. let opcode = code[self.pc];
  107. if !self.opcodes.contains_key(&opcode) {
  108. return Err(format!("invalid opcode {:x}", opcode));
  109. }
  110. if debug {
  111. println!(
  112. "{} (0x{:x}): pc={:?} gas={:?}",
  113. self.opcodes.get(&opcode).unwrap().name,
  114. opcode,
  115. self.pc,
  116. self.gas,
  117. );
  118. self.print_stack();
  119. self.print_memory();
  120. self.print_storage();
  121. println!();
  122. }
  123. match opcode & 0xf0 {
  124. 0x00 => {
  125. // arithmetic
  126. match opcode {
  127. 0x00 => {
  128. println!("0x00: STOP");
  129. return Ok(Vec::new());
  130. }
  131. 0x01 => self.add()?,
  132. 0x02 => self.mul()?,
  133. 0x03 => self.sub()?,
  134. 0x04 => self.div()?,
  135. 0x05 => self.sdiv()?,
  136. 0x06 => self.modulus()?,
  137. 0x07 => self.smod()?,
  138. 0x08 => self.add_mod()?,
  139. 0x09 => self.mul_mod()?,
  140. 0x0a => self.exp()?,
  141. // 0x0b => self.sign_extend(),
  142. _ => return Err(format!("unimplemented {:x}", opcode)),
  143. }
  144. self.pc += 1;
  145. }
  146. 0x10 => {
  147. // arithmetic
  148. match opcode {
  149. 0x10 => self.lt()?,
  150. 0x11 => self.gt()?,
  151. // 0x12 => self.slt()?,
  152. // 0x13 => self.sgt()?,
  153. 0x14 => self.eq()?,
  154. 0x15 => self.is_zero()?,
  155. 0x16 => self.and()?,
  156. 0x17 => self.or()?,
  157. 0x18 => self.xor()?,
  158. 0x19 => self.not()?,
  159. // 0x1a => self.byte()?,
  160. _ => return Err(format!("unimplemented {:x}", opcode)),
  161. }
  162. self.pc += 1;
  163. }
  164. 0x30 => {
  165. match opcode {
  166. 0x35 => self.calldata_load(&calldata)?,
  167. 0x36 => self.calldata_size(&calldata),
  168. 0x39 => self.code_copy(&code)?,
  169. _ => return Err(format!("unimplemented {:x}", opcode)),
  170. }
  171. self.pc += 1;
  172. }
  173. 0x50 => {
  174. self.pc += 1;
  175. match opcode {
  176. 0x51 => self.mload()?,
  177. 0x52 => self.mstore()?,
  178. 0x55 => self.sstore()?,
  179. 0x56 => self.jump(code)?,
  180. 0x57 => self.jump_i(code)?,
  181. 0x5b => self.jump_dest()?,
  182. _ => return Err(format!("unimplemented {:x}", opcode)),
  183. }
  184. }
  185. 0x60 | 0x70 => {
  186. // push
  187. let n = (opcode - 0x5f) as usize;
  188. self.push_arbitrary(&code[self.pc + 1..self.pc + 1 + n]);
  189. self.pc += 1 + n;
  190. }
  191. 0x80 => {
  192. // 0x8x dup
  193. let l = self.stack.len();
  194. if opcode > 0x7f {
  195. self.stack.push(self.stack[l - (opcode - 0x7f) as usize]);
  196. } else {
  197. self.stack.push(self.stack[(0x7f - opcode) as usize]);
  198. }
  199. self.pc += 1;
  200. }
  201. 0x90 => {
  202. // 0x9x swap
  203. let l = self.stack.len();
  204. let pos;
  205. if opcode > 0x8e {
  206. pos = l - (opcode - 0x8e) as usize;
  207. } else {
  208. pos = (0x8e - opcode) as usize;
  209. }
  210. self.stack.swap(pos, l - 1);
  211. self.pc += 1;
  212. }
  213. 0xf0 => {
  214. if opcode == 0xf3 {
  215. let pos_to_return = u256::u256_to_u64(self.pop()?) as usize;
  216. let len_to_return = u256::u256_to_u64(self.pop()?) as usize;
  217. return Ok(self.mem[pos_to_return..pos_to_return + len_to_return].to_vec());
  218. }
  219. }
  220. _ => {
  221. return Err(format!("unimplemented {:x}", opcode));
  222. }
  223. }
  224. self.substract_gas(self.opcodes.get(&opcode).unwrap().gas)?;
  225. }
  226. Ok(Vec::new())
  227. }
  228. }
  229. pub fn vec_u8_to_hex(bytes: Vec<u8>) -> String {
  230. let strs: Vec<String> = bytes.iter().map(|b| format!("{:02X}", b)).collect();
  231. strs.join("")
  232. }