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.

468 lines
16 KiB

  1. #![allow(dead_code)]
  2. use num_bigint::BigUint;
  3. use std::collections::HashMap;
  4. // Non-opcode gas prices
  5. const GDEFAULT: usize = 1;
  6. const GMEMORY: usize = 3;
  7. const GQUADRATICMEMDENOM: usize = 512; // 1 gas per 512 quadwords
  8. const GSTORAGEREFUND: usize = 15000;
  9. const GSTORAGEKILL: usize = 5000;
  10. const GSTORAGEMOD: usize = 5000;
  11. const GSTORAGEADD: usize = 20000;
  12. const GEXPONENTBYTE: usize = 10; // cost of EXP exponent per byte
  13. const GCOPY: usize = 3; // cost to copy one 32 byte word
  14. const GCONTRACTBYTE: usize = 200; // one byte of code in contract creation
  15. const GCALLVALUETRANSFER: usize = 9000; // non-zero-valued call
  16. const GLOGBYTE: usize = 8; // cost of a byte of logdata
  17. const GTXCOST: usize = 21000; // TX BASE GAS COST
  18. const GTXDATAZERO: usize = 4; // TX DATA ZERO BYTE GAS COST
  19. const GTXDATANONZERO: usize = 68; // TX DATA NON ZERO BYTE GAS COST
  20. const GSHA3WORD: usize = 6; // Cost of SHA3 per word
  21. const GSHA256BASE: usize = 60; // Base c of SHA256
  22. const GSHA256WORD: usize = 12; // Cost of SHA256 per word
  23. const GRIPEMD160BASE: usize = 600; // Base cost of RIPEMD160
  24. const GRIPEMD160WORD: usize = 120; // Cost of RIPEMD160 per word
  25. const GIDENTITYBASE: usize = 15; // Base cost of indentity
  26. const GIDENTITYWORD: usize = 3; // Cost of identity per word
  27. const GECRECOVER: usize = 3000; // Cost of ecrecover op
  28. const GSTIPEND: usize = 2300;
  29. const GCALLNEWACCOUNT: usize = 25000;
  30. const GSUICIDEREFUND: usize = 24000;
  31. pub struct Stack {
  32. pc: usize,
  33. calldata_i: usize,
  34. stack: Vec<[u8; 32]>,
  35. mem: Vec<u8>,
  36. gas: u64,
  37. opcodes: HashMap<u8, Opcode>,
  38. }
  39. impl Stack {
  40. pub fn new() -> Stack {
  41. let mut s = Stack {
  42. pc: 0,
  43. calldata_i: 0,
  44. stack: Vec::new(),
  45. mem: Vec::new(),
  46. gas: 10000000000,
  47. opcodes: HashMap::new(),
  48. };
  49. s.opcodes = new_opcodes();
  50. s
  51. }
  52. fn print_stack(&self) {
  53. for i in (0..self.stack.len()).rev() {
  54. println!("{:x?}", &self.stack[i][28..]);
  55. }
  56. }
  57. 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 input into a 32
  61. // byte array
  62. 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. 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[32 - b.len()..].copy_from_slice(&b[..]);
  73. let l = self.stack.len();
  74. self.stack[l - 1] = d;
  75. }
  76. fn pop(&mut self) -> [u8; 32] {
  77. match self.stack.pop() {
  78. Some(x) => return x,
  79. None => panic!("err"),
  80. }
  81. }
  82. 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={:?}\nstack:",
  94. self.opcodes.get(&opcode).unwrap().name,
  95. opcode,
  96. self.pc,
  97. self.gas,
  98. );
  99. self.print_stack();
  100. println!("");
  101. }
  102. match opcode & 0xf0 {
  103. 0x00 => {
  104. // arithmetic
  105. match opcode {
  106. 0x00 => {
  107. return Vec::new();
  108. }
  109. 0x01 => self.add(),
  110. 0x02 => self.mul(),
  111. 0x03 => self.sub(),
  112. 0x04 => self.div(),
  113. 0x05 => self.sdiv(),
  114. 0x06 => self.modulus(),
  115. 0x07 => self.smod(),
  116. 0x08 => self.add_mod(),
  117. 0x09 => self.mul_mod(),
  118. 0x0a => self.exp(),
  119. // 0x0b => self.sign_extend(),
  120. _ => panic!("unimplemented {:x}", opcode),
  121. }
  122. self.pc += 1;
  123. }
  124. 0x30 => {
  125. match opcode {
  126. 0x35 => {
  127. self.calldata_load(&calldata);
  128. }
  129. _ => panic!("unimplemented {:x}", opcode),
  130. }
  131. self.pc += 1;
  132. }
  133. 0x50 => {
  134. self.pc += 1;
  135. match opcode {
  136. 0x52 => self.mstore(),
  137. _ => panic!("unimplemented {:x}", opcode),
  138. }
  139. }
  140. 0x60 | 0x70 => {
  141. // push
  142. let n = (opcode - 0x5f) as usize;
  143. self.push_arbitrary(&code[self.pc + 1..self.pc + 1 + n]);
  144. self.pc += 1 + n;
  145. }
  146. 0xf0 => {
  147. if opcode == 0xf3 {
  148. let pos_to_return = u256_to_u64(self.pop()) as usize;
  149. let len_to_return = u256_to_u64(self.pop()) as usize;
  150. return self.mem[pos_to_return..pos_to_return + len_to_return].to_vec();
  151. }
  152. }
  153. _ => {
  154. panic!("unimplemented {:x}", opcode);
  155. }
  156. }
  157. self.gas -= self.opcodes.get(&opcode).unwrap().gas;
  158. }
  159. return Vec::new();
  160. }
  161. // arithmetic
  162. // TODO instead of [u8;32] converted to BigUint, use custom type uint256 that implements all
  163. // the arithmetic
  164. fn add(&mut self) {
  165. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  166. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  167. self.push_arbitrary(&(b0 + b1).to_bytes_be());
  168. }
  169. fn mul(&mut self) {
  170. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  171. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  172. self.push_arbitrary(&(b0 * b1).to_bytes_be());
  173. }
  174. fn sub(&mut self) {
  175. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  176. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  177. if b0 >= b1 {
  178. self.push_arbitrary(&(b0 - b1).to_bytes_be());
  179. } else {
  180. // 2**256
  181. let max =
  182. "115792089237316195423570985008687907853269984665640564039457584007913129639936"
  183. .parse::<BigUint>()
  184. .unwrap();
  185. self.push_arbitrary(&(max + b0 - b1).to_bytes_be());
  186. }
  187. }
  188. fn div(&mut self) {
  189. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  190. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  191. self.push_arbitrary(&(b0 / b1).to_bytes_be());
  192. }
  193. fn sdiv(&mut self) {
  194. panic!("unimplemented");
  195. }
  196. fn modulus(&mut self) {
  197. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  198. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  199. self.push_arbitrary(&(b0 % b1).to_bytes_be());
  200. }
  201. fn smod(&mut self) {
  202. panic!("unimplemented");
  203. }
  204. fn add_mod(&mut self) {
  205. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  206. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  207. let b2 = BigUint::from_bytes_be(&self.pop()[..]);
  208. self.push_arbitrary(&(b0 + b1 % b2).to_bytes_be());
  209. }
  210. fn mul_mod(&mut self) {
  211. let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  212. let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  213. let b2 = BigUint::from_bytes_be(&self.pop()[..]);
  214. self.push_arbitrary(&(b0 * b1 % b2).to_bytes_be());
  215. }
  216. fn exp(&mut self) {
  217. panic!("unimplemented");
  218. // let b0 = BigUint::from_bytes_be(&self.pop()[..]);
  219. // let b1 = BigUint::from_bytes_be(&self.pop()[..]);
  220. // self.push_arbitrary(&(pow(b0, b1)).to_bytes_be());
  221. }
  222. // boolean
  223. // crypto
  224. // contract context
  225. fn calldata_load(&mut self, calldata: &[u8]) {
  226. self.put_arbitrary(&calldata[self.calldata_i..self.calldata_i + 32]);
  227. self.calldata_i += 32;
  228. }
  229. // blockchain context
  230. // storage and execution
  231. fn extend_mem(&mut self, start: usize, size: usize) {
  232. if size <= self.mem.len() || start + size <= self.mem.len() {
  233. return;
  234. }
  235. let old_size = self.mem.len() / 32;
  236. let new_size = (start + size) / 32;
  237. let old_total_fee = old_size * GMEMORY + old_size.pow(2) / GQUADRATICMEMDENOM;
  238. let new_total_fee = new_size * GMEMORY + new_size.pow(2) / GQUADRATICMEMDENOM;
  239. let mem_fee = new_total_fee - old_total_fee;
  240. self.gas -= mem_fee as u64;
  241. let mut new_bytes: Vec<u8> = vec![0; size];
  242. self.mem.append(&mut new_bytes);
  243. }
  244. fn mstore(&mut self) {
  245. let pos = u256_to_u64(self.pop());
  246. let val = self.pop();
  247. self.extend_mem(pos as usize, 32);
  248. self.mem[pos as usize..].copy_from_slice(&val);
  249. }
  250. }
  251. fn u256_to_u64(a: [u8; 32]) -> u64 {
  252. let mut b8: [u8; 8] = [0; 8];
  253. b8.copy_from_slice(&a[32 - 8..32]);
  254. let pos = u64::from_be_bytes(b8);
  255. pos
  256. }
  257. fn str_to_u256(s: &str) -> [u8; 32] {
  258. let bi = s.parse::<BigUint>().unwrap().to_bytes_be();
  259. let mut r: [u8; 32] = [0; 32];
  260. r[32 - bi.len()..].copy_from_slice(&bi[..]);
  261. r
  262. }
  263. struct Opcode {
  264. name: String,
  265. ins: u32,
  266. outs: u32,
  267. gas: u64,
  268. }
  269. fn new_opcode(name: &str, ins: u32, outs: u32, gas: u64) -> Opcode {
  270. Opcode {
  271. name: name.to_string(),
  272. ins,
  273. outs,
  274. gas,
  275. }
  276. }
  277. fn new_opcodes() -> HashMap<u8, Opcode> {
  278. let mut opcodes: HashMap<u8, Opcode> = HashMap::new();
  279. // arithmetic
  280. opcodes.insert(0x00, new_opcode("STOP", 0, 0, 0));
  281. opcodes.insert(0x01, new_opcode("ADD", 2, 1, 3));
  282. opcodes.insert(0x02, new_opcode("MUL", 2, 1, 5));
  283. opcodes.insert(0x03, new_opcode("SUB", 2, 1, 3));
  284. opcodes.insert(0x04, new_opcode("DIV", 2, 1, 5));
  285. opcodes.insert(0x05, new_opcode("SDIV", 2, 1, 5));
  286. opcodes.insert(0x06, new_opcode("MOD", 2, 1, 5));
  287. opcodes.insert(0x07, new_opcode("SMOD", 2, 1, 5));
  288. opcodes.insert(0x08, new_opcode("ADDMOD", 3, 1, 8));
  289. opcodes.insert(0x09, new_opcode("MULMOD", 3, 1, 8));
  290. opcodes.insert(0x0a, new_opcode("EXP", 2, 1, 10));
  291. opcodes.insert(0x0b, new_opcode("SIGNEXTEND", 2, 1, 5));
  292. // boolean
  293. opcodes.insert(0x10, new_opcode("LT", 2, 1, 3));
  294. opcodes.insert(0x11, new_opcode("GT", 2, 1, 3));
  295. opcodes.insert(0x12, new_opcode("SLT", 2, 1, 3));
  296. opcodes.insert(0x13, new_opcode("SGT", 2, 1, 3));
  297. opcodes.insert(0x14, new_opcode("EQ", 2, 1, 3));
  298. opcodes.insert(0x15, new_opcode("ISZERO", 1, 1, 3));
  299. opcodes.insert(0x16, new_opcode("AND", 2, 1, 3));
  300. opcodes.insert(0x17, new_opcode("OR", 2, 1, 3));
  301. opcodes.insert(0x18, new_opcode("XOR", 2, 1, 3));
  302. opcodes.insert(0x19, new_opcode("NOT", 1, 1, 3));
  303. opcodes.insert(0x1a, new_opcode("BYTE", 2, 1, 3));
  304. // crypto
  305. opcodes.insert(0x20, new_opcode("SHA3", 2, 1, 30));
  306. // contract context
  307. opcodes.insert(0x30, new_opcode("ADDRESS", 0, 1, 2));
  308. opcodes.insert(0x31, new_opcode("BALANCE", 1, 1, 20));
  309. opcodes.insert(0x32, new_opcode("ORIGIN", 0, 1, 2));
  310. opcodes.insert(0x33, new_opcode("CALLER", 0, 1, 2));
  311. opcodes.insert(0x34, new_opcode("CALLVALUE", 0, 1, 2));
  312. opcodes.insert(0x35, new_opcode("CALLDATALOAD", 1, 1, 3));
  313. opcodes.insert(0x36, new_opcode("CALLDATASIZE", 0, 1, 2));
  314. opcodes.insert(0x37, new_opcode("CALLDATACOPY", 3, 0, 3));
  315. opcodes.insert(0x38, new_opcode("CODESIZE", 0, 1, 2));
  316. opcodes.insert(0x39, new_opcode("CODECOPY", 3, 0, 3));
  317. opcodes.insert(0x3a, new_opcode("GASPRICE", 0, 1, 2));
  318. opcodes.insert(0x3b, new_opcode("EXTCODESIZE", 1, 1, 20));
  319. opcodes.insert(0x3c, new_opcode("EXTCODECOPY", 4, 0, 20));
  320. // blockchain context
  321. opcodes.insert(0x40, new_opcode("BLOCKHASH", 1, 1, 20));
  322. opcodes.insert(0x41, new_opcode("COINBASE", 0, 1, 2));
  323. opcodes.insert(0x42, new_opcode("TIMESTAMP", 0, 1, 2));
  324. opcodes.insert(0x43, new_opcode("NUMBER", 0, 1, 2));
  325. opcodes.insert(0x44, new_opcode("DIFFICULTY", 0, 1, 2));
  326. opcodes.insert(0x45, new_opcode("GASLIMIT", 0, 1, 2));
  327. // storage and execution
  328. opcodes.insert(0x50, new_opcode("POP", 1, 0, 2));
  329. opcodes.insert(0x51, new_opcode("MLOAD", 1, 1, 3));
  330. opcodes.insert(0x52, new_opcode("MSTORE", 2, 0, 3));
  331. opcodes.insert(0x53, new_opcode("MSTORE8", 2, 0, 3));
  332. opcodes.insert(0x54, new_opcode("SLOAD", 1, 1, 50));
  333. opcodes.insert(0x55, new_opcode("SSTORE", 2, 0, 0));
  334. opcodes.insert(0x56, new_opcode("JUMP", 1, 0, 8));
  335. opcodes.insert(0x57, new_opcode("JUMPI", 2, 0, 10));
  336. opcodes.insert(0x58, new_opcode("PC", 0, 1, 2));
  337. opcodes.insert(0x59, new_opcode("MSIZE", 0, 1, 2));
  338. opcodes.insert(0x5a, new_opcode("GAS", 0, 1, 2));
  339. opcodes.insert(0x5b, new_opcode("JUMPDEST", 0, 0, 1));
  340. // logging
  341. opcodes.insert(0xa0, new_opcode("LOG0", 2, 0, 375));
  342. opcodes.insert(0xa1, new_opcode("LOG1", 3, 0, 750));
  343. opcodes.insert(0xa2, new_opcode("LOG2", 4, 0, 1125));
  344. opcodes.insert(0xa3, new_opcode("LOG3", 5, 0, 1500));
  345. opcodes.insert(0xa4, new_opcode("LOG4", 6, 0, 1875));
  346. // closures
  347. opcodes.insert(0xf0, new_opcode("CREATE", 3, 1, 32000));
  348. opcodes.insert(0xf1, new_opcode("CALL", 7, 1, 40));
  349. opcodes.insert(0xf2, new_opcode("CALLCODE", 7, 1, 40));
  350. opcodes.insert(0xf3, new_opcode("RETURN", 2, 0, 0));
  351. opcodes.insert(0xf4, new_opcode("DELEGATECALL", 6, 0, 40));
  352. opcodes.insert(0xff, new_opcode("SUICIDE", 1, 0, 0));
  353. for i in 1..33 {
  354. let name = format!("PUSH{}", i);
  355. opcodes.insert(0x5f + i, new_opcode(&name, 0, 1, 3));
  356. }
  357. for i in 1..17 {
  358. let name = format!("DUP{}", i);
  359. opcodes.insert(0x7f + i, new_opcode(&name, i as u32, i as u32 + 1, 3));
  360. let name = format!("SWAP{}", i);
  361. opcodes.insert(0x8f + i, new_opcode(&name, i as u32 + 1, i as u32 + 1, 3));
  362. }
  363. opcodes
  364. }
  365. #[cfg(test)]
  366. mod tests {
  367. use super::*;
  368. #[test]
  369. fn stack_simple_push_pop() {
  370. let mut s = Stack::new();
  371. s.push(str_to_u256("1"));
  372. s.push(str_to_u256("2"));
  373. s.push(str_to_u256("3"));
  374. assert_eq!(s.pop(), str_to_u256("3"));
  375. assert_eq!(s.pop(), str_to_u256("2"));
  376. assert_eq!(s.pop(), str_to_u256("1"));
  377. // assert_eq!(s.pop(), str_to_u256("1"));
  378. // assert_eq!(s.pop(), error); // TODO expect error as stack is empty
  379. }
  380. // arithmetic
  381. #[test]
  382. fn execute_opcodes_0() {
  383. let code = hex::decode("6005600c01").unwrap(); // 5+12
  384. let calldata = vec![];
  385. let mut s = Stack::new();
  386. s.execute(&code, &calldata, false);
  387. assert_eq!(s.pop(), str_to_u256("17"));
  388. assert_eq!(s.gas, 9999999991);
  389. assert_eq!(s.pc, 5);
  390. }
  391. #[test]
  392. fn execute_opcodes_1() {
  393. let code = hex::decode("60056004016000526001601ff3").unwrap();
  394. let calldata = vec![];
  395. let mut s = Stack::new();
  396. let out = s.execute(&code, &calldata, false);
  397. assert_eq!(out[0], 0x09);
  398. assert_eq!(s.gas, 9999999976);
  399. assert_eq!(s.pc, 12);
  400. // assert_eq!(s.pop(), err); // TODO expect error as stack is empty
  401. }
  402. #[test]
  403. fn execute_opcodes_2() {
  404. let code = hex::decode("61010161010201").unwrap();
  405. let calldata = vec![];
  406. let mut s = Stack::new();
  407. s.execute(&code, &calldata, false);
  408. // assert_eq!(out[0], 0x09);
  409. assert_eq!(s.gas, 9999999991);
  410. assert_eq!(s.pc, 7);
  411. assert_eq!(s.pop(), str_to_u256("515"));
  412. }
  413. #[test]
  414. fn execute_opcodes_3() {
  415. // contains calldata
  416. let code = hex::decode("60003560203501").unwrap();
  417. let calldata = hex::decode("00000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000004").unwrap();
  418. let mut s = Stack::new();
  419. s.execute(&code, &calldata, false);
  420. assert_eq!(s.gas, 9999999985);
  421. assert_eq!(s.pc, 7);
  422. assert_eq!(s.pop(), str_to_u256("9"));
  423. }
  424. }