separated tracing logic to its own trait

This commit is contained in:
debris 2016-04-08 01:50:55 +02:00
parent 09beeaba8e
commit 64294853cc
6 changed files with 431 additions and 246 deletions

View File

@ -113,12 +113,20 @@ impl<'a> Executive<'a> {
} }
/// Creates `Externalities` from `Executive`. /// Creates `Externalities` from `Executive`.
pub fn as_externalities<'_>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_, '_>) -> Externalities { pub fn as_externalities<'_, T>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_, '_>, tracer: &'_ mut T) -> Externalities<'_, T> where T: Tracer {
Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output) Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output, tracer)
} }
/// This funtion should be used to execute transaction. /// This funtion should be used to execute transaction.
pub fn transact(&'a mut self, t: &SignedTransaction, options: TransactOptions) -> Result<Executed, Error> { pub fn transact(&'a mut self, t: &SignedTransaction, options: TransactOptions) -> Result<Executed, Error> {
let check = options.check_nonce;
match options.tracing {
true => self.transact_with_tracer(t, check, ExecutiveTracer::default()),
false => self.transact_with_tracer(t, check, NoopTracer),
}
}
pub fn transact_with_tracer<T>(&'a mut self, t: &SignedTransaction, check_nonce: bool, mut tracer: T) -> Result<Executed, Error> where T: Tracer {
let sender = try!(t.sender()); let sender = try!(t.sender());
let nonce = self.state.nonce(&sender); let nonce = self.state.nonce(&sender);
@ -132,7 +140,7 @@ impl<'a> Executive<'a> {
let init_gas = t.gas - base_gas_required; let init_gas = t.gas - base_gas_required;
// validate transaction nonce // validate transaction nonce
if options.check_nonce { if check_nonce {
if t.nonce != nonce { if t.nonce != nonce {
return Err(From::from(ExecutionError::InvalidNonce { expected: nonce, got: t.nonce })); return Err(From::from(ExecutionError::InvalidNonce { expected: nonce, got: t.nonce }));
} }
@ -161,7 +169,7 @@ impl<'a> Executive<'a> {
self.state.inc_nonce(&sender); self.state.inc_nonce(&sender);
self.state.sub_balance(&sender, &U256::from(gas_cost)); self.state.sub_balance(&sender, &U256::from(gas_cost));
let mut substate = Substate::new(options.tracing); let mut substate = Substate::new();
let (gas_left, output) = match t.action { let (gas_left, output) = match t.action {
Action::Create => { Action::Create => {
@ -177,7 +185,7 @@ impl<'a> Executive<'a> {
code: Some(t.data.clone()), code: Some(t.data.clone()),
data: None, data: None,
}; };
(self.create(params, &mut substate), vec![]) (self.create(params, &mut substate, &mut tracer), vec![])
}, },
Action::Call(ref address) => { Action::Call(ref address) => {
let params = ActionParams { let params = ActionParams {
@ -193,18 +201,19 @@ impl<'a> Executive<'a> {
}; };
// TODO: move output upstream // TODO: move output upstream
let mut out = vec![]; let mut out = vec![];
(self.call(params, &mut substate, BytesRef::Flexible(&mut out)), out) (self.call(params, &mut substate, BytesRef::Flexible(&mut out), &mut tracer), out)
} }
}; };
// finalize here! // finalize here!
Ok(try!(self.finalize(t, substate, gas_left, output))) Ok(try!(self.finalize(t, substate, gas_left, output, tracer.traces().pop())))
} }
fn exec_vm(&mut self, params: ActionParams, unconfirmed_substate: &mut Substate, output_policy: OutputPolicy) -> evm::Result { fn exec_vm<T>(&mut self, params: ActionParams, unconfirmed_substate: &mut Substate, output_policy: OutputPolicy, tracer: &mut T)
-> evm::Result where T: Tracer {
// Ordinary execution - keep VM in same thread // Ordinary execution - keep VM in same thread
if (self.depth + 1) % MAX_VM_DEPTH_FOR_THREAD != 0 { if (self.depth + 1) % MAX_VM_DEPTH_FOR_THREAD != 0 {
let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy); let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer);
let vm_factory = self.engine.vm_factory(); let vm_factory = self.engine.vm_factory();
trace!(target: "executive", "ext.schedule.have_delegate_call: {}", ext.schedule().have_delegate_call); trace!(target: "executive", "ext.schedule.have_delegate_call: {}", ext.schedule().have_delegate_call);
return vm_factory.create().exec(params, &mut ext); return vm_factory.create().exec(params, &mut ext);
@ -214,7 +223,7 @@ impl<'a> Executive<'a> {
// TODO [todr] No thread builder yet, so we need to reset once for a while // TODO [todr] No thread builder yet, so we need to reset once for a while
// https://github.com/aturon/crossbeam/issues/16 // https://github.com/aturon/crossbeam/issues/16
crossbeam::scope(|scope| { crossbeam::scope(|scope| {
let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy); let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer);
let vm_factory = self.engine.vm_factory(); let vm_factory = self.engine.vm_factory();
scope.spawn(move || { scope.spawn(move || {
@ -227,7 +236,8 @@ impl<'a> Executive<'a> {
/// NOTE. It does not finalize the transaction (doesn't do refunds, nor suicides). /// NOTE. It does not finalize the transaction (doesn't do refunds, nor suicides).
/// Modifies the substate and the output. /// Modifies the substate and the output.
/// Returns either gas_left or `evm::Error`. /// Returns either gas_left or `evm::Error`.
pub fn call(&mut self, params: ActionParams, substate: &mut Substate, mut output: BytesRef) -> evm::Result { pub fn call<T>(&mut self, params: ActionParams, substate: &mut Substate, mut output: BytesRef, tracer: &mut T)
-> evm::Result where T: Tracer {
// backup used in case of running out of gas // backup used in case of running out of gas
self.state.snapshot(); self.state.snapshot();
@ -257,49 +267,45 @@ impl<'a> Executive<'a> {
} }
} }
} else { } else {
// if destination is a contract, do normal message call let trace_info = tracer.prepare_trace_call(&params);
let mut trace_output = tracer.prepare_trace_output();
// don't trace if it's DELEGATECALL or CALLCODE. let mut subtracer = tracer.subtracer();
let should_trace = if let ActionValue::Transfer(_) = params.value { let delegate_call = params.code_address != params.address;
params.code_address == params.address && substate.subtraces.is_some() let gas = params.gas;
} else { false };
// transaction tracing stuff. None if there's no tracing.
let (mut trace_info, mut trace_output) = if should_trace {
(Some((TraceAction::from_call(&params), self.depth)), Some(vec![]))
} else { (None, None) };
if params.code.is_some() { if params.code.is_some() {
// part of substate that may be reverted // part of substate that may be reverted
let mut unconfirmed_substate = Substate::new(should_trace); let mut unconfirmed_substate = Substate::new();
let res = { let res = {
self.exec_vm(params, &mut unconfirmed_substate, OutputPolicy::Return(output, trace_output.as_mut())) self.exec_vm(params, &mut unconfirmed_substate, OutputPolicy::Return(output, trace_output.as_mut()), &mut subtracer)
}; };
trace!(target: "executive", "res={:?}", res); trace!(target: "executive", "res={:?}", res);
// if there's tracing, make up trace_info's result with trace_output and some arithmetic. let traces = subtracer.traces();
if let Some((TraceAction::Call(ref mut c), _)) = trace_info { match res {
c.result = res.as_ref().ok().map(|gas_left| TraceCallResult { Ok(gas_left) => tracer.trace_call(
gas_used: c.gas - *gas_left, trace_info,
output: trace_output.expect("trace_info is Some: qed") gas - gas_left,
}); trace_output,
} self.depth,
traces,
delegate_call
),
_ => tracer.trace_failed_call(trace_info, self.depth, traces, delegate_call),
};
trace!(target: "executive", "substate={:?}; unconfirmed_substate={:?}\n", substate, unconfirmed_substate); trace!(target: "executive", "substate={:?}; unconfirmed_substate={:?}\n", substate, unconfirmed_substate);
self.enact_result(&res, substate, unconfirmed_substate, trace_info); self.enact_result(&res, substate, unconfirmed_substate);
trace!(target: "executive", "enacted: substate={:?}\n", substate); trace!(target: "executive", "enacted: substate={:?}\n", substate);
res res
} else { } else {
// otherwise it's just a basic transaction, only do tracing, if necessary. // otherwise it's just a basic transaction, only do tracing, if necessary.
trace!(target: "executive", "Basic message (send funds) should_trace={}", should_trace);
self.state.clear_snapshot(); self.state.clear_snapshot();
if let Some((TraceAction::Call(ref mut c), _)) = trace_info {
c.result = Some(TraceCallResult::default());// Some((x!(0), vec![])); tracer.trace_call(trace_info, U256::zero(), Some(vec![]), self.depth, vec![], delegate_call);
}
substate.accrue_trace(if should_trace {Some(vec![])} else {None}, trace_info);
Ok(params.gas) Ok(params.gas)
} }
} }
@ -308,12 +314,13 @@ impl<'a> Executive<'a> {
/// Creates contract with given contract params. /// Creates contract with given contract params.
/// NOTE. It does not finalize the transaction (doesn't do refunds, nor suicides). /// NOTE. It does not finalize the transaction (doesn't do refunds, nor suicides).
/// Modifies the substate. /// Modifies the substate.
pub fn create(&mut self, params: ActionParams, substate: &mut Substate) -> evm::Result { pub fn create<T>(&mut self, params: ActionParams, substate: &mut Substate, tracer: &mut T) -> evm::Result where T:
Tracer {
// backup used in case of running out of gas // backup used in case of running out of gas
self.state.snapshot(); self.state.snapshot();
// part of substate that may be reverted // part of substate that may be reverted
let mut unconfirmed_substate = Substate::new(substate.subtraces.is_some()); let mut unconfirmed_substate = Substate::new();
// create contract and transfer value to it if necessary // create contract and transfer value to it if necessary
let prev_bal = self.state.balance(&params.address); let prev_bal = self.state.balance(&params.address);
@ -324,30 +331,34 @@ impl<'a> Executive<'a> {
self.state.new_contract(&params.address, prev_bal); self.state.new_contract(&params.address, prev_bal);
} }
let mut trace_info = substate.subtraces.as_ref().map(|_| (TraceAction::from_create(&params), self.depth)); let trace_info = tracer.prepare_trace_create(&params);
let mut trace_output = trace_info.as_ref().map(|_| vec![]); let mut trace_output = tracer.prepare_trace_output();
let mut subtracer = tracer.subtracer();
let gas = params.gas;
let created = params.address.clone(); let created = params.address.clone();
let res = { let res = {
self.exec_vm(params, &mut unconfirmed_substate, OutputPolicy::InitContract(trace_output.as_mut())) self.exec_vm(params, &mut unconfirmed_substate, OutputPolicy::InitContract(trace_output.as_mut()), &mut subtracer)
}; };
if let Some((TraceAction::Create(ref mut c), _)) = trace_info { match res {
c.result = res.as_ref().ok().map(|gas_left| TraceCreateResult { Ok(gas_left) => tracer.trace_create(
gas_used: c.gas - *gas_left, trace_info,
address: created, gas - gas_left,
code: trace_output.expect("trace_info is Some: qed") trace_output,
}); created,
} self.depth,
subtracer.traces()
),
_ => tracer.trace_failed_create(trace_info, self.depth, subtracer.traces())
};
trace!(target: "executive", "trace_info={:?}", trace_info); self.enact_result(&res, substate, unconfirmed_substate);
self.enact_result(&res, substate, unconfirmed_substate, trace_info);
res res
} }
/// Finalizes the transaction (does refunds and suicides). /// Finalizes the transaction (does refunds and suicides).
fn finalize(&mut self, t: &SignedTransaction, substate: Substate, result: evm::Result, output: Bytes) -> ExecutionResult { fn finalize(&mut self, t: &SignedTransaction, substate: Substate, result: evm::Result, output: Bytes, trace: Option<Trace>) -> ExecutionResult {
let schedule = self.engine.schedule(self.info); let schedule = self.engine.schedule(self.info);
// refunds from SSTORE nonzero -> zero // refunds from SSTORE nonzero -> zero
@ -378,8 +389,6 @@ impl<'a> Executive<'a> {
self.state.kill_account(address); self.state.kill_account(address);
} }
let trace = substate.subtraces.and_then(|mut v| v.pop());
match result { match result {
Err(evm::Error::Internal) => Err(ExecutionError::Internal), Err(evm::Error::Internal) => Err(ExecutionError::Internal),
Err(_) => { Err(_) => {
@ -409,7 +418,7 @@ impl<'a> Executive<'a> {
} }
} }
fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate, maybe_info: Option<(TraceAction, usize)>) { fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate) {
match *result { match *result {
Err(evm::Error::OutOfGas) Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination {..}) | Err(evm::Error::BadJumpDestination {..})
@ -417,11 +426,10 @@ impl<'a> Executive<'a> {
| Err(evm::Error::StackUnderflow {..}) | Err(evm::Error::StackUnderflow {..})
| Err(evm::Error::OutOfStack {..}) => { | Err(evm::Error::OutOfStack {..}) => {
self.state.revert_snapshot(); self.state.revert_snapshot();
substate.accrue_trace(un_substate.subtraces, maybe_info)
}, },
Ok(_) | Err(evm::Error::Internal) => { Ok(_) | Err(evm::Error::Internal) => {
self.state.clear_snapshot(); self.state.clear_snapshot();
substate.accrue(un_substate, maybe_info) substate.accrue(un_substate);
} }
} }
} }
@ -459,11 +467,11 @@ mod tests {
state.add_balance(&sender, &U256::from(0x100u64)); state.add_balance(&sender, &U256::from(0x100u64));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate).unwrap() ex.create(params, &mut substate, &mut NoopTracer).unwrap()
}; };
assert_eq!(gas_left, U256::from(79_975)); assert_eq!(gas_left, U256::from(79_975));
@ -518,11 +526,11 @@ mod tests {
state.add_balance(&sender, &U256::from(100)); state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate).unwrap() ex.create(params, &mut substate, &mut NoopTracer).unwrap()
}; };
assert_eq!(gas_left, U256::from(62_976)); assert_eq!(gas_left, U256::from(62_976));
@ -573,16 +581,16 @@ mod tests {
state.add_balance(&sender, &U256::from(100)); state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(5, factory); let engine = TestEngine::new(5, factory);
let mut substate = Substate::new(true); let mut substate = Substate::new();
let mut tracer = ExecutiveTracer::default();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
let output = BytesRef::Fixed(&mut[0u8;0]); let output = BytesRef::Fixed(&mut[0u8;0]);
ex.call(params, &mut substate, output).unwrap() ex.call(params, &mut substate, output, &mut tracer).unwrap()
}; };
println!("trace: {:?}", substate.subtraces); let expected_trace = vec![ Trace {
let expected_trace = Some(vec![ Trace {
depth: 0, depth: 0,
action: TraceAction::Call(TraceCall { action: TraceAction::Call(TraceCall {
from: x!("cd1722f3947def4cf144679da39c4c32bdc35681"), from: x!("cd1722f3947def4cf144679da39c4c32bdc35681"),
@ -590,10 +598,10 @@ mod tests {
value: x!(100), value: x!(100),
gas: x!(100000), gas: x!(100000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(55_248), gas_used: U256::from(55_248),
output: vec![], output: vec![],
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -601,17 +609,17 @@ mod tests {
from: x!("b010143a42d5980c7e5ef0e4a4416dc098a4fed3"), from: x!("b010143a42d5980c7e5ef0e4a4416dc098a4fed3"),
value: x!(23), value: x!(23),
gas: x!(67979), gas: x!(67979),
init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85], init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85]
result: Some(TraceCreateResult { }),
result: TraceResult::Create(TraceCreateResult {
gas_used: U256::from(3224), gas_used: U256::from(3224),
address: Address::from_str("c6d80f262ae5e0f164e5fde365044d7ada2bfa34").unwrap(), address: Address::from_str("c6d80f262ae5e0f164e5fde365044d7ada2bfa34").unwrap(),
code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53] code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53]
})
}), }),
subs: vec![] subs: vec![]
}] }]
} ]); }];
assert_eq!(substate.subtraces, expected_trace); assert_eq!(tracer.traces(), expected_trace);
assert_eq!(gas_left, U256::from(44_752)); assert_eq!(gas_left, U256::from(44_752));
} }
@ -645,30 +653,31 @@ mod tests {
state.add_balance(&sender, &U256::from(100)); state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(5, factory); let engine = TestEngine::new(5, factory);
let mut substate = Substate::new(true); let mut substate = Substate::new();
let mut tracer = ExecutiveTracer::default();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params.clone(), &mut substate).unwrap() ex.create(params.clone(), &mut substate, &mut tracer).unwrap()
}; };
println!("trace: {:?}", substate.subtraces); let expected_trace = vec![Trace {
let expected_trace = Some(vec![Trace {
depth: 0, depth: 0,
action: TraceAction::Create(TraceCreate { action: TraceAction::Create(TraceCreate {
from: params.sender, from: params.sender,
value: x!(100), value: x!(100),
gas: params.gas, gas: params.gas,
init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85], init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85],
result: Some(TraceCreateResult { }),
result: TraceResult::Create(TraceCreateResult {
gas_used: U256::from(3224), gas_used: U256::from(3224),
address: params.address, address: params.address,
code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53] code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53]
})
}), }),
subs: vec![] subs: vec![]
} ]); }];
assert_eq!(substate.subtraces, expected_trace);
assert_eq!(tracer.traces(), expected_trace);
assert_eq!(gas_left, U256::from(96_776)); assert_eq!(gas_left, U256::from(96_776));
} }
@ -714,11 +723,11 @@ mod tests {
state.add_balance(&sender, &U256::from(100)); state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate).unwrap() ex.create(params, &mut substate, &mut NoopTracer).unwrap()
}; };
assert_eq!(gas_left, U256::from(62_976)); assert_eq!(gas_left, U256::from(62_976));
@ -766,11 +775,11 @@ mod tests {
state.add_balance(&sender, &U256::from(100)); state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(1024, factory); let engine = TestEngine::new(1024, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
{ {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate).unwrap(); ex.create(params, &mut substate, &mut NoopTracer).unwrap();
} }
assert_eq!(substate.contracts_created.len(), 1); assert_eq!(substate.contracts_created.len(), 1);
@ -827,11 +836,11 @@ mod tests {
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.call(params, &mut substate, BytesRef::Fixed(&mut [])).unwrap() ex.call(params, &mut substate, BytesRef::Fixed(&mut []), &mut NoopTracer).unwrap()
}; };
assert_eq!(gas_left, U256::from(73_237)); assert_eq!(gas_left, U256::from(73_237));
@ -872,11 +881,11 @@ mod tests {
state.init_code(&address, code.clone()); state.init_code(&address, code.clone());
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let gas_left = { let gas_left = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.call(params, &mut substate, BytesRef::Fixed(&mut [])).unwrap() ex.call(params, &mut substate, BytesRef::Fixed(&mut []), &mut NoopTracer).unwrap()
}; };
assert_eq!(gas_left, U256::from(59_870)); assert_eq!(gas_left, U256::from(59_870));
@ -1074,11 +1083,11 @@ mod tests {
state.add_balance(&sender, &U256::from_str("152d02c7e14af6800000").unwrap()); state.add_balance(&sender, &U256::from_str("152d02c7e14af6800000").unwrap());
let info = EnvInfo::default(); let info = EnvInfo::default();
let engine = TestEngine::new(0, factory); let engine = TestEngine::new(0, factory);
let mut substate = Substate::new(false); let mut substate = Substate::new();
let result = { let result = {
let mut ex = Executive::new(&mut state, &info, &engine); let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate) ex.create(params, &mut substate, &mut NoopTracer)
}; };
match result { match result {

View File

@ -54,7 +54,7 @@ impl OriginInfo {
} }
/// Implementation of evm Externalities. /// Implementation of evm Externalities.
pub struct Externalities<'a> { pub struct Externalities<'a, T> where T: 'a + Tracer {
state: &'a mut State, state: &'a mut State,
env_info: &'a EnvInfo, env_info: &'a EnvInfo,
engine: &'a Engine, engine: &'a Engine,
@ -62,10 +62,11 @@ pub struct Externalities<'a> {
origin_info: OriginInfo, origin_info: OriginInfo,
substate: &'a mut Substate, substate: &'a mut Substate,
schedule: Schedule, schedule: Schedule,
output: OutputPolicy<'a, 'a> output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
} }
impl<'a> Externalities<'a> { impl<'a, T> Externalities<'a, T> where T: 'a + Tracer {
/// Basic `Externalities` constructor. /// Basic `Externalities` constructor.
pub fn new(state: &'a mut State, pub fn new(state: &'a mut State,
env_info: &'a EnvInfo, env_info: &'a EnvInfo,
@ -73,7 +74,8 @@ impl<'a> Externalities<'a> {
depth: usize, depth: usize,
origin_info: OriginInfo, origin_info: OriginInfo,
substate: &'a mut Substate, substate: &'a mut Substate,
output: OutputPolicy<'a, 'a> output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
) -> Self { ) -> Self {
Externalities { Externalities {
state: state, state: state,
@ -83,12 +85,13 @@ impl<'a> Externalities<'a> {
origin_info: origin_info, origin_info: origin_info,
substate: substate, substate: substate,
schedule: engine.schedule(env_info), schedule: engine.schedule(env_info),
output: output output: output,
tracer: tracer,
} }
} }
} }
impl<'a> Ext for Externalities<'a> { impl<'a, T> Ext for Externalities<'a, T> where T: 'a + Tracer {
fn storage_at(&self, key: &H256) -> H256 { fn storage_at(&self, key: &H256) -> H256 {
self.state.storage_at(&self.origin_info.address, key) self.state.storage_at(&self.origin_info.address, key)
} }
@ -143,7 +146,7 @@ impl<'a> Ext for Externalities<'a> {
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth); let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth);
// TODO: handle internal error separately // TODO: handle internal error separately
match ex.create(params, self.substate) { match ex.create(params, self.substate, self.tracer) {
Ok(gas_left) => { Ok(gas_left) => {
self.substate.contracts_created.push(address.clone()); self.substate.contracts_created.push(address.clone());
ContractCreateResult::Created(address, gas_left) ContractCreateResult::Created(address, gas_left)
@ -181,7 +184,7 @@ impl<'a> Ext for Externalities<'a> {
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth); let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth);
match ex.call(params, self.substate, BytesRef::Fixed(output)) { match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer) {
Ok(gas_left) => MessageCallResult::Success(gas_left), Ok(gas_left) => MessageCallResult::Success(gas_left),
_ => MessageCallResult::Failed _ => MessageCallResult::Failed
} }
@ -328,7 +331,7 @@ mod tests {
TestSetup { TestSetup {
state: get_temp_state(), state: get_temp_state(),
engine: get_test_spec().to_engine().unwrap(), engine: get_test_spec().to_engine().unwrap(),
sub_state: Substate::new(false), sub_state: Substate::new(),
env_info: get_test_env_info() env_info: get_test_env_info()
} }
} }
@ -338,8 +341,9 @@ mod tests {
fn can_be_created() { fn can_be_created() {
let mut setup = TestSetup::new(); let mut setup = TestSetup::new();
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
assert_eq!(ext.env_info().number, 100); assert_eq!(ext.env_info().number, 100);
} }
@ -348,7 +352,9 @@ mod tests {
fn can_return_block_hash_no_env() { fn can_return_block_hash_no_env() {
let mut setup = TestSetup::new(); let mut setup = TestSetup::new();
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let mut tracer = NoopTracer;
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
@ -367,7 +373,9 @@ mod tests {
env_info.last_hashes.push(test_hash.clone()); env_info.last_hashes.push(test_hash.clone());
} }
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let mut tracer = NoopTracer;
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
@ -379,7 +387,9 @@ mod tests {
fn can_call_fail_empty() { fn can_call_fail_empty() {
let mut setup = TestSetup::new(); let mut setup = TestSetup::new();
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let mut tracer = NoopTracer;
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
let mut output = vec![]; let mut output = vec![];
@ -401,9 +411,10 @@ mod tests {
let mut setup = TestSetup::new(); let mut setup = TestSetup::new();
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
{ {
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
ext.log(log_topics, &log_data); ext.log(log_topics, &log_data);
} }
@ -416,9 +427,10 @@ mod tests {
let mut setup = TestSetup::new(); let mut setup = TestSetup::new();
let state = setup.state.reference_mut(); let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
{ {
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None)); let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer);
ext.suicide(&refund_account); ext.suicide(&refund_account);
} }

View File

@ -398,11 +398,11 @@ fn should_apply_create_transaction() {
value: x!(100), value: x!(100),
gas: x!(77412), gas: x!(77412),
init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85], init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85],
result: Some(TraceCreateResult { }),
result: TraceResult::Create(TraceCreateResult {
gas_used: U256::from(3224), gas_used: U256::from(3224),
address: Address::from_str("8988167e088c87cd314df6d3c2b83da5acb93ace").unwrap(), address: Address::from_str("8988167e088c87cd314df6d3c2b83da5acb93ace").unwrap(),
code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53] code: vec![96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -458,8 +458,8 @@ fn should_trace_failed_create_transaction() {
value: x!(100), value: x!(100),
gas: x!(78792), gas: x!(78792),
init: vec![91, 96, 0, 86], init: vec![91, 96, 0, 86],
result: None
}), }),
result: TraceResult::FailedCreate,
subs: vec![] subs: vec![]
}); });
@ -497,10 +497,10 @@ fn should_trace_call_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(3), gas_used: U256::from(3),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -538,10 +538,10 @@ fn should_trace_basic_call_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(0), gas_used: U256::from(0),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -605,10 +605,10 @@ fn should_not_trace_subcall_transaction_to_builtin() {
value: x!(0), value: x!(0),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(28_061), gas_used: U256::from(28_061),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -647,10 +647,10 @@ fn should_not_trace_callcode() {
value: x!(0), value: x!(0),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(64), gas_used: U256::from(64),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -692,10 +692,10 @@ fn should_not_trace_delegatecall() {
value: x!(0), value: x!(0),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(61), gas_used: U256::from(61),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -733,8 +733,8 @@ fn should_trace_failed_call_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: None
}), }),
result: TraceResult::FailedCall,
subs: vec![] subs: vec![]
}); });
@ -775,10 +775,10 @@ fn should_trace_call_with_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(69), gas_used: U256::from(69),
output: vec![] output: vec![]
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -788,10 +788,10 @@ fn should_trace_call_with_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78934), gas: x!(78934),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(3), gas_used: U256::from(3),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}] }]
@ -831,10 +831,10 @@ fn should_trace_call_with_basic_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(31761), gas_used: U256::from(31761),
output: vec![] output: vec![]
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -844,8 +844,8 @@ fn should_trace_call_with_basic_subcall_transaction() {
value: x!(69), value: x!(69),
gas: x!(2300), gas: x!(2300),
input: vec![], input: vec![],
result: Some(TraceCallResult::default())
}), }),
result: TraceResult::Call(TraceCallResult::default()),
subs: vec![] subs: vec![]
}] }]
}); });
@ -884,10 +884,10 @@ fn should_not_trace_call_with_invalid_basic_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(31761), gas_used: U256::from(31761),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}); });
@ -927,12 +927,10 @@ fn should_trace_failed_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(79_000), gas_used: U256::from(79_000),
output: vec![] output: vec![]
})
// Some((x!(79000), vec![]))
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -942,8 +940,8 @@ fn should_trace_failed_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78934), gas: x!(78934),
input: vec![], input: vec![],
result: None
}), }),
result: TraceResult::FailedCall,
subs: vec![] subs: vec![]
}] }]
}); });
@ -984,10 +982,10 @@ fn should_trace_call_with_subcall_with_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(135), gas_used: U256::from(135),
output: vec![] output: vec![]
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -997,10 +995,10 @@ fn should_trace_call_with_subcall_with_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78934), gas: x!(78934),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(69), gas_used: U256::from(69),
output: vec![] output: vec![]
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 2, depth: 2,
@ -1010,10 +1008,10 @@ fn should_trace_call_with_subcall_with_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78868), gas: x!(78868),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(3), gas_used: U256::from(3),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}] }]
@ -1056,10 +1054,10 @@ fn should_trace_failed_subcall_with_subcall_transaction() {
value: x!(100), value: x!(100),
gas: x!(79000), gas: x!(79000),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(79_000), gas_used: U256::from(79_000),
output: vec![] output: vec![]
})
}), }),
subs: vec![Trace { subs: vec![Trace {
depth: 1, depth: 1,
@ -1069,8 +1067,8 @@ fn should_trace_failed_subcall_with_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78934), gas: x!(78934),
input: vec![], input: vec![],
result: None
}), }),
result: TraceResult::FailedCall,
subs: vec![Trace { subs: vec![Trace {
depth: 2, depth: 2,
action: TraceAction::Call(TraceCall { action: TraceAction::Call(TraceCall {
@ -1079,10 +1077,10 @@ fn should_trace_failed_subcall_with_subcall_transaction() {
value: x!(0), value: x!(0),
gas: x!(78868), gas: x!(78868),
input: vec![], input: vec![],
result: Some(TraceCallResult { }),
result: TraceResult::Call(TraceCallResult {
gas_used: U256::from(3), gas_used: U256::from(3),
output: vec![] output: vec![]
})
}), }),
subs: vec![] subs: vec![]
}] }]

View File

@ -32,44 +32,25 @@ pub struct Substate {
/// Created contracts. /// Created contracts.
pub contracts_created: Vec<Address>, pub contracts_created: Vec<Address>,
/// The trace during this execution or `None` if we're not tracing.
pub subtraces: Option<Vec<Trace>>,
} }
impl Substate { impl Substate {
/// Creates new substate. /// Creates new substate.
pub fn new(tracing: bool) -> Self { pub fn new() -> Self {
Substate { Substate {
suicides: Default::default(), suicides: Default::default(),
logs: Default::default(), logs: Default::default(),
sstore_clears_count: Default::default(), sstore_clears_count: Default::default(),
contracts_created: Default::default(), contracts_created: Default::default(),
subtraces: if tracing {Some(vec![])} else {None},
} }
} }
/// Merge tracing information from substate `s` if enabled. /// Merge secondary substate `s` into self, accruing each element correspondingly.
pub fn accrue_trace(&mut self, subs: Option<Vec<Trace>>, maybe_info: Option<(TraceAction, usize)>) { pub fn accrue(&mut self, s: Substate) {
// it failed, so we don't bother accrueing any protocol-level stuff, only the
// trace info.
if let Some(info) = maybe_info {
self.subtraces.as_mut().expect("maybe_action is Some: so we must be tracing: qed").push(Trace {
action: info.0,
depth: info.1,
subs: subs.expect("maybe_action is Some: so we must be tracing: qed"),
});
}
}
/// Merge secondary substate `s` into self, accruing each element correspondingly; will merge
/// tracing information too, if enabled.
pub fn accrue(&mut self, s: Substate, maybe_info: Option<(TraceAction, usize)>) {
self.suicides.extend(s.suicides.into_iter()); self.suicides.extend(s.suicides.into_iter());
self.logs.extend(s.logs.into_iter()); self.logs.extend(s.logs.into_iter());
self.sstore_clears_count = self.sstore_clears_count + s.sstore_clears_count; self.sstore_clears_count = self.sstore_clears_count + s.sstore_clears_count;
self.contracts_created.extend(s.contracts_created.into_iter()); self.contracts_created.extend(s.contracts_created.into_iter());
self.accrue_trace(s.subtraces, maybe_info);
} }
} }
@ -80,13 +61,13 @@ mod tests {
#[test] #[test]
fn created() { fn created() {
let sub_state = Substate::new(false); let sub_state = Substate::new();
assert_eq!(sub_state.suicides.len(), 0); assert_eq!(sub_state.suicides.len(), 0);
} }
#[test] #[test]
fn accrue() { fn accrue() {
let mut sub_state = Substate::new(false); let mut sub_state = Substate::new();
sub_state.contracts_created.push(address_from_u64(1u64)); sub_state.contracts_created.push(address_from_u64(1u64));
sub_state.logs.push(LogEntry { sub_state.logs.push(LogEntry {
address: address_from_u64(1u64), address: address_from_u64(1u64),
@ -96,7 +77,7 @@ mod tests {
sub_state.sstore_clears_count = x!(5); sub_state.sstore_clears_count = x!(5);
sub_state.suicides.insert(address_from_u64(10u64)); sub_state.suicides.insert(address_from_u64(10u64));
let mut sub_state_2 = Substate::new(false); let mut sub_state_2 = Substate::new();
sub_state_2.contracts_created.push(address_from_u64(2u64)); sub_state_2.contracts_created.push(address_from_u64(2u64));
sub_state_2.logs.push(LogEntry { sub_state_2.logs.push(LogEntry {
address: address_from_u64(1u64), address: address_from_u64(1u64),
@ -105,7 +86,7 @@ mod tests {
}); });
sub_state_2.sstore_clears_count = x!(7); sub_state_2.sstore_clears_count = x!(7);
sub_state.accrue(sub_state_2, None); sub_state.accrue(sub_state_2);
assert_eq!(sub_state.contracts_created.len(), 2); assert_eq!(sub_state.contracts_created.len(), 2);
assert_eq!(sub_state.sstore_clears_count, x!(12)); assert_eq!(sub_state.sstore_clears_count, x!(12));
assert_eq!(sub_state.suicides.len(), 1); assert_eq!(sub_state.suicides.len(), 1);

View File

@ -19,3 +19,181 @@
mod trace; mod trace;
pub use self::trace::*; pub use self::trace::*;
use util::bytes::Bytes;
use util::hash::Address;
use util::numbers::U256;
use action_params::ActionParams;
/// This trait is used by executive to build traces.
pub trait Tracer: Send {
/// Prepares call trace for given params. Noop tracer should return None.
fn prepare_trace_call(&self, params: &ActionParams) -> Option<TraceCall>;
/// Prepares create trace for given params. Noop tracer should return None.
fn prepare_trace_create(&self, params: &ActionParams) -> Option<TraceCreate>;
/// Prepare trace output. Noop tracer should return None.
fn prepare_trace_output(&self) -> Option<Bytes>;
/// Stores trace call info.
fn trace_call(
&mut self,
call: Option<TraceCall>,
gas_used: U256,
output: Option<Bytes>,
depth: usize,
subs: Vec<Trace>,
delegate_call: bool
);
/// Stores trace create info.
fn trace_create(
&mut self,
create: Option<TraceCreate>,
gas_used: U256,
code: Option<Bytes>,
address: Address,
depth: usize,
subs: Vec<Trace>
);
/// Stores failed call trace.
fn trace_failed_call(&mut self, call: Option<TraceCall>, depth: usize, subs: Vec<Trace>, delegate_call: bool);
/// Stores failed create trace.
fn trace_failed_create(&mut self, create: Option<TraceCreate>, depth: usize, subs: Vec<Trace>);
/// Spawn subracer which will be used to trace deeper levels of execution.
fn subtracer(&self) -> Self where Self: Sized;
/// Consumes self and returns all traces.
fn traces(self) -> Vec<Trace>;
}
/// Nonoperative tracer. Does not trace anything.
pub struct NoopTracer;
impl Tracer for NoopTracer {
fn prepare_trace_call(&self, _: &ActionParams) -> Option<TraceCall> {
None
}
fn prepare_trace_create(&self, _: &ActionParams) -> Option<TraceCreate> {
None
}
fn prepare_trace_output(&self) -> Option<Bytes> {
None
}
fn trace_call(&mut self, call: Option<TraceCall>, _: U256, output: Option<Bytes>, _: usize, _: Vec<Trace>,
_: bool) {
assert!(call.is_none());
assert!(output.is_none());
}
fn trace_create(&mut self, create: Option<TraceCreate>, _: U256, code: Option<Bytes>, _: Address, _: usize, _: Vec<Trace>) {
assert!(create.is_none());
assert!(code.is_none());
}
fn trace_failed_call(&mut self, call: Option<TraceCall>, _: usize, _: Vec<Trace>, _: bool) {
assert!(call.is_none());
}
fn trace_failed_create(&mut self, create: Option<TraceCreate>, _: usize, _: Vec<Trace>) {
assert!(create.is_none());
}
fn subtracer(&self) -> Self {
NoopTracer
}
fn traces(self) -> Vec<Trace> {
vec![]
}
}
/// Simple executive tracer. Traces all calls and creates. Ignores delegatecalls.
#[derive(Default)]
pub struct ExecutiveTracer {
traces: Vec<Trace>
}
impl Tracer for ExecutiveTracer {
fn prepare_trace_call(&self, params: &ActionParams) -> Option<TraceCall> {
Some(TraceCall::from(params.clone()))
}
fn prepare_trace_create(&self, params: &ActionParams) -> Option<TraceCreate> {
Some(TraceCreate::from(params.clone()))
}
fn prepare_trace_output(&self) -> Option<Bytes> {
Some(vec![])
}
fn trace_call(&mut self, call: Option<TraceCall>, gas_used: U256, output: Option<Bytes>, depth: usize, subs:
Vec<Trace>, delegate_call: bool) {
if delegate_call {
return;
}
let trace = Trace {
depth: depth,
subs: subs,
action: TraceAction::Call(call.expect("Trace call expected to be Some.")),
result: TraceResult::Call(TraceCallResult {
gas_used: gas_used,
output: output.expect("Trace call output expected to be Some.")
})
};
self.traces.push(trace);
}
fn trace_create(&mut self, create: Option<TraceCreate>, gas_used: U256, code: Option<Bytes>, address: Address, depth: usize, subs: Vec<Trace>) {
let trace = Trace {
depth: depth,
subs: subs,
action: TraceAction::Create(create.expect("Trace create expected to be Some.")),
result: TraceResult::Create(TraceCreateResult {
gas_used: gas_used,
code: code.expect("Trace create code expected to be Some."),
address: address
})
};
self.traces.push(trace);
}
fn trace_failed_call(&mut self, call: Option<TraceCall>, depth: usize, subs: Vec<Trace>, delegate_call: bool) {
if delegate_call {
return;
}
let trace = Trace {
depth: depth,
subs: subs,
action: TraceAction::Call(call.expect("Trace call expected to be Some.")),
result: TraceResult::FailedCall,
};
self.traces.push(trace);
}
fn trace_failed_create(&mut self, create: Option<TraceCreate>, depth: usize, subs: Vec<Trace>) {
let trace = Trace {
depth: depth,
subs: subs,
action: TraceAction::Create(create.expect("Trace create expected to be Some.")),
result: TraceResult::FailedCreate,
};
self.traces.push(trace);
}
fn subtracer(&self) -> Self {
ExecutiveTracer::default()
}
fn traces(self) -> Vec<Trace> {
self.traces
}
}

View File

@ -50,8 +50,18 @@ pub struct TraceCall {
pub gas: U256, pub gas: U256,
/// The input data provided to the call. /// The input data provided to the call.
pub input: Bytes, pub input: Bytes,
/// The result of the operation; the gas used and the output data of the call. }
pub result: Option<TraceCallResult>,
impl From<ActionParams> for TraceCall {
fn from(p: ActionParams) -> Self {
TraceCall {
from: p.sender,
to: p.address,
value: p.value.value(),
gas: p.gas,
input: p.data.unwrap_or_else(Vec::new),
}
}
} }
/// Description of a _create_ action, either a `CREATE` operation or a create transction. /// Description of a _create_ action, either a `CREATE` operation or a create transction.
@ -65,9 +75,17 @@ pub struct TraceCreate {
pub gas: U256, pub gas: U256,
/// The init code. /// The init code.
pub init: Bytes, pub init: Bytes,
/// The result of the operation; tuple of the gas used, the address of the newly created account and its code. }
/// NOTE: Presently failed operations are not reported so this will always be `Some`.
pub result: Option<TraceCreateResult>, impl From<ActionParams> for TraceCreate {
fn from(p: ActionParams) -> Self {
TraceCreate {
from: p.sender,
value: p.value.value(),
gas: p.gas,
init: p.code.unwrap_or_else(Vec::new),
}
}
} }
/// Description of an action that we trace; will be either a call or a create. /// Description of an action that we trace; will be either a call or a create.
@ -79,6 +97,19 @@ pub enum TraceAction {
Create(TraceCreate), Create(TraceCreate),
} }
/// The result of the performed action.
#[derive(Debug, Clone, PartialEq)]
pub enum TraceResult {
/// Successful call action result.
Call(TraceCallResult),
/// Successful create action result.
Create(TraceCreateResult),
/// Failed call.
FailedCall,
/// Failed create.
FailedCreate,
}
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
/// A trace; includes a description of the action being traced and sub traces of each interior action. /// A trace; includes a description of the action being traced and sub traces of each interior action.
pub struct Trace { pub struct Trace {
@ -89,30 +120,6 @@ pub struct Trace {
pub action: TraceAction, pub action: TraceAction,
/// The sub traces for each interior action performed as part of this call. /// The sub traces for each interior action performed as part of this call.
pub subs: Vec<Trace>, pub subs: Vec<Trace>,
/// The result of the performed action.
pub result: TraceResult,
} }
impl TraceAction {
/// Compose a `TraceAction` from an `ActionParams`, knowing that the action is a call.
pub fn from_call(p: &ActionParams) -> TraceAction {
TraceAction::Call(TraceCall {
from: p.sender.clone(),
to: p.address.clone(),
value: p.value.value(),
gas: p.gas,
input: p.data.clone().unwrap_or_else(Vec::new),
result: None,
})
}
/// Compose a `TraceAction` from an `ActionParams`, knowing that the action is a create.
pub fn from_create(p: &ActionParams) -> TraceAction {
TraceAction::Create(TraceCreate {
from: p.sender.clone(),
value: p.value.value(),
gas: p.gas,
init: p.code.clone().unwrap_or_else(Vec::new),
result: None,
})
}
}