Merge small changes

This commit is contained in:
nicksavers 2014-06-07 10:04:19 +02:00
parent 11cbb3c1b6
commit a3f2206d51
6 changed files with 323 additions and 299 deletions

View File

@ -49,14 +49,14 @@ public class AccountState {
this(ecKey, BigInteger.ZERO, BigInteger.ZERO);
}
public AccountState(byte[] rlpData){
public AccountState(byte[] rlpData) {
this.rlpEncoded = rlpData;
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.balance = new BigInteger(1, items.get(1).getRLPData());
this.stateRoot = items.get(2).getRLPData();
this.codeHash = items.get(3).getRLPData();
RLPList items = (RLPList) RLP.decode2(rlpEncoded).get(0);
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.stateRoot = items.get(2).getRLPData();
this.codeHash = items.get(3).getRLPData();
}
public AccountState(ECKey ecKey, BigInteger nonce, BigInteger balance) {
@ -88,7 +88,7 @@ public class AccountState {
this.codeHash = codeHash;
}
public BigInteger getBalance() {
public BigInteger getBalance() {
return balance;
}

View File

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

View File

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

View File

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

View File

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

View File

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