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.

201 lines
6.8 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
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.len() > 0 {
  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.len() > 0 {
  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) -> [u8; 32] {
  77. match self.stack.pop() {
  78. Some(x) => x,
  79. None => panic!("pop err"),
  80. }
  81. }
  82. pub fn execute(&mut self, code: &[u8], calldata: &[u8], debug: bool) -> Vec<u8> {
  83. self.pc = 0;
  84. self.calldata_i = 0;
  85. let l = code.len();
  86. while self.pc < l {
  87. let opcode = code[self.pc];
  88. if !self.opcodes.contains_key(&opcode) {
  89. panic!("invalid opcode {:x}", opcode);
  90. }
  91. if debug {
  92. println!(
  93. "{} (0x{:x}): pc={:?} gas={:?}",
  94. self.opcodes.get(&opcode).unwrap().name,
  95. opcode,
  96. self.pc,
  97. self.gas,
  98. );
  99. self.print_stack();
  100. self.print_memory();
  101. self.print_storage();
  102. println!();
  103. }
  104. match opcode & 0xf0 {
  105. 0x00 => {
  106. // arithmetic
  107. match opcode {
  108. 0x00 => {
  109. println!("0x00: STOP");
  110. return Vec::new();
  111. }
  112. 0x01 => self.add(),
  113. 0x02 => self.mul(),
  114. 0x03 => self.sub(),
  115. 0x04 => self.div(),
  116. 0x05 => self.sdiv(),
  117. 0x06 => self.modulus(),
  118. 0x07 => self.smod(),
  119. 0x08 => self.add_mod(),
  120. 0x09 => self.mul_mod(),
  121. 0x0a => self.exp(),
  122. // 0x0b => self.sign_extend(),
  123. _ => panic!("unimplemented {:x}", opcode),
  124. }
  125. self.pc += 1;
  126. }
  127. 0x30 => {
  128. match opcode {
  129. 0x35 => self.calldata_load(&calldata),
  130. 0x36 => self.calldata_size(&calldata),
  131. 0x39 => self.code_copy(&code),
  132. _ => panic!("unimplemented {:x}", opcode),
  133. }
  134. self.pc += 1;
  135. }
  136. 0x50 => {
  137. self.pc += 1;
  138. match opcode {
  139. 0x51 => self.mload(),
  140. 0x52 => self.mstore(),
  141. 0x55 => self.sstore(),
  142. 0x56 => self.jump(),
  143. 0x57 => self.jump_i(),
  144. 0x5b => self.jump_dest(),
  145. _ => panic!("unimplemented {:x}", opcode),
  146. }
  147. }
  148. 0x60 | 0x70 => {
  149. // push
  150. let n = (opcode - 0x5f) as usize;
  151. self.push_arbitrary(&code[self.pc + 1..self.pc + 1 + n]);
  152. self.pc += 1 + n;
  153. }
  154. 0x80 => {
  155. // 0x8x dup
  156. let l = self.stack.len();
  157. if opcode > 0x7f {
  158. self.stack.push(self.stack[l - (opcode - 0x7f) as usize]);
  159. } else {
  160. self.stack.push(self.stack[(0x7f - opcode) as usize]);
  161. }
  162. self.pc += 1;
  163. }
  164. 0x90 => {
  165. // 0x9x swap
  166. let l = self.stack.len();
  167. let pos;
  168. if opcode > 0x8e {
  169. pos = l - (opcode - 0x8e) as usize;
  170. } else {
  171. pos = (0x8e - opcode) as usize;
  172. }
  173. self.stack.swap(pos, l - 1);
  174. self.pc += 1;
  175. }
  176. 0xf0 => {
  177. if opcode == 0xf3 {
  178. let pos_to_return = u256::u256_to_u64(self.pop()) as usize;
  179. let len_to_return = u256::u256_to_u64(self.pop()) as usize;
  180. return self.mem[pos_to_return..pos_to_return + len_to_return].to_vec();
  181. }
  182. }
  183. _ => {
  184. return panic!("unimplemented {:x}", opcode);
  185. }
  186. }
  187. self.gas -= self.opcodes.get(&opcode).unwrap().gas;
  188. }
  189. Vec::new()
  190. }
  191. }
  192. pub fn vec_u8_to_hex(bytes: Vec<u8>) -> String {
  193. let strs: Vec<String> = bytes.iter().map(|b| format!("{:02X}", b)).collect();
  194. strs.join("")
  195. }