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.

445 lines
17 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
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
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. use super::*;
  2. use num_bigint::BigUint;
  3. use num_traits::identities::Zero;
  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 EXP_SUPPLEMENTAL_GAS: usize = 40;
  14. const GCOPY: usize = 3; // cost to copy one 32 byte word
  15. const GCONTRACTBYTE: usize = 200; // one byte of code in contract creation
  16. const GCALLVALUETRANSFER: usize = 9000; // non-zero-valued call
  17. const GLOGBYTE: usize = 8; // cost of a byte of logdata
  18. const GTXCOST: usize = 21000; // TX BASE GAS COST
  19. const GTXDATAZERO: usize = 4; // TX DATA ZERO BYTE GAS COST
  20. const GTXDATANONZERO: usize = 68; // TX DATA NON ZERO BYTE GAS COST
  21. const GSHA3WORD: usize = 6; // Cost of SHA3 per word
  22. const GSHA256BASE: usize = 60; // Base c of SHA256
  23. const GSHA256WORD: usize = 12; // Cost of SHA256 per word
  24. const GRIPEMD160BASE: usize = 600; // Base cost of RIPEMD160
  25. const GRIPEMD160WORD: usize = 120; // Cost of RIPEMD160 per word
  26. const GIDENTITYBASE: usize = 15; // Base cost of indentity
  27. const GIDENTITYWORD: usize = 3; // Cost of identity per word
  28. const GECRECOVER: usize = 3000; // Cost of ecrecover op
  29. const GSTIPEND: usize = 2300;
  30. const GCALLNEWACCOUNT: usize = 25000;
  31. const GSUICIDEREFUND: usize = 24000;
  32. pub struct Opcode {
  33. pub name: String,
  34. pub ins: u32,
  35. pub outs: u32,
  36. pub gas: u64,
  37. // operation: fn(),
  38. }
  39. pub fn new_opcode(name: &str, ins: u32, outs: u32, gas: u64) -> Opcode {
  40. Opcode {
  41. name: name.to_string(),
  42. ins,
  43. outs,
  44. gas,
  45. }
  46. }
  47. pub fn new_opcodes() -> HashMap<u8, Opcode> {
  48. let mut opcodes: HashMap<u8, Opcode> = HashMap::new();
  49. // arithmetic
  50. opcodes.insert(0x00, new_opcode("STOP", 0, 0, 0));
  51. opcodes.insert(0x01, new_opcode("ADD", 2, 1, 3));
  52. opcodes.insert(0x02, new_opcode("MUL", 2, 1, 5));
  53. opcodes.insert(0x03, new_opcode("SUB", 2, 1, 3));
  54. opcodes.insert(0x04, new_opcode("DIV", 2, 1, 5));
  55. opcodes.insert(0x05, new_opcode("SDIV", 2, 1, 5));
  56. opcodes.insert(0x06, new_opcode("MOD", 2, 1, 5));
  57. opcodes.insert(0x07, new_opcode("SMOD", 2, 1, 5));
  58. opcodes.insert(0x08, new_opcode("ADDMOD", 3, 1, 8));
  59. opcodes.insert(0x09, new_opcode("MULMOD", 3, 1, 8));
  60. opcodes.insert(0x0a, new_opcode("EXP", 2, 1, 10));
  61. opcodes.insert(0x0b, new_opcode("SIGNEXTEND", 2, 1, 5));
  62. // boolean
  63. opcodes.insert(0x10, new_opcode("LT", 2, 1, 3));
  64. opcodes.insert(0x11, new_opcode("GT", 2, 1, 3));
  65. opcodes.insert(0x12, new_opcode("SLT", 2, 1, 3));
  66. opcodes.insert(0x13, new_opcode("SGT", 2, 1, 3));
  67. opcodes.insert(0x14, new_opcode("EQ", 2, 1, 3));
  68. opcodes.insert(0x15, new_opcode("ISZERO", 1, 1, 3));
  69. opcodes.insert(0x16, new_opcode("AND", 2, 1, 3));
  70. opcodes.insert(0x17, new_opcode("OR", 2, 1, 3));
  71. opcodes.insert(0x18, new_opcode("XOR", 2, 1, 3));
  72. opcodes.insert(0x19, new_opcode("NOT", 1, 1, 3));
  73. opcodes.insert(0x1a, new_opcode("BYTE", 2, 1, 3));
  74. // crypto
  75. opcodes.insert(0x20, new_opcode("SHA3", 2, 1, 30));
  76. // contract context
  77. opcodes.insert(0x30, new_opcode("ADDRESS", 0, 1, 2));
  78. opcodes.insert(0x31, new_opcode("BALANCE", 1, 1, 20));
  79. opcodes.insert(0x32, new_opcode("ORIGIN", 0, 1, 2));
  80. opcodes.insert(0x33, new_opcode("CALLER", 0, 1, 2));
  81. opcodes.insert(0x34, new_opcode("CALLVALUE", 0, 1, 2));
  82. opcodes.insert(0x35, new_opcode("CALLDATALOAD", 1, 1, 3));
  83. opcodes.insert(0x36, new_opcode("CALLDATASIZE", 0, 1, 2));
  84. opcodes.insert(0x37, new_opcode("CALLDATACOPY", 3, 0, 3));
  85. opcodes.insert(0x38, new_opcode("CODESIZE", 0, 1, 2));
  86. opcodes.insert(0x39, new_opcode("CODECOPY", 3, 0, 3));
  87. opcodes.insert(0x3a, new_opcode("GASPRICE", 0, 1, 2));
  88. opcodes.insert(0x3b, new_opcode("EXTCODESIZE", 1, 1, 20));
  89. opcodes.insert(0x3c, new_opcode("EXTCODECOPY", 4, 0, 20));
  90. // blockchain context
  91. opcodes.insert(0x40, new_opcode("BLOCKHASH", 1, 1, 20));
  92. opcodes.insert(0x41, new_opcode("COINBASE", 0, 1, 2));
  93. opcodes.insert(0x42, new_opcode("TIMESTAMP", 0, 1, 2));
  94. opcodes.insert(0x43, new_opcode("NUMBER", 0, 1, 2));
  95. opcodes.insert(0x44, new_opcode("DIFFICULTY", 0, 1, 2));
  96. opcodes.insert(0x45, new_opcode("GASLIMIT", 0, 1, 2));
  97. // storage and execution
  98. opcodes.insert(0x50, new_opcode("POP", 1, 0, 2));
  99. opcodes.insert(0x51, new_opcode("MLOAD", 1, 1, 3));
  100. opcodes.insert(0x52, new_opcode("MSTORE", 2, 0, 3));
  101. opcodes.insert(0x53, new_opcode("MSTORE8", 2, 0, 3));
  102. opcodes.insert(0x54, new_opcode("SLOAD", 1, 1, 50));
  103. opcodes.insert(0x55, new_opcode("SSTORE", 2, 0, 0));
  104. opcodes.insert(0x56, new_opcode("JUMP", 1, 0, 8));
  105. opcodes.insert(0x57, new_opcode("JUMPI", 2, 0, 10));
  106. opcodes.insert(0x58, new_opcode("PC", 0, 1, 2));
  107. opcodes.insert(0x59, new_opcode("MSIZE", 0, 1, 2));
  108. opcodes.insert(0x5a, new_opcode("GAS", 0, 1, 2));
  109. opcodes.insert(0x5b, new_opcode("JUMPDEST", 0, 0, 1));
  110. // logging
  111. opcodes.insert(0xa0, new_opcode("LOG0", 2, 0, 375));
  112. opcodes.insert(0xa1, new_opcode("LOG1", 3, 0, 750));
  113. opcodes.insert(0xa2, new_opcode("LOG2", 4, 0, 1125));
  114. opcodes.insert(0xa3, new_opcode("LOG3", 5, 0, 1500));
  115. opcodes.insert(0xa4, new_opcode("LOG4", 6, 0, 1875));
  116. // closures
  117. opcodes.insert(0xf0, new_opcode("CREATE", 3, 1, 32000));
  118. opcodes.insert(0xf1, new_opcode("CALL", 7, 1, 40));
  119. opcodes.insert(0xf2, new_opcode("CALLCODE", 7, 1, 40));
  120. opcodes.insert(0xf3, new_opcode("RETURN", 2, 0, 0));
  121. opcodes.insert(0xf4, new_opcode("DELEGATECALL", 6, 0, 40));
  122. opcodes.insert(0xff, new_opcode("SUICIDE", 1, 0, 0));
  123. for i in 1..33 {
  124. let name = format!("PUSH{}", i);
  125. opcodes.insert(0x5f + i, new_opcode(&name, 0, 1, 3));
  126. }
  127. for i in 1..17 {
  128. let name = format!("DUP{}", i);
  129. opcodes.insert(0x7f + i, new_opcode(&name, i as u32, i as u32 + 1, 3));
  130. let name = format!("SWAP{}", i);
  131. opcodes.insert(0x8f + i, new_opcode(&name, i as u32 + 1, i as u32 + 1, 3));
  132. }
  133. opcodes
  134. }
  135. impl Stack {
  136. // arithmetic
  137. // TODO instead of [u8;32] converted to BigUint, use custom type uint256 that implements all
  138. // the arithmetic
  139. pub fn add(&mut self) -> Result<(), String> {
  140. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  141. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  142. self.push_arbitrary(&(b0 + b1).to_bytes_be());
  143. Ok(())
  144. }
  145. pub fn mul(&mut self) -> Result<(), String> {
  146. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  147. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  148. self.push_arbitrary(&(b0 * b1).to_bytes_be());
  149. Ok(())
  150. }
  151. pub fn sub(&mut self) -> Result<(), String> {
  152. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  153. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  154. if b0 >= b1 {
  155. self.push_arbitrary(&(b0 - b1).to_bytes_be());
  156. } else {
  157. // 2**256 TODO this will not be here hardcoded, there will be a custom type uint256
  158. let max =
  159. "115792089237316195423570985008687907853269984665640564039457584007913129639936"
  160. .parse::<BigUint>()
  161. .unwrap();
  162. self.push_arbitrary(&(max + b0 - b1).to_bytes_be());
  163. }
  164. Ok(())
  165. }
  166. pub fn div(&mut self) -> Result<(), String> {
  167. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  168. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  169. self.push_arbitrary(&(b0 / b1).to_bytes_be());
  170. Ok(())
  171. }
  172. pub fn sdiv(&mut self) -> Result<(), String> {
  173. Err("unimplemented".to_string())
  174. }
  175. pub fn modulus(&mut self) -> Result<(), String> {
  176. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  177. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  178. self.push_arbitrary(&(b0 % b1).to_bytes_be());
  179. Ok(())
  180. }
  181. pub fn smod(&mut self) -> Result<(), String> {
  182. Err("unimplemented".to_string())
  183. }
  184. pub fn add_mod(&mut self) -> Result<(), String> {
  185. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  186. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  187. let b2 = BigUint::from_bytes_be(&self.pop()?[..]);
  188. self.push_arbitrary(&(b0 + b1 % b2).to_bytes_be());
  189. Ok(())
  190. }
  191. pub fn mul_mod(&mut self) -> Result<(), String> {
  192. let b0 = BigUint::from_bytes_be(&self.pop()?[..]);
  193. let b1 = BigUint::from_bytes_be(&self.pop()?[..]);
  194. let b2 = BigUint::from_bytes_be(&self.pop()?[..]);
  195. self.push_arbitrary(&(b0 * b1 % b2).to_bytes_be());
  196. Ok(())
  197. }
  198. pub fn exp(&mut self) -> Result<(), String> {
  199. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  200. let e = BigUint::from_bytes_be(&self.pop()?[..]);
  201. let mut r = "1".parse::<BigUint>().unwrap();
  202. let zero = "0".parse::<BigUint>().unwrap();
  203. let mut rem = e.clone();
  204. let mut exp = b;
  205. // 2**256 TODO this will not be here hardcoded, there will be a custom type uint256
  206. let field =
  207. "115792089237316195423570985008687907853269984665640564039457584007913129639936"
  208. .parse::<BigUint>()
  209. .unwrap();
  210. while rem != zero {
  211. if rem.bit(0) {
  212. // is odd
  213. r = r * exp.clone() % field.clone();
  214. }
  215. exp = exp.clone() * exp.clone();
  216. rem >>= 1;
  217. }
  218. self.push_arbitrary(&r.to_bytes_be());
  219. let n_bytes = &e.to_bytes_be().len();
  220. let mut exp_fee = n_bytes * GEXPONENTBYTE;
  221. exp_fee += EXP_SUPPLEMENTAL_GAS * n_bytes;
  222. self.gas -= exp_fee as u64;
  223. Ok(())
  224. }
  225. // boolean
  226. pub fn lt(&mut self) -> Result<(), String> {
  227. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  228. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  229. self.push(u256::usize_to_u256((a < b) as usize));
  230. Ok(())
  231. }
  232. pub fn gt(&mut self) -> Result<(), String> {
  233. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  234. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  235. self.push(u256::usize_to_u256((a > b) as usize));
  236. Ok(())
  237. }
  238. pub fn eq(&mut self) -> Result<(), String> {
  239. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  240. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  241. self.push(u256::usize_to_u256((a == b) as usize));
  242. Ok(())
  243. }
  244. pub fn is_zero(&mut self) -> Result<(), String> {
  245. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  246. self.push(u256::usize_to_u256(a.is_zero() as usize));
  247. Ok(())
  248. }
  249. pub fn and(&mut self) -> Result<(), String> {
  250. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  251. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  252. self.push_arbitrary(&(a & b).to_bytes_be());
  253. Ok(())
  254. }
  255. pub fn or(&mut self) -> Result<(), String> {
  256. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  257. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  258. self.push_arbitrary(&(a | b).to_bytes_be());
  259. Ok(())
  260. }
  261. pub fn xor(&mut self) -> Result<(), String> {
  262. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  263. let b = BigUint::from_bytes_be(&self.pop()?[..]);
  264. self.push_arbitrary(&(a ^ b).to_bytes_be());
  265. Ok(())
  266. }
  267. pub fn not(&mut self) -> Result<(), String> {
  268. // 2**256-1 TODO this will not be here hardcoded, there will be a custom type uint256
  269. let f = "115792089237316195423570985008687907853269984665640564039457584007913129639935"
  270. .parse::<BigUint>()
  271. .unwrap();
  272. let a = BigUint::from_bytes_be(&self.pop()?[..]);
  273. self.push_arbitrary(&(f - a).to_bytes_be());
  274. Ok(())
  275. }
  276. // crypto
  277. // contract context
  278. pub fn calldata_load(&mut self, calldata: &[u8]) -> Result<(), String> {
  279. let mut start = self.calldata_i;
  280. if !self.stack.is_empty() {
  281. start = u256::u256_to_u64(self.peek()?) as usize;
  282. }
  283. let l = calldata.len();
  284. if start > l {
  285. start = l;
  286. }
  287. let mut end = start + self.calldata_size;
  288. if end > l {
  289. end = l;
  290. }
  291. self.put_arbitrary(&calldata[start..end]);
  292. self.calldata_i += self.calldata_size;
  293. Ok(())
  294. }
  295. pub fn calldata_size(&mut self, calldata: &[u8]) {
  296. self.calldata_size = calldata.len();
  297. self.push(u256::usize_to_u256(self.calldata_size));
  298. }
  299. fn spend_gas_data_copy(&mut self, length: usize) {
  300. let length32 = upper_multiple_of_32(length);
  301. self.gas -= ((GCOPY * length32) / 32) as u64;
  302. }
  303. pub fn code_copy(&mut self, code: &[u8]) -> Result<(), String> {
  304. let dest_offset = u256::u256_to_u64(self.pop()?) as usize;
  305. let offset = u256::u256_to_u64(self.pop()?) as usize;
  306. let length = u256::u256_to_u64(self.pop()?) as usize;
  307. self.extend_mem(dest_offset, length);
  308. self.spend_gas_data_copy(length);
  309. for i in 0..length {
  310. if offset + i < code.len() {
  311. self.mem[dest_offset + i] = code[offset + i];
  312. } else {
  313. self.mem[dest_offset + i] = 0;
  314. }
  315. }
  316. // self.mem[dest_offset..dest_offset+length] =
  317. Ok(())
  318. }
  319. // blockchain context
  320. // storage and execution
  321. pub fn extend_mem(&mut self, start: usize, size: usize) {
  322. if size <= self.mem.len() || start + size <= self.mem.len() {
  323. return;
  324. }
  325. let old_size = self.mem.len() / 32;
  326. let new_size = upper_multiple_of_32(start + size) / 32;
  327. let old_total_fee = old_size * GMEMORY + old_size.pow(2) / GQUADRATICMEMDENOM;
  328. let new_total_fee = new_size * GMEMORY + new_size.pow(2) / GQUADRATICMEMDENOM;
  329. let mem_fee = new_total_fee - old_total_fee;
  330. self.gas -= mem_fee as u64;
  331. let mut new_bytes: Vec<u8> = vec![0; (new_size - old_size) * 32];
  332. self.mem.append(&mut new_bytes);
  333. }
  334. pub fn mload(&mut self) -> Result<(), String> {
  335. let pos = u256::u256_to_u64(self.pop()?) as usize;
  336. self.extend_mem(pos as usize, 32);
  337. let mem32 = self.mem[pos..pos + 32].to_vec();
  338. self.push_arbitrary(&mem32);
  339. Ok(())
  340. }
  341. pub fn mstore(&mut self) -> Result<(), String> {
  342. let pos = u256::u256_to_u64(self.pop()?);
  343. let val = self.pop()?;
  344. self.extend_mem(pos as usize, 32);
  345. self.mem[pos as usize..].copy_from_slice(&val);
  346. Ok(())
  347. }
  348. pub fn sstore(&mut self) -> Result<(), String> {
  349. // TODO WIP
  350. let key = self.pop()?;
  351. let value = self.pop()?;
  352. if self.storage.contains_key(&key) {
  353. let old_value = self.storage.get(&key).unwrap();
  354. if &value.to_vec() == old_value {
  355. // if the new value is the same as the old one, do not set
  356. return Ok(());
  357. }
  358. // if value (from self.pop()) does not exist in the stack, is a STORAGEKILL TODO
  359. println!("mingas {:?}", GSTORAGEMOD);
  360. self.gas -= GSTORAGEMOD as u64;
  361. } else {
  362. // if value does not exist, substract gas for the addition
  363. println!("mingas {:?}", GSTORAGEADD);
  364. self.gas -= GSTORAGEADD as u64;
  365. }
  366. println!(
  367. "insert {:?} - {:?}",
  368. vec_u8_to_hex(key.to_vec()),
  369. vec_u8_to_hex(value.to_vec())
  370. );
  371. self.storage.insert(key, value.to_vec());
  372. Ok(())
  373. }
  374. pub fn jump(&mut self, code: &[u8]) -> Result<(), String> {
  375. // TODO that jump destination is valid
  376. let new_pc = u256::u256_to_u64(self.pop()?) as usize;
  377. if !valid_dest(code, new_pc) {
  378. return Err(format!("not valid dest: {:02x}", new_pc));
  379. }
  380. self.pc = new_pc;
  381. Ok(())
  382. }
  383. pub fn jump_i(&mut self, code: &[u8]) -> Result<(), String> {
  384. let new_pc = u256::u256_to_u64(self.pop()?) as usize;
  385. if !valid_dest(code, new_pc) {
  386. return Err(format!("not valid dest: {:02x}", new_pc));
  387. }
  388. if !self.stack.is_empty() {
  389. let cond = u256::u256_to_u64(self.pop()?) as usize;
  390. if cond != 0 {
  391. self.pc = new_pc;
  392. }
  393. }
  394. // let cont = self.pop();
  395. // if cont {} // TODO depends on having impl Err in pop()
  396. Ok(())
  397. }
  398. pub fn jump_dest(&mut self) -> Result<(), String> {
  399. // TODO
  400. Ok(())
  401. }
  402. }
  403. fn valid_dest(code: &[u8], pos: usize) -> bool {
  404. if code[pos] == 0x5b {
  405. return true;
  406. }
  407. false
  408. }
  409. fn upper_multiple_of_32(n: usize) -> usize {
  410. ((n - 1) | 31) + 1
  411. }