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.

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