Merge pull request #23 from nicksavers/master

Merge small changes
This commit is contained in:
romanman 2014-06-07 09:42:36 +01:00
commit a22dfb99f9
6 changed files with 323 additions and 299 deletions

View File

@ -49,11 +49,11 @@ public class AccountState {
this(ecKey, BigInteger.ZERO, BigInteger.ZERO); this(ecKey, BigInteger.ZERO, BigInteger.ZERO);
} }
public AccountState(byte[] rlpData){ public AccountState(byte[] rlpData) {
this.rlpEncoded = rlpData; this.rlpEncoded = rlpData;
RLPList items = (RLPList)RLP.decode2(rlpEncoded).get(0); RLPList items = (RLPList) RLP.decode2(rlpEncoded).get(0);
this.nonce = new BigInteger(1, ((items.get(0).getRLPData()) == null ? new byte[]{} : items.get(0).getRLPData())); this.nonce = new BigInteger(1, ((items.get(0).getRLPData()) == null ? new byte[0] : items.get(0).getRLPData()));
this.balance = new BigInteger(1, items.get(1).getRLPData()); this.balance = new BigInteger(1, items.get(1).getRLPData());
this.stateRoot = items.get(2).getRLPData(); this.stateRoot = items.get(2).getRLPData();
this.codeHash = items.get(3).getRLPData(); this.codeHash = items.get(3).getRLPData();
@ -88,7 +88,7 @@ public class AccountState {
this.codeHash = codeHash; this.codeHash = codeHash;
} }
public BigInteger getBalance() { public BigInteger getBalance() {
return balance; return balance;
} }

View File

@ -89,6 +89,8 @@ public class Block {
this.transactionsList.add(tx); this.transactionsList.add(tx);
this.txsState.update(RLP.encodeInt(i), tx.getEncoded()); this.txsState.update(RLP.encodeInt(i), tx.getEncoded());
// this.accountState.update();
// YP 4.3.1 // YP 4.3.1
RLPElement cummGas = ((RLPList)rlpTxReceipt).get(1); RLPElement cummGas = ((RLPList)rlpTxReceipt).get(1);
RLPElement pstTxState = ((RLPList)rlpTxReceipt).get(2); RLPElement pstTxState = ((RLPList)rlpTxReceipt).get(2);
@ -184,6 +186,14 @@ public class Block {
return this.header.getNonce(); return this.header.getNonce();
} }
public Trie getAccountState() {
return this.accountState;
}
public Trie getTxsState() {
return this.txsState;
}
public List<Transaction> getTransactionsList() { public List<Transaction> getTransactionsList() {
if (!parsed) parseRLP(); if (!parsed) parseRLP();
if (transactionsList == null) { if (transactionsList == null) {

View File

@ -104,9 +104,7 @@ public class Trie {
* @return value * @return value
*/ */
public byte[] get(String key) { public byte[] get(String key) {
byte[] k = binToNibbles(key.getBytes()); return this.get(key.getBytes());
Value c = new Value( this.get(this.root, k) );
return c.asBytes();
} }
/** /**

View File

@ -35,23 +35,23 @@ public class Program {
public Program(byte[] ops, ProgramInvoke invokeData) { public Program(byte[] ops, ProgramInvoke invokeData) {
if (ops == null) throw new RuntimeException("program can not run with ops: null"); if (ops == null)
throw new RuntimeException("program can not run with ops: null");
this.invokeData = invokeData; this.invokeData = invokeData;
this.ops = ops; this.ops = ops;
} }
public byte getCurrentOp(){ public byte getCurrentOp() {
return ops[pc]; return ops[pc];
} }
public void stackPush(byte[] data) {
public void stackPush(byte[] data){
DataWord stackWord = new DataWord(data); DataWord stackWord = new DataWord(data);
stack.push(stackWord); stack.push(stackWord);
} }
public void stackPush(DataWord stackWord){ public void stackPush(DataWord stackWord) {
stack.push(stackWord); stack.push(stackWord);
} }
@ -72,58 +72,62 @@ public class Program {
this.pc = pc; this.pc = pc;
} }
public boolean isStopped(){ public boolean isStopped() {
return stopped; return stopped;
} }
public void stop(){ public void stop() {
stopped = true; stopped = true;
} }
public void setHReturn(ByteBuffer buff){ public void setHReturn(ByteBuffer buff) {
hReturn = buff; hReturn = buff;
} }
public void step(){ public void step() {
++pc; ++pc;
if (pc >= ops.length) stop(); if (pc >= ops.length)
stop();
} }
public byte[] sweep(int n){ public byte[] sweep(int n) {
if (pc + n > ops.length) { if (pc + n > ops.length) {
stop(); stop();
throw new RuntimeException("pc overflow sweep n: " + n + " pc: " + pc); throw new RuntimeException("pc overflow sweep n: " + n + " pc: "
+ pc);
} }
byte[] data = Arrays.copyOfRange(ops, pc, pc + n); byte[] data = Arrays.copyOfRange(ops, pc, pc + n);
pc += n; pc += n;
if (pc >= ops.length) stop(); if (pc >= ops.length)
stop();
return data; return data;
} }
public DataWord stackPop(){ public DataWord stackPop() {
if (stack.size() == 0){ if (stack.size() == 0) {
stop(); stop();
throw new RuntimeException("attempted pull action for empty stack"); throw new RuntimeException("attempted pull action for empty stack");
} }
return stack.pop(); return stack.pop();
}; };
public int getMemSize(){ public int getMemSize() {
int memSize = 0; int memSize = 0;
if (memory != null) memSize = memory.limit(); if (memory != null)
memSize = memory.limit();
return memSize; return memSize;
} }
public void memorySave(DataWord addrB, DataWord value){ public void memorySave(DataWord addrB, DataWord value) {
memorySave(addrB.data, value.data); memorySave(addrB.data, value.data);
} }
public void memorySave(byte[] addr, byte[] value){ public void memorySave(byte[] addr, byte[] value) {
int address = new BigInteger(1, addr).intValue(); int address = new BigInteger(1, addr).intValue();
allocateMemory(address, value); allocateMemory(address, value);
@ -131,42 +135,43 @@ public class Program {
System.arraycopy(value, 0, memory.array(), address, value.length); System.arraycopy(value, 0, memory.array(), address, value.length);
} }
public DataWord memoryLoad(DataWord addr){ public DataWord memoryLoad(DataWord addr) {
int address = new BigInteger(1, addr.getData()).intValue(); int address = new BigInteger(1, addr.getData()).intValue();
allocateMemory(address, DataWord.ZERO.data); allocateMemory(address, DataWord.ZERO.data);
byte[] data = new byte[32]; byte[] data = new byte[32];
System.arraycopy(memory.array(), address, data , 0 ,32); System.arraycopy(memory.array(), address, data, 0, 32);
return new DataWord(data); return new DataWord(data);
} }
public ByteBuffer memoryChunk(DataWord offsetData, DataWord sizeData){ public ByteBuffer memoryChunk(DataWord offsetData, DataWord sizeData) {
int offset = offsetData.value().intValue(); int offset = offsetData.value().intValue();
int size = sizeData.value().intValue(); int size = sizeData.value().intValue();
byte[] chunk = new byte[size]; byte[] chunk = new byte[size];
if (memory.limit() < offset + size) size = memory.limit() - offset; if (memory.limit() < offset + size)
size = memory.limit() - offset;
System.arraycopy(memory.array(), offset, chunk, 0, size); System.arraycopy(memory.array(), offset, chunk, 0, size);
return ByteBuffer.wrap(chunk); return ByteBuffer.wrap(chunk);
} }
private void allocateMemory(int address, byte[] value) {
private void allocateMemory(int address, byte[] value){
int memSize = 0; int memSize = 0;
if (memory != null) memSize = memory.limit(); if (memory != null)
memSize = memory.limit();
// check if you need to allocate // check if you need to allocate
if (memSize < (address + value.length)){ if (memSize < (address + value.length)) {
int sizeToAllocate = 0; int sizeToAllocate = 0;
if (memSize > address){ if (memSize > address) {
sizeToAllocate = memSize + value.length; sizeToAllocate = memSize + value.length;
} else { } else {
@ -174,133 +179,147 @@ public class Program {
} }
// complete to 32 // complete to 32
sizeToAllocate = (sizeToAllocate % 32)==0 ? sizeToAllocate : sizeToAllocate = (sizeToAllocate % 32) == 0 ? sizeToAllocate
sizeToAllocate + (32 - sizeToAllocate % 32); : sizeToAllocate + (32 - sizeToAllocate % 32);
sizeToAllocate = (sizeToAllocate == 0)? 32: sizeToAllocate; sizeToAllocate = (sizeToAllocate == 0) ? 32 : sizeToAllocate;
ByteBuffer tmpMem = ByteBuffer.allocate(sizeToAllocate); ByteBuffer tmpMem = ByteBuffer.allocate(sizeToAllocate);
if (memory != null) if (memory != null)
System.arraycopy(memory.array(), 0, tmpMem.array(), 0, memory.limit()); System.arraycopy(memory.array(), 0, tmpMem.array(), 0,
memory.limit());
memory = tmpMem; memory = tmpMem;
} }
} }
public void spendGas(int gasValue) {
public void spendGas(int gasValue){
// todo: check it against avail gas // todo: check it against avail gas
// todo: out of gas will revert the changes [YP 5, 6 ] // todo: out of gas will revert the changes [YP 5, 6 ]
spendGas += gasValue; spendGas += gasValue;
} }
public void storageSave(DataWord word1, DataWord word2){ public void storageSave(DataWord word1, DataWord word2) {
storageSave(word1.getData(), word2.getData()); storageSave(word1.getData(), word2.getData());
} }
public void storageSave(byte[] key, byte[] val){ public void storageSave(byte[] key, byte[] val) {
DataWord keyWord = new DataWord(key); DataWord keyWord = new DataWord(key);
DataWord valWord = new DataWord(val); DataWord valWord = new DataWord(val);
storage.put(keyWord, valWord); storage.put(keyWord, valWord);
} }
public DataWord getOwnerAddress() {
public DataWord getOwnerAddress(){ if (invokeData == null)
if (invokeData == null) return new DataWord( new byte[0]); return new DataWord(new byte[0]);
return invokeData.getOwnerAddress(); return invokeData.getOwnerAddress();
} }
public DataWord getBalance(){ public DataWord getBalance() {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getBalance(); return invokeData.getBalance();
} }
public DataWord getOriginAddress(){ public DataWord getOriginAddress() {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getOriginAddress(); return invokeData.getOriginAddress();
} }
public DataWord getCallerAddress(){ public DataWord getCallerAddress() {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getCallerAddress(); return invokeData.getCallerAddress();
} }
public DataWord getMinGasPrice(){ public DataWord getMinGasPrice() {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getMinGasPrice(); return invokeData.getMinGasPrice();
} }
public DataWord getCallValue(){ public DataWord getCallValue() {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getCallValue(); return invokeData.getCallValue();
} }
public DataWord getDataSize() {
public DataWord getDataSize(){ if (invokeData == null)
if (invokeData == null) return new DataWord( new byte[0]); return new DataWord(new byte[0]);
return invokeData.getDataSize(); return invokeData.getDataSize();
} }
public DataWord getDataValue(DataWord index){ public DataWord getDataValue(DataWord index) {
if (invokeData == null) return new DataWord( new byte[0]); if (invokeData == null)
return new DataWord(new byte[0]);
return invokeData.getDataValue(index); return invokeData.getDataValue(index);
} }
public byte[] getDataCopy(DataWord offset, DataWord length){ public byte[] getDataCopy(DataWord offset, DataWord length) {
if (invokeData == null) return new byte[0]; if (invokeData == null)
return new byte[0];
return invokeData.getDataCopy(offset, length); return invokeData.getDataCopy(offset, length);
} }
public DataWord storageLoad(DataWord key){ public DataWord storageLoad(DataWord key) {
return storage.get(key); return storage.get(key);
} }
public void fullTrace() {
public void fullTrace(){
// todo: add gas to full trace calc // todo: add gas to full trace calc
if (logger.isDebugEnabled()){ if (logger.isDebugEnabled()) {
StringBuilder stackData = new StringBuilder(); StringBuilder stackData = new StringBuilder();
for (int i = 0; i < stack.size(); ++i){ for (int i = 0; i < stack.size(); ++i) {
stackData.append(" ").append(stack.get(i)); stackData.append(" ").append(stack.get(i));
if (i < stack.size() - 1) stackData.append("\n"); if (i < stack.size() - 1)
stackData.append("\n");
} }
if (stackData.length() > 0) stackData.insert(0, "\n"); if (stackData.length() > 0)
stackData.insert(0, "\n");
StringBuilder storageData = new StringBuilder(); StringBuilder storageData = new StringBuilder();
for (DataWord key : storage.keySet()){ for (DataWord key : storage.keySet()) {
storageData.append(" ").append(key).append(" -> ").append(storage.get(key)).append("\n"); storageData.append(" ").append(key).append(" -> ")
.append(storage.get(key)).append("\n");
} }
if (storageData.length() > 0) storageData.insert(0, "\n"); if (storageData.length() > 0)
storageData.insert(0, "\n");
StringBuilder memoryData = new StringBuilder(); StringBuilder memoryData = new StringBuilder();
StringBuilder oneLine = new StringBuilder(); StringBuilder oneLine = new StringBuilder();
for (int i = 0; memory != null && i < memory.limit(); ++i){ for (int i = 0; memory != null && i < memory.limit(); ++i) {
byte value = memory.get(i); byte value = memory.get(i);
oneLine.append(Utils.oneByteToHexString(value)).append(" "); oneLine.append(Utils.oneByteToHexString(value)).append(" ");
if ((i + 1) % 16 == 0) { if ((i + 1) % 16 == 0) {
String tmp = String.format("[%4s]-[%4s]", Integer.toString(i - 15, 16), String tmp = String.format("[%4s]-[%4s]",
Integer.toString(i - 15, 16),
Integer.toString(i, 16)).replace(" ", "0"); Integer.toString(i, 16)).replace(" ", "0");
memoryData.append("" ).append(tmp).append(" "); memoryData.append("").append(tmp).append(" ");
memoryData.append(oneLine); memoryData.append(oneLine);
if (i < memory.limit()) memoryData.append("\n"); if (i < memory.limit())
memoryData.append("\n");
oneLine.setLength(0); oneLine.setLength(0);
} }
} }
if (memoryData.length() > 0) memoryData.insert(0, "\n"); if (memoryData.length() > 0)
memoryData.insert(0, "\n");
StringBuilder opsString = new StringBuilder(); StringBuilder opsString = new StringBuilder();
for (int i = 0; i < ops.length; ++i){ for (int i = 0; i < ops.length; ++i) {
String tmpString = Integer.toString(ops[i] & 0xFF, 16); String tmpString = Integer.toString(ops[i] & 0xFF, 16);
tmpString = tmpString.length() == 1? "0" + tmpString : tmpString; tmpString = tmpString.length() == 1 ? "0" + tmpString
: tmpString;
if (i != pc) if (i != pc)
opsString.append(tmpString); opsString.append(tmpString);
@ -308,39 +327,41 @@ public class Program {
opsString.append(" >>").append(tmpString).append(""); opsString.append(" >>").append(tmpString).append("");
} }
if (pc >= ops.length) opsString.append(" >>"); if (pc >= ops.length)
if (opsString.length() > 0) opsString.insert(0, "\n "); opsString.append(" >>");
if (opsString.length() > 0)
opsString.insert(0, "\n ");
logger.debug(" -- OPS -- {}", opsString); logger.debug(" -- OPS -- {}", opsString);
logger.debug(" -- STACK -- {}", stackData); logger.debug(" -- STACK -- {}", stackData);
logger.debug(" -- MEMORY -- {}", memoryData); logger.debug(" -- MEMORY -- {}", memoryData);
logger.debug(" -- STORAGE -- {}\n", storageData); logger.debug(" -- STORAGE -- {}\n", storageData);
StringBuilder global = new StringBuilder("\n"); StringBuilder global = new StringBuilder("\n");
if (stackData.length() > 0) stackData.append("\n"); if (stackData.length() > 0)
stackData.append("\n");
global.append(" -- OPS -- ").append(opsString).append("\n"); global.append(" -- OPS -- ").append(opsString).append("\n");
global.append(" -- STACK -- ").append(stackData).append("\n"); global.append(" -- STACK -- ").append(stackData).append("\n");
global.append(" -- MEMORY -- ").append(memoryData).append("\n"); global.append(" -- MEMORY -- ").append(memoryData).append("\n");
global.append(" -- STORAGE -- ").append(storageData).append("\n"); global.append(" -- STORAGE -- ").append(storageData).append("\n");
if (hReturn != null){ if (hReturn != null) {
global.append("\n HReturn: ").append(Hex.toHexString(hReturn.array())); global.append("\n HReturn: ").append(
Hex.toHexString(hReturn.array()));
} }
if (listener != null){ if (listener != null) {
listener.output(global.toString()); listener.output(global.toString());
} }
}
};
} }
public void addListener(ProgramListener listener){ public void addListener(ProgramListener listener) {
this.listener = listener; this.listener = listener;
} }
public interface ProgramListener{ public interface ProgramListener {
public void output(String out); public void output(String out);
} }
} }

View File

@ -1,5 +1,9 @@
package org.ethereum.core; package org.ethereum.core;
import static org.junit.Assert.*;
import java.math.BigInteger;
import org.ethereum.crypto.HashUtil; import org.ethereum.crypto.HashUtil;
import org.ethereum.trie.MockDB; import org.ethereum.trie.MockDB;
import org.ethereum.trie.Trie; import org.ethereum.trie.Trie;
@ -7,10 +11,6 @@ import org.ethereum.util.RLP;
import org.junit.Test; import org.junit.Test;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
public class StateTest { public class StateTest {
@Test @Test
@ -19,9 +19,8 @@ public class StateTest {
assertEquals("23b503734ff34ddb7bd5e478f1645680ec778ab3f90007cb1c854653693e5adc", Hex.toHexString(trie.getRootHash())); assertEquals("23b503734ff34ddb7bd5e478f1645680ec778ab3f90007cb1c854653693e5adc", Hex.toHexString(trie.getRootHash()));
} }
@Test // right way to calc tx trie hash @Test // right way to calc tx trie hash
public void testCalculatePostTxState(){ public void testCalculatePostTxState() {
/* txTrieHash=a77691cf47bec9021d3f027fc8ef2d51b758b600a79967154354b8e37108896f */ /* txTrieHash=a77691cf47bec9021d3f027fc8ef2d51b758b600a79967154354b8e37108896f */
String expected = "a77691cf47bec9021d3f027fc8ef2d51b758b600a79967154354b8e37108896f"; String expected = "a77691cf47bec9021d3f027fc8ef2d51b758b600a79967154354b8e37108896f";
@ -82,12 +81,8 @@ public class StateTest {
*/ */
} }
@Test // calc state after applying first tx on genesis @Test // calc state after applying first tx on genesis
public void test2(){ public void test2() {
// explanation: // explanation:
// 0) create genesis // 0) create genesis
@ -99,24 +94,28 @@ public class StateTest {
Trie trie = generateGenesis(); Trie trie = generateGenesis();
String expected = "69c21ff84a5af0b53b11c61110a16d6ad43dad37b3eb29ae8e88c936eb06456a"; String expected = "69c21ff84a5af0b53b11c61110a16d6ad43dad37b3eb29ae8e88c936eb06456a";
byte[] data = trie.get(Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826")); // Get and update sender in world state
AccountState account_1 = new AccountState(data); byte[] cowAddress = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826");
byte[] rlpEncodedState = trie.get(cowAddress);
AccountState account_1 = new AccountState(rlpEncodedState);
account_1.addToBalance(new BigInteger("-6260000000001000")); account_1.addToBalance(new BigInteger("-6260000000001000"));
account_1.incrementNonce(); account_1.incrementNonce();
trie.update(Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"), account_1.getEncoded()); trie.update(cowAddress, account_1.getEncoded());
String code = "61778e600054"; // Add contract to world state
byte[] codeData = Hex.decode(code); byte[] codeData = Hex.decode("61778e600054");
AccountState account_2 = new AccountState(BigInteger.ZERO, new BigInteger("1000")); AccountState account_2 = new AccountState(BigInteger.ZERO, BigInteger.valueOf(1000));
account_2.setCodeHash(HashUtil.sha3(codeData)); account_2.setCodeHash(HashUtil.sha3(codeData));
trie.update(Hex.decode("77045e71a7a2c50903d88e564cd72fab11e82051"), account_2.getEncoded()); byte[] contractAddress = Hex.decode("77045e71a7a2c50903d88e564cd72fab11e82051"); // generated based on sender + nonce
trie.update(contractAddress, account_2.getEncoded());
// this is saved in the db // this is saved in the db
// trie.update(HashUtil.sha3(codeData), codeData); // trie.update(HashUtil.sha3(codeData), codeData);
// Update miner in world state
byte[] minerAddress = Hex.decode("4c5f4d519dff3c16f0d54b6866e256fbbbc1a600");
AccountState account_3 = new AccountState(BigInteger.ZERO, new BigInteger("1506260000000000000")); AccountState account_3 = new AccountState(BigInteger.ZERO, new BigInteger("1506260000000000000"));
trie.update(Hex.decode("4c5f4d519dff3c16f0d54b6866e256fbbbc1a600"), account_3.getEncoded()); trie.update(minerAddress, account_3.getEncoded());
assertEquals(expected, Hex.toHexString(trie.getRootHash())); assertEquals(expected, Hex.toHexString(trie.getRootHash()));
@ -155,11 +154,10 @@ public class StateTest {
* cd2a3d9f938e13cd947ec05abc7fe734df8dd826: #1 1606938044258990275541962092341162602522202987522792835300376 (-6260000000001000) * cd2a3d9f938e13cd947ec05abc7fe734df8dd826: #1 1606938044258990275541962092341162602522202987522792835300376 (-6260000000001000)
*/ */
assertEquals("69c21ff84a5af0b53b11c61110a16d6ad43dad37b3eb29ae8e88c936eb06456a", Hex.toHexString(trie.getRootHash()));
} }
private Trie generateGenesis() {
private Trie generateGenesis(){
Trie trie = new Trie(new MockDB()); Trie trie = new Trie(new MockDB());
// 2ef47100e0787b915105fd5e3f4ff6752079d5cb # (M) // 2ef47100e0787b915105fd5e3f4ff6752079d5cb # (M)
@ -195,8 +193,5 @@ public class StateTest {
trie.update(Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"), acct6.getEncoded()); trie.update(Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"), acct6.getEncoded());
return trie; return trie;
} }
} }

View File

@ -10,7 +10,7 @@ import org.spongycastle.util.encoders.Hex;
* Created on: 03/06/2014 15:00 * Created on: 03/06/2014 15:00
*/ */
public class ProgramInvokeMockImpl implements ProgramInvoke{ public class ProgramInvokeMockImpl implements ProgramInvoke {
byte[] msgData; byte[] msgData;
@ -19,7 +19,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke{
this.msgData = msgDataRaw; this.msgData = msgDataRaw;
} }
ProgramInvokeMockImpl() { public ProgramInvokeMockImpl() {
} }
/* ADDRESS op */ /* ADDRESS op */