1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! The evmasm crate aims to provide a simple interface for the conversion between
//! evm bytecode and it's human readable form.
//!
//!```
//!extern crate evmasm;
//!use evmasm::{assemble, disassemble};
//!
//!fn main() {
//!    let bytecode = assemble("PUSH1 2 PUSH1 1 ADD").unwrap();
//!    println!("{:?}", bytecode);
//!    let code = disassemble(&bytecode).unwrap();
//!    for ln in code {
//!        println!("{}", ln);
//!    }
//!}
//!```
//!
//!```
//!extern crate evmasm;
//!use evmasm::{BYTE_INST, instruction, arguments_size};
//!
//!fn main() {
//!    for (&bc, _) in BYTE_INST.iter() {
//!        let inst = instruction(bc).ok().unwrap();
//!        println!("0x{:2x} - {} - needs {} bytes of arguments",
//!                 bc,
//!                 inst,
//!                 arguments_size(bc).ok().unwrap());
//!    }
//!}
//!```

use std::iter;

#[macro_use]
extern crate lazy_static;

extern crate hex;
use hex::{ToHex, FromHexError};

extern crate num;
use num::bigint::{BigUint, ParseBigIntError};
use num::traits::Num;

mod instructions;
pub use instructions::{BYTE_INST, INST_BYTE};

/// Error is only returned when an instruction/bytecode is not found
#[derive(Debug)]
pub enum Error {
    UnknownBytecode(u8),
    UnknownInstruction(String),
    NotEnoughBytes,
    BadValue,
    MissingPushValue,
}

impl From<FromHexError> for Error {
    fn from(e: FromHexError) -> Error {
        match e {
            FromHexError::InvalidHexCharacter { .. } |
            FromHexError::InvalidHexLength => Error::BadValue,
        }
    }
}

impl From<ParseBigIntError> for Error {
    fn from(e: ParseBigIntError) -> Error {
        match e {
            ParseBigIntError::ParseInt(_) |
            ParseBigIntError::Other => Error::BadValue,
        }
    }
}

/// Return the bytecode corresponding to the provided instruction
pub fn bytecode(inst: &str) -> Result<u8, Error> {
    match INST_BYTE.get(inst) {
        Some(bc) => Ok(*bc),
        None => Err(Error::UnknownInstruction(inst.to_string())),
    }
}

/// Return the instruction corresponding to the provided bytecode
pub fn instruction(bytecode: u8) -> Result<&'static str, Error> {
    match BYTE_INST.get(&bytecode) {
        Some(i) => Ok(*i),
        None => Err(Error::UnknownBytecode(bytecode)),
    }
}

/// Return the size in bytes of the arguments of a specific bytecode
pub fn arguments_size(bytecode: u8) -> Result<usize, Error> {
    if bytecode > 0x5f && bytecode < 0x80 {
        Ok((bytecode as usize) - 0x5f)
    } else if BYTE_INST.contains_key(&bytecode) {
        Ok(0)
    } else {
        Err(Error::UnknownBytecode(bytecode))
    }
}

// Parse and assemble
pub fn assemble(code: &str) -> Result<Vec<u8>, Error> {
    let w: Vec<_> = code.to_string()
        .split_whitespace()
        .map(|v| v.to_uppercase())
        .collect();
    let mut r = Vec::with_capacity(w.len() * 2);
    let mut words = w.iter();
    while let Some(word) = words.next() {
        let opcode = bytecode(word)?;
        r.push(opcode);
        let args_size = arguments_size(opcode)?;
        if args_size > 0 {
            let value = match words.next() {
                Some(v) => parse_value(v)?,
                None => return Err(Error::MissingPushValue),
            };
            let extra = iter::repeat(0 as u8).take(args_size - value.len());
            r.extend(extra);
            r.extend(value);
        }
    }
    Ok(r)
}

fn parse_value(val: &str) -> Result<Vec<u8>, Error> {
    let (radix, val_str) = if val.starts_with('0') {
        let vs = &val[1..];
        if vs.starts_with('X') {
            (16, &vs[1..])
        } else if vs.starts_with('B') {
            (2, &vs[1..])
        } else {
            (8, vs)
        }
    } else {
        (10, val)
    };
    Ok(BigUint::from_str_radix(val_str, radix)?.to_bytes_be())
}

// Disassemble
pub fn disassemble(bytes: &[u8]) -> Result<Vec<String>, Error> {
    let mut r = Vec::with_capacity(4096);
    let mut b = bytes;
    while !b.is_empty() {
        let opcode = b[0];
        b = &b[1..];
        let mut inst = instruction(opcode)?.to_string();
        let args_size = arguments_size(opcode).unwrap();
        if args_size != 0 {
            if b.len() < args_size {
                return Err(Error::NotEnoughBytes);
            }
            let args = &b[..args_size];
            b = &b[args_size..];
            let inst_sz = inst.len();
            inst.reserve(inst_sz + 3 + args_size * 2);
            inst.push_str(" 0x");
            inst.push_str(&args.to_vec().to_hex());
        }
        r.push(inst);
    }
    Ok(r)
}

#[cfg(test)]
mod tests {
    use std::iter;
    use super::{bytecode, assemble, disassemble};

    #[test]
    fn unknown_instruction() {
        if let Ok(_) = bytecode("hello world") {
            panic!("not an instruction");
        }
    }

    #[test]
    fn all_instructions() {
        let mut all_instructions = "STOP ADD MUL SUB DIV SDIV MOD SMOD ADDMOD MULMOD EXP SIGNEXTEND LT GT SLT SGT EQ ISZERO AND OR XOR NOT BYTE SHA3 ADDRESS BALANCE ORIGIN CALLER CALLVALUE CALLDATALOAD CALLDATASIZE CALLDATACOPY CODESIZE CODECOPY TXGASPRICE EXTCODESIZE EXTCODECOPY BLOCKHASH COINBASE TIMESTAMP NUMBER DIFFICULTY GASLIMIT POP MLOAD MSTORE MSTORE8 SLOAD SSTORE JUMP JUMPI PC MSIZE GAS JUMPDEST DUP1 DUP2 DUP3 DUP4 DUP5 DUP6 DUP7 DUP8 DUP9 DUP10 DUP11 DUP12 DUP13 DUP14 DUP15 DUP16 SWAP1 SWAP2 SWAP3 SWAP4 SWAP5 SWAP6 SWAP7 SWAP8 SWAP9 SWAP10 SWAP11 SWAP12 SWAP13 SWAP14 SWAP15 SWAP16 LOG0 LOG1 LOG2 LOG3 LOG4 CREATE CALL CALLCODE RETURN DELEGATECALL SUICIDE"
                .to_string();
        for i in 1..33 {
            all_instructions.push_str(&format!(" PUSH{} 0x{}",
                                              i,
                                              iter::repeat("00").take(i).collect::<String>()));
        }
        let exp_opcodes =
            vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
                 32, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 64, 65, 66, 67, 68, 69,
                 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 128, 129, 130, 131, 132, 133,
                 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
                 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 240,
                 241, 242, 243, 244, 255, 96, 0, 97, 0, 0, 98, 0, 0, 0, 99, 0, 0, 0, 0, 100, 0, 0,
                 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 102, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 0, 0, 0, 0,
                 0, 0, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 106, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 108, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 111, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 113,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 114, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 117, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        let opcodes = assemble(&all_instructions).unwrap();
        assert_eq!(opcodes, exp_opcodes);
        let insts = disassemble(&opcodes).unwrap();
        let all_insts = &insts.join(" ");
        assert_eq!(&all_instructions, all_insts);
    }
}